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/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.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> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 STATISTIC(NumTailCalls, "Number of tail calls");
125 STATISTIC(NumSiblingCalls, "Number of sibling calls");
126 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
127 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
128 
129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
130 
131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
132 
133 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
134 
135 // FIXME: Remove this once the bug has been fixed!
136 extern cl::opt<bool> ANDIGlueBug;
137 
138 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
139                                      const PPCSubtarget &STI)
140     : TargetLowering(TM), Subtarget(STI) {
141   // Initialize map that relates the PPC addressing modes to the computed flags
142   // of a load/store instruction. The map is used to determine the optimal
143   // addressing mode when selecting load and stores.
144   initializeAddrModeMap();
145   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
146   // arguments are at least 4/8 bytes aligned.
147   bool isPPC64 = Subtarget.isPPC64();
148   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
149 
150   // Set up the register classes.
151   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
152   if (!useSoftFloat()) {
153     if (hasSPE()) {
154       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
155       // EFPU2 APU only supports f32
156       if (!Subtarget.hasEFPU2())
157         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
158     } else {
159       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
160       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
161     }
162   }
163 
164   // Match BITREVERSE to customized fast code sequence in the td file.
165   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
166   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
167 
168   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
169   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
170 
171   // Custom lower inline assembly to check for special registers.
172   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
173   setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
174 
175   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
176   for (MVT VT : MVT::integer_valuetypes()) {
177     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
178     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
179   }
180 
181   if (Subtarget.isISA3_0()) {
182     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
183     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
184     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
185     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
186   } else {
187     // No extending loads from f16 or HW conversions back and forth.
188     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
189     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
190     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
191     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
192     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
193     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
194     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
195     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
196   }
197 
198   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
199 
200   // PowerPC has pre-inc load and store's.
201   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
202   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
203   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
204   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
205   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
206   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
207   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
208   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
209   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
210   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
211   if (!Subtarget.hasSPE()) {
212     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
213     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
214     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
215     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
216   }
217 
218   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
219   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
220   for (MVT VT : ScalarIntVTs) {
221     setOperationAction(ISD::ADDC, VT, Legal);
222     setOperationAction(ISD::ADDE, VT, Legal);
223     setOperationAction(ISD::SUBC, VT, Legal);
224     setOperationAction(ISD::SUBE, VT, Legal);
225   }
226 
227   if (Subtarget.useCRBits()) {
228     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
229 
230     if (isPPC64 || Subtarget.hasFPCVT()) {
231       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
232       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
233                         isPPC64 ? MVT::i64 : MVT::i32);
234       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
235       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
236                         isPPC64 ? MVT::i64 : MVT::i32);
237 
238       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
239       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
240                          isPPC64 ? MVT::i64 : MVT::i32);
241       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
242       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
243                         isPPC64 ? MVT::i64 : MVT::i32);
244 
245       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
246       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
247                         isPPC64 ? MVT::i64 : MVT::i32);
248       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
249       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
250                         isPPC64 ? MVT::i64 : MVT::i32);
251 
252       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
253       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
254                         isPPC64 ? MVT::i64 : MVT::i32);
255       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
256       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
257                         isPPC64 ? MVT::i64 : MVT::i32);
258     } else {
259       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
260       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
261       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
262       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
263     }
264 
265     // PowerPC does not support direct load/store of condition registers.
266     setOperationAction(ISD::LOAD, MVT::i1, Custom);
267     setOperationAction(ISD::STORE, MVT::i1, Custom);
268 
269     // FIXME: Remove this once the ANDI glue bug is fixed:
270     if (ANDIGlueBug)
271       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
272 
273     for (MVT VT : MVT::integer_valuetypes()) {
274       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
275       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
276       setTruncStoreAction(VT, MVT::i1, Expand);
277     }
278 
279     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
280   }
281 
282   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
283   // PPC (the libcall is not available).
284   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
285   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
286   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
287   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
288 
289   // We do not currently implement these libm ops for PowerPC.
290   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
291   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
292   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
293   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
294   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
295   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
296 
297   // PowerPC has no SREM/UREM instructions unless we are on P9
298   // On P9 we may use a hardware instruction to compute the remainder.
299   // When the result of both the remainder and the division is required it is
300   // more efficient to compute the remainder from the result of the division
301   // rather than use the remainder instruction. The instructions are legalized
302   // directly because the DivRemPairsPass performs the transformation at the IR
303   // level.
304   if (Subtarget.isISA3_0()) {
305     setOperationAction(ISD::SREM, MVT::i32, Legal);
306     setOperationAction(ISD::UREM, MVT::i32, Legal);
307     setOperationAction(ISD::SREM, MVT::i64, Legal);
308     setOperationAction(ISD::UREM, MVT::i64, Legal);
309   } else {
310     setOperationAction(ISD::SREM, MVT::i32, Expand);
311     setOperationAction(ISD::UREM, MVT::i32, Expand);
312     setOperationAction(ISD::SREM, MVT::i64, Expand);
313     setOperationAction(ISD::UREM, MVT::i64, Expand);
314   }
315 
316   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
317   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
318   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
319   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
320   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
321   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
322   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
323   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
324   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
325 
326   // Handle constrained floating-point operations of scalar.
327   // TODO: Handle SPE specific operation.
328   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
329   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
330   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
331   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
332   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
333 
334   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
335   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
336   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
337   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
338 
339   if (!Subtarget.hasSPE()) {
340     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
341     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
342   }
343 
344   if (Subtarget.hasVSX()) {
345     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
346     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
347   }
348 
349   if (Subtarget.hasFSQRT()) {
350     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
352   }
353 
354   if (Subtarget.hasFPRND()) {
355     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
357     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
358     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
359 
360     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
361     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
362     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
363     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
364   }
365 
366   // We don't support sin/cos/sqrt/fmod/pow
367   setOperationAction(ISD::FSIN , MVT::f64, Expand);
368   setOperationAction(ISD::FCOS , MVT::f64, Expand);
369   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
370   setOperationAction(ISD::FREM , MVT::f64, Expand);
371   setOperationAction(ISD::FPOW , MVT::f64, Expand);
372   setOperationAction(ISD::FSIN , MVT::f32, Expand);
373   setOperationAction(ISD::FCOS , MVT::f32, Expand);
374   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
375   setOperationAction(ISD::FREM , MVT::f32, Expand);
376   setOperationAction(ISD::FPOW , MVT::f32, Expand);
377   if (Subtarget.hasSPE()) {
378     setOperationAction(ISD::FMA  , MVT::f64, Expand);
379     setOperationAction(ISD::FMA  , MVT::f32, Expand);
380   } else {
381     setOperationAction(ISD::FMA  , MVT::f64, Legal);
382     setOperationAction(ISD::FMA  , MVT::f32, Legal);
383   }
384 
385   if (Subtarget.hasSPE())
386     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
387 
388   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
389 
390   // If we're enabling GP optimizations, use hardware square root
391   if (!Subtarget.hasFSQRT() &&
392       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
393         Subtarget.hasFRE()))
394     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
395 
396   if (!Subtarget.hasFSQRT() &&
397       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
398         Subtarget.hasFRES()))
399     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
400 
401   if (Subtarget.hasFCPSGN()) {
402     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
403     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
404   } else {
405     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
406     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
407   }
408 
409   if (Subtarget.hasFPRND()) {
410     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
411     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
412     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
413     setOperationAction(ISD::FROUND, MVT::f64, Legal);
414 
415     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
416     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
417     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
418     setOperationAction(ISD::FROUND, MVT::f32, Legal);
419   }
420 
421   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
422   // to speed up scalar BSWAP64.
423   // CTPOP or CTTZ were introduced in P8/P9 respectively
424   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
425   if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
426     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
427   else
428     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
429   if (Subtarget.isISA3_0()) {
430     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
431     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
432   } else {
433     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
434     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
435   }
436 
437   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
438     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
439     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
440   } else {
441     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
442     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
443   }
444 
445   // PowerPC does not have ROTR
446   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
447   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
448 
449   if (!Subtarget.useCRBits()) {
450     // PowerPC does not have Select
451     setOperationAction(ISD::SELECT, MVT::i32, Expand);
452     setOperationAction(ISD::SELECT, MVT::i64, Expand);
453     setOperationAction(ISD::SELECT, MVT::f32, Expand);
454     setOperationAction(ISD::SELECT, MVT::f64, Expand);
455   }
456 
457   // PowerPC wants to turn select_cc of FP into fsel when possible.
458   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
459   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
460 
461   // PowerPC wants to optimize integer setcc a bit
462   if (!Subtarget.useCRBits())
463     setOperationAction(ISD::SETCC, MVT::i32, Custom);
464 
465   if (Subtarget.hasFPU()) {
466     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
467     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
468     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
469 
470     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
471     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
472     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
473   }
474 
475   // PowerPC does not have BRCOND which requires SetCC
476   if (!Subtarget.useCRBits())
477     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
478 
479   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
480 
481   if (Subtarget.hasSPE()) {
482     // SPE has built-in conversions
483     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
484     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
485     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
486     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
487     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
488     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
489 
490     // SPE supports signaling compare of f32/f64.
491     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
492     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
493   } else {
494     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
495     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
496     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
497 
498     // PowerPC does not have [U|S]INT_TO_FP
499     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
500     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
501     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
502     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
503   }
504 
505   if (Subtarget.hasDirectMove() && isPPC64) {
506     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
507     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
508     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
509     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
510     if (TM.Options.UnsafeFPMath) {
511       setOperationAction(ISD::LRINT, MVT::f64, Legal);
512       setOperationAction(ISD::LRINT, MVT::f32, Legal);
513       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
514       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
515       setOperationAction(ISD::LROUND, MVT::f64, Legal);
516       setOperationAction(ISD::LROUND, MVT::f32, Legal);
517       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
518       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
519     }
520   } else {
521     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
522     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
523     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
524     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
525   }
526 
527   // We cannot sextinreg(i1).  Expand to shifts.
528   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
529 
530   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
531   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
532   // support continuation, user-level threading, and etc.. As a result, no
533   // other SjLj exception interfaces are implemented and please don't build
534   // your own exception handling based on them.
535   // LLVM/Clang supports zero-cost DWARF exception handling.
536   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
537   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
538 
539   // We want to legalize GlobalAddress and ConstantPool nodes into the
540   // appropriate instructions to materialize the address.
541   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
542   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
543   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
544   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
545   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
546   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
547   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
549   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
550   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
551 
552   // TRAP is legal.
553   setOperationAction(ISD::TRAP, MVT::Other, Legal);
554 
555   // TRAMPOLINE is custom lowered.
556   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558 
559   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
560   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
561 
562   if (Subtarget.is64BitELFABI()) {
563     // VAARG always uses double-word chunks, so promote anything smaller.
564     setOperationAction(ISD::VAARG, MVT::i1, Promote);
565     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
566     setOperationAction(ISD::VAARG, MVT::i8, Promote);
567     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
568     setOperationAction(ISD::VAARG, MVT::i16, Promote);
569     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
570     setOperationAction(ISD::VAARG, MVT::i32, Promote);
571     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
572     setOperationAction(ISD::VAARG, MVT::Other, Expand);
573   } else if (Subtarget.is32BitELFABI()) {
574     // VAARG is custom lowered with the 32-bit SVR4 ABI.
575     setOperationAction(ISD::VAARG, MVT::Other, Custom);
576     setOperationAction(ISD::VAARG, MVT::i64, Custom);
577   } else
578     setOperationAction(ISD::VAARG, MVT::Other, Expand);
579 
580   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
581   if (Subtarget.is32BitELFABI())
582     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
583   else
584     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
585 
586   // Use the default implementation.
587   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
588   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
589   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
590   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
591   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
592   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
593   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
594   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
595   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
596 
597   // We want to custom lower some of our intrinsics.
598   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
599 
600   // To handle counter-based loop conditions.
601   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
602 
603   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
604   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
605   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
606   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
607 
608   // Comparisons that require checking two conditions.
609   if (Subtarget.hasSPE()) {
610     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
611     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
612     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
613     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
614   }
615   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
616   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
617   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
618   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
619   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
620   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
621   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
622   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
623   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
624   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
625   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
626   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
627 
628   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
629   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
630 
631   if (Subtarget.has64BitSupport()) {
632     // They also have instructions for converting between i64 and fp.
633     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
634     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
635     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
636     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
637     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
638     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
639     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
640     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
641     // This is just the low 32 bits of a (signed) fp->i64 conversion.
642     // We cannot do this with Promote because i64 is not a legal type.
643     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
645 
646     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
647       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
648       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
649     }
650   } else {
651     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
652     if (Subtarget.hasSPE()) {
653       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
654       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
655     } else {
656       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
657       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
658     }
659   }
660 
661   // With the instructions enabled under FPCVT, we can do everything.
662   if (Subtarget.hasFPCVT()) {
663     if (Subtarget.has64BitSupport()) {
664       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
665       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
666       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
667       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
668       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
669       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
670       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
671       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
672     }
673 
674     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
675     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
676     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
677     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
678     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
679     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
680     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
681     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
682   }
683 
684   if (Subtarget.use64BitRegs()) {
685     // 64-bit PowerPC implementations can support i64 types directly
686     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
687     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
688     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
689     // 64-bit PowerPC wants to expand i128 shifts itself.
690     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
691     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
692     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
693   } else {
694     // 32-bit PowerPC wants to expand i64 shifts itself.
695     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
696     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
697     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
698   }
699 
700   // PowerPC has better expansions for funnel shifts than the generic
701   // TargetLowering::expandFunnelShift.
702   if (Subtarget.has64BitSupport()) {
703     setOperationAction(ISD::FSHL, MVT::i64, Custom);
704     setOperationAction(ISD::FSHR, MVT::i64, Custom);
705   }
706   setOperationAction(ISD::FSHL, MVT::i32, Custom);
707   setOperationAction(ISD::FSHR, MVT::i32, Custom);
708 
709   if (Subtarget.hasVSX()) {
710     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
711     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
712     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
713     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
714   }
715 
716   if (Subtarget.hasAltivec()) {
717     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
718       setOperationAction(ISD::SADDSAT, VT, Legal);
719       setOperationAction(ISD::SSUBSAT, VT, Legal);
720       setOperationAction(ISD::UADDSAT, VT, Legal);
721       setOperationAction(ISD::USUBSAT, VT, Legal);
722     }
723     // First set operation action for all vector types to expand. Then we
724     // will selectively turn on ones that can be effectively codegen'd.
725     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
726       // add/sub are legal for all supported vector VT's.
727       setOperationAction(ISD::ADD, VT, Legal);
728       setOperationAction(ISD::SUB, VT, Legal);
729 
730       // For v2i64, these are only valid with P8Vector. This is corrected after
731       // the loop.
732       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
733         setOperationAction(ISD::SMAX, VT, Legal);
734         setOperationAction(ISD::SMIN, VT, Legal);
735         setOperationAction(ISD::UMAX, VT, Legal);
736         setOperationAction(ISD::UMIN, VT, Legal);
737       }
738       else {
739         setOperationAction(ISD::SMAX, VT, Expand);
740         setOperationAction(ISD::SMIN, VT, Expand);
741         setOperationAction(ISD::UMAX, VT, Expand);
742         setOperationAction(ISD::UMIN, VT, Expand);
743       }
744 
745       if (Subtarget.hasVSX()) {
746         setOperationAction(ISD::FMAXNUM, VT, Legal);
747         setOperationAction(ISD::FMINNUM, VT, Legal);
748       }
749 
750       // Vector instructions introduced in P8
751       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
752         setOperationAction(ISD::CTPOP, VT, Legal);
753         setOperationAction(ISD::CTLZ, VT, Legal);
754       }
755       else {
756         setOperationAction(ISD::CTPOP, VT, Expand);
757         setOperationAction(ISD::CTLZ, VT, Expand);
758       }
759 
760       // Vector instructions introduced in P9
761       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
762         setOperationAction(ISD::CTTZ, VT, Legal);
763       else
764         setOperationAction(ISD::CTTZ, VT, Expand);
765 
766       // We promote all shuffles to v16i8.
767       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
768       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
769 
770       // We promote all non-typed operations to v4i32.
771       setOperationAction(ISD::AND   , VT, Promote);
772       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
773       setOperationAction(ISD::OR    , VT, Promote);
774       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
775       setOperationAction(ISD::XOR   , VT, Promote);
776       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
777       setOperationAction(ISD::LOAD  , VT, Promote);
778       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
779       setOperationAction(ISD::SELECT, VT, Promote);
780       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
781       setOperationAction(ISD::VSELECT, VT, Legal);
782       setOperationAction(ISD::SELECT_CC, VT, Promote);
783       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
784       setOperationAction(ISD::STORE, VT, Promote);
785       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
786 
787       // No other operations are legal.
788       setOperationAction(ISD::MUL , VT, Expand);
789       setOperationAction(ISD::SDIV, VT, Expand);
790       setOperationAction(ISD::SREM, VT, Expand);
791       setOperationAction(ISD::UDIV, VT, Expand);
792       setOperationAction(ISD::UREM, VT, Expand);
793       setOperationAction(ISD::FDIV, VT, Expand);
794       setOperationAction(ISD::FREM, VT, Expand);
795       setOperationAction(ISD::FNEG, VT, Expand);
796       setOperationAction(ISD::FSQRT, VT, Expand);
797       setOperationAction(ISD::FLOG, VT, Expand);
798       setOperationAction(ISD::FLOG10, VT, Expand);
799       setOperationAction(ISD::FLOG2, VT, Expand);
800       setOperationAction(ISD::FEXP, VT, Expand);
801       setOperationAction(ISD::FEXP2, VT, Expand);
802       setOperationAction(ISD::FSIN, VT, Expand);
803       setOperationAction(ISD::FCOS, VT, Expand);
804       setOperationAction(ISD::FABS, VT, Expand);
805       setOperationAction(ISD::FFLOOR, VT, Expand);
806       setOperationAction(ISD::FCEIL,  VT, Expand);
807       setOperationAction(ISD::FTRUNC, VT, Expand);
808       setOperationAction(ISD::FRINT,  VT, Expand);
809       setOperationAction(ISD::FNEARBYINT, VT, Expand);
810       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
811       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
812       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
813       setOperationAction(ISD::MULHU, VT, Expand);
814       setOperationAction(ISD::MULHS, VT, Expand);
815       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
816       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
817       setOperationAction(ISD::UDIVREM, VT, Expand);
818       setOperationAction(ISD::SDIVREM, VT, Expand);
819       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
820       setOperationAction(ISD::FPOW, VT, Expand);
821       setOperationAction(ISD::BSWAP, VT, Expand);
822       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
823       setOperationAction(ISD::ROTL, VT, Expand);
824       setOperationAction(ISD::ROTR, VT, Expand);
825 
826       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
827         setTruncStoreAction(VT, InnerVT, Expand);
828         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
829         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
830         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
831       }
832     }
833     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
834     if (!Subtarget.hasP8Vector()) {
835       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
836       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
837       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
838       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
839     }
840 
841     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
842     // with merges, splats, etc.
843     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
844 
845     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
846     // are cheap, so handle them before they get expanded to scalar.
847     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
848     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
849     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
850     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
851     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
852 
853     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
854     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
855     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
856     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
857     setOperationAction(ISD::SELECT, MVT::v4i32,
858                        Subtarget.useCRBits() ? Legal : Expand);
859     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
860     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
861     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
862     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
863     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
864     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
865     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
866     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
867     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
868     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
869     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
870     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
871     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
872 
873     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
874     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
875     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
876     if (Subtarget.hasAltivec())
877       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
878         setOperationAction(ISD::ROTL, VT, Legal);
879     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
880     if (Subtarget.hasP8Altivec())
881       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
882 
883     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
884     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
885     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
886     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
887 
888     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
889     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
890 
891     if (Subtarget.hasVSX()) {
892       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
893       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
894       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
895     }
896 
897     if (Subtarget.hasP8Altivec())
898       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
899     else
900       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
901 
902     if (Subtarget.isISA3_1()) {
903       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
904       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
905       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
906       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
907       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
908       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
909       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
910       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
911       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
912       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
913       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
914       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
915       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
916       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
917       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
918       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
919       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
920       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
921     }
922 
923     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
924     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
925 
926     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
927     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
928 
929     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
930     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
931     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
932     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
933 
934     // Altivec does not contain unordered floating-point compare instructions
935     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
936     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
937     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
938     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
939 
940     if (Subtarget.hasVSX()) {
941       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
942       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
943       if (Subtarget.hasP8Vector()) {
944         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
945         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
946       }
947       if (Subtarget.hasDirectMove() && isPPC64) {
948         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
949         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
950         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
951         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
952         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
953         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
954         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
955         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
956       }
957       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
958 
959       // The nearbyint variants are not allowed to raise the inexact exception
960       // so we can only code-gen them with unsafe math.
961       if (TM.Options.UnsafeFPMath) {
962         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
963         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
964       }
965 
966       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
967       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
968       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
969       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
970       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
971       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
972       setOperationAction(ISD::FROUND, MVT::f64, Legal);
973       setOperationAction(ISD::FRINT, MVT::f64, Legal);
974 
975       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
976       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
977       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
978       setOperationAction(ISD::FROUND, MVT::f32, Legal);
979       setOperationAction(ISD::FRINT, MVT::f32, Legal);
980 
981       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
982       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
983 
984       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
985       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
986 
987       // Share the Altivec comparison restrictions.
988       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
989       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
990       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
991       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
992 
993       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
994       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
995 
996       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
997 
998       if (Subtarget.hasP8Vector())
999         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1000 
1001       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1002 
1003       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1004       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1005       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1006 
1007       if (Subtarget.hasP8Altivec()) {
1008         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1009         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1010         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1011 
1012         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1013         // SRL, but not for SRA because of the instructions available:
1014         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1015         // doing
1016         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1017         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1018         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1019 
1020         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1021       }
1022       else {
1023         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1024         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1025         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1026 
1027         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1028 
1029         // VSX v2i64 only supports non-arithmetic operations.
1030         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1031         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1032       }
1033 
1034       if (Subtarget.isISA3_1())
1035         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1036       else
1037         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1038 
1039       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1040       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1041       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1042       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1043 
1044       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1045 
1046       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1047       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1048       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1049       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1050       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1051       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1052       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1053       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1054 
1055       // Custom handling for partial vectors of integers converted to
1056       // floating point. We already have optimal handling for v2i32 through
1057       // the DAG combine, so those aren't necessary.
1058       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1059       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1060       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1061       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1062       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1063       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1064       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1065       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1066       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1067       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1068       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1069       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1070       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1071       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1072       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1073       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1074 
1075       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1076       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1077       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1078       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1079       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1080       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1081 
1082       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1083       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1084 
1085       // Handle constrained floating-point operations of vector.
1086       // The predictor is `hasVSX` because altivec instruction has
1087       // no exception but VSX vector instruction has.
1088       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1089       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1090       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1091       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1092       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1093       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1094       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1095       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1096       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1097       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1098       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1099       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1100       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1101 
1102       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1103       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1104       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1105       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1106       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1107       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1108       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1109       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1110       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1111       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1112       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1113       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1114       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1115 
1116       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1117       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1118 
1119       for (MVT FPT : MVT::fp_valuetypes())
1120         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1121 
1122       // Expand the SELECT to SELECT_CC
1123       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1124 
1125       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1126       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1127 
1128       // No implementation for these ops for PowerPC.
1129       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1130       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1131       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1132       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1133       setOperationAction(ISD::FREM, MVT::f128, Expand);
1134     }
1135 
1136     if (Subtarget.hasP8Altivec()) {
1137       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1138       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1139     }
1140 
1141     if (Subtarget.hasP9Vector()) {
1142       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1143       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1144 
1145       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1146       // SRL, but not for SRA because of the instructions available:
1147       // VS{RL} and VS{RL}O.
1148       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1149       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1150       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1151 
1152       setOperationAction(ISD::FADD, MVT::f128, Legal);
1153       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1154       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1155       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1156       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1157 
1158       setOperationAction(ISD::FMA, MVT::f128, Legal);
1159       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1160       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1161       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1162       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1163       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1164       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1165 
1166       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1167       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1168       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1169       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1170       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1171       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1172 
1173       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1174       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1175       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1176 
1177       // Handle constrained floating-point operations of fp128
1178       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1179       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1180       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1181       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1182       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1183       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1184       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1185       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1186       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1187       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1188       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1189       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1190       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1191       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1192       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1193       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1194       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1195       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1196       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1197       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1198     } else if (Subtarget.hasVSX()) {
1199       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1200       setOperationAction(ISD::STORE, MVT::f128, Promote);
1201 
1202       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1203       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1204 
1205       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1206       // fp_to_uint and int_to_fp.
1207       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1208       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1209 
1210       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1211       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1212       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1213       setOperationAction(ISD::FABS, MVT::f128, Expand);
1214       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1215       setOperationAction(ISD::FMA, MVT::f128, Expand);
1216       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1217 
1218       // Expand the fp_extend if the target type is fp128.
1219       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1220       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1221 
1222       // Expand the fp_round if the source type is fp128.
1223       for (MVT VT : {MVT::f32, MVT::f64}) {
1224         setOperationAction(ISD::FP_ROUND, VT, Custom);
1225         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1226       }
1227 
1228       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1229       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1230       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1231       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1232 
1233       // Lower following f128 select_cc pattern:
1234       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1235       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1236 
1237       // We need to handle f128 SELECT_CC with integer result type.
1238       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1239       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1240     }
1241 
1242     if (Subtarget.hasP9Altivec()) {
1243       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1244       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1245 
1246       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1247       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1248       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1249       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1250       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1251       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1252       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1253     }
1254 
1255     if (Subtarget.isISA3_1())
1256       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1257   }
1258 
1259   if (Subtarget.pairedVectorMemops()) {
1260     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1261     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1262     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1263   }
1264   if (Subtarget.hasMMA()) {
1265     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1266     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1267     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1268     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1269   }
1270 
1271   if (Subtarget.has64BitSupport())
1272     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1273 
1274   if (Subtarget.isISA3_1())
1275     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1276 
1277   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1278 
1279   if (!isPPC64) {
1280     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1281     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1282   }
1283 
1284   setBooleanContents(ZeroOrOneBooleanContent);
1285 
1286   if (Subtarget.hasAltivec()) {
1287     // Altivec instructions set fields to all zeros or all ones.
1288     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1289   }
1290 
1291   if (!isPPC64) {
1292     // These libcalls are not available in 32-bit.
1293     setLibcallName(RTLIB::SHL_I128, nullptr);
1294     setLibcallName(RTLIB::SRL_I128, nullptr);
1295     setLibcallName(RTLIB::SRA_I128, nullptr);
1296   }
1297 
1298   if (!isPPC64)
1299     setMaxAtomicSizeInBitsSupported(32);
1300 
1301   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1302 
1303   // We have target-specific dag combine patterns for the following nodes:
1304   setTargetDAGCombine(ISD::ADD);
1305   setTargetDAGCombine(ISD::SHL);
1306   setTargetDAGCombine(ISD::SRA);
1307   setTargetDAGCombine(ISD::SRL);
1308   setTargetDAGCombine(ISD::MUL);
1309   setTargetDAGCombine(ISD::FMA);
1310   setTargetDAGCombine(ISD::SINT_TO_FP);
1311   setTargetDAGCombine(ISD::BUILD_VECTOR);
1312   if (Subtarget.hasFPCVT())
1313     setTargetDAGCombine(ISD::UINT_TO_FP);
1314   setTargetDAGCombine(ISD::LOAD);
1315   setTargetDAGCombine(ISD::STORE);
1316   setTargetDAGCombine(ISD::BR_CC);
1317   if (Subtarget.useCRBits())
1318     setTargetDAGCombine(ISD::BRCOND);
1319   setTargetDAGCombine(ISD::BSWAP);
1320   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1321   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1322   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1323 
1324   setTargetDAGCombine(ISD::SIGN_EXTEND);
1325   setTargetDAGCombine(ISD::ZERO_EXTEND);
1326   setTargetDAGCombine(ISD::ANY_EXTEND);
1327 
1328   setTargetDAGCombine(ISD::TRUNCATE);
1329   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1330 
1331 
1332   if (Subtarget.useCRBits()) {
1333     setTargetDAGCombine(ISD::TRUNCATE);
1334     setTargetDAGCombine(ISD::SETCC);
1335     setTargetDAGCombine(ISD::SELECT_CC);
1336   }
1337 
1338   if (Subtarget.hasP9Altivec()) {
1339     setTargetDAGCombine(ISD::ABS);
1340     setTargetDAGCombine(ISD::VSELECT);
1341   }
1342 
1343   setLibcallName(RTLIB::LOG_F128, "logf128");
1344   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1345   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1346   setLibcallName(RTLIB::EXP_F128, "expf128");
1347   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1348   setLibcallName(RTLIB::SIN_F128, "sinf128");
1349   setLibcallName(RTLIB::COS_F128, "cosf128");
1350   setLibcallName(RTLIB::POW_F128, "powf128");
1351   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1352   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1353   setLibcallName(RTLIB::REM_F128, "fmodf128");
1354   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1355   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1356   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1357   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1358   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1359   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1360   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1361   setLibcallName(RTLIB::RINT_F128, "rintf128");
1362   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1363   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1364   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1365   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1366 
1367   // With 32 condition bits, we don't need to sink (and duplicate) compares
1368   // aggressively in CodeGenPrep.
1369   if (Subtarget.useCRBits()) {
1370     setHasMultipleConditionRegisters();
1371     setJumpIsExpensive();
1372   }
1373 
1374   setMinFunctionAlignment(Align(4));
1375 
1376   switch (Subtarget.getCPUDirective()) {
1377   default: break;
1378   case PPC::DIR_970:
1379   case PPC::DIR_A2:
1380   case PPC::DIR_E500:
1381   case PPC::DIR_E500mc:
1382   case PPC::DIR_E5500:
1383   case PPC::DIR_PWR4:
1384   case PPC::DIR_PWR5:
1385   case PPC::DIR_PWR5X:
1386   case PPC::DIR_PWR6:
1387   case PPC::DIR_PWR6X:
1388   case PPC::DIR_PWR7:
1389   case PPC::DIR_PWR8:
1390   case PPC::DIR_PWR9:
1391   case PPC::DIR_PWR10:
1392   case PPC::DIR_PWR_FUTURE:
1393     setPrefLoopAlignment(Align(16));
1394     setPrefFunctionAlignment(Align(16));
1395     break;
1396   }
1397 
1398   if (Subtarget.enableMachineScheduler())
1399     setSchedulingPreference(Sched::Source);
1400   else
1401     setSchedulingPreference(Sched::Hybrid);
1402 
1403   computeRegisterProperties(STI.getRegisterInfo());
1404 
1405   // The Freescale cores do better with aggressive inlining of memcpy and
1406   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1407   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1408       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1409     MaxStoresPerMemset = 32;
1410     MaxStoresPerMemsetOptSize = 16;
1411     MaxStoresPerMemcpy = 32;
1412     MaxStoresPerMemcpyOptSize = 8;
1413     MaxStoresPerMemmove = 32;
1414     MaxStoresPerMemmoveOptSize = 8;
1415   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1416     // The A2 also benefits from (very) aggressive inlining of memcpy and
1417     // friends. The overhead of a the function call, even when warm, can be
1418     // over one hundred cycles.
1419     MaxStoresPerMemset = 128;
1420     MaxStoresPerMemcpy = 128;
1421     MaxStoresPerMemmove = 128;
1422     MaxLoadsPerMemcmp = 128;
1423   } else {
1424     MaxLoadsPerMemcmp = 8;
1425     MaxLoadsPerMemcmpOptSize = 4;
1426   }
1427 
1428   IsStrictFPEnabled = true;
1429 
1430   // Let the subtarget (CPU) decide if a predictable select is more expensive
1431   // than the corresponding branch. This information is used in CGP to decide
1432   // when to convert selects into branches.
1433   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1434 }
1435 
1436 // *********************************** NOTE ************************************
1437 // For selecting load and store instructions, the addressing modes are defined
1438 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1439 // patterns to match the load the store instructions.
1440 //
1441 // The TD definitions for the addressing modes correspond to their respective
1442 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1443 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1444 // address mode flags of a particular node. Afterwards, the computed address
1445 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1446 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1447 // accordingly, based on the preferred addressing mode.
1448 //
1449 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1450 // MemOpFlags contains all the possible flags that can be used to compute the
1451 // optimal addressing mode for load and store instructions.
1452 // AddrMode contains all the possible load and store addressing modes available
1453 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1454 //
1455 // When adding new load and store instructions, it is possible that new address
1456 // flags may need to be added into MemOpFlags, and a new addressing mode will
1457 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1458 // of the minimal and main distinguishing address flags for the new load/store
1459 // instructions) will need to be added into initializeAddrModeMap() below.
1460 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1461 // need to be updated to account for selecting the optimal addressing mode.
1462 // *****************************************************************************
1463 /// Initialize the map that relates the different addressing modes of the load
1464 /// and store instructions to a set of flags. This ensures the load/store
1465 /// instruction is correctly matched during instruction selection.
1466 void PPCTargetLowering::initializeAddrModeMap() {
1467   AddrModesMap[PPC::AM_DForm] = {
1468       // LWZ, STW
1469       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1470       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1471       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1472       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1473       // LBZ, LHZ, STB, STH
1474       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1475       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1476       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1477       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1478       // LHA
1479       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1480       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1481       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1482       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1483       // LFS, LFD, STFS, STFD
1484       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1485       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1486       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1487       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1488   };
1489   AddrModesMap[PPC::AM_DSForm] = {
1490       // LWA
1491       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1492       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1493       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1494       // LD, STD
1495       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1496       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1497       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1498       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1499       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1500       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1501       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1502   };
1503   AddrModesMap[PPC::AM_DQForm] = {
1504       // LXV, STXV
1505       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1506       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1507       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1508       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10,
1509       PPC::MOF_NotAddNorCst | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10,
1510       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10,
1511   };
1512 }
1513 
1514 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1515 /// the desired ByVal argument alignment.
1516 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1517   if (MaxAlign == MaxMaxAlign)
1518     return;
1519   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1520     if (MaxMaxAlign >= 32 &&
1521         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1522       MaxAlign = Align(32);
1523     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1524              MaxAlign < 16)
1525       MaxAlign = Align(16);
1526   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1527     Align EltAlign;
1528     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1529     if (EltAlign > MaxAlign)
1530       MaxAlign = EltAlign;
1531   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1532     for (auto *EltTy : STy->elements()) {
1533       Align EltAlign;
1534       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1535       if (EltAlign > MaxAlign)
1536         MaxAlign = EltAlign;
1537       if (MaxAlign == MaxMaxAlign)
1538         break;
1539     }
1540   }
1541 }
1542 
1543 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1544 /// function arguments in the caller parameter area.
1545 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1546                                                   const DataLayout &DL) const {
1547   // 16byte and wider vectors are passed on 16byte boundary.
1548   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1549   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1550   if (Subtarget.hasAltivec())
1551     getMaxByValAlign(Ty, Alignment, Align(16));
1552   return Alignment.value();
1553 }
1554 
1555 bool PPCTargetLowering::useSoftFloat() const {
1556   return Subtarget.useSoftFloat();
1557 }
1558 
1559 bool PPCTargetLowering::hasSPE() const {
1560   return Subtarget.hasSPE();
1561 }
1562 
1563 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1564   return VT.isScalarInteger();
1565 }
1566 
1567 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1568   switch ((PPCISD::NodeType)Opcode) {
1569   case PPCISD::FIRST_NUMBER:    break;
1570   case PPCISD::FSEL:            return "PPCISD::FSEL";
1571   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1572   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1573   case PPCISD::FCFID:           return "PPCISD::FCFID";
1574   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1575   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1576   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1577   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1578   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1579   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1580   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1581   case PPCISD::FP_TO_UINT_IN_VSR:
1582                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1583   case PPCISD::FP_TO_SINT_IN_VSR:
1584                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1585   case PPCISD::FRE:             return "PPCISD::FRE";
1586   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1587   case PPCISD::FTSQRT:
1588     return "PPCISD::FTSQRT";
1589   case PPCISD::FSQRT:
1590     return "PPCISD::FSQRT";
1591   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1592   case PPCISD::VPERM:           return "PPCISD::VPERM";
1593   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1594   case PPCISD::XXSPLTI_SP_TO_DP:
1595     return "PPCISD::XXSPLTI_SP_TO_DP";
1596   case PPCISD::XXSPLTI32DX:
1597     return "PPCISD::XXSPLTI32DX";
1598   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1599   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1600   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1601   case PPCISD::CMPB:            return "PPCISD::CMPB";
1602   case PPCISD::Hi:              return "PPCISD::Hi";
1603   case PPCISD::Lo:              return "PPCISD::Lo";
1604   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1605   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1606   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1607   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1608   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1609   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1610   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1611   case PPCISD::SRL:             return "PPCISD::SRL";
1612   case PPCISD::SRA:             return "PPCISD::SRA";
1613   case PPCISD::SHL:             return "PPCISD::SHL";
1614   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1615   case PPCISD::CALL:            return "PPCISD::CALL";
1616   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1617   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1618   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1619   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1620   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1621   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1622   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1623   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1624   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1625   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1626   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1627   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1628   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1629   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1630   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1631   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1632     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1633   case PPCISD::ANDI_rec_1_EQ_BIT:
1634     return "PPCISD::ANDI_rec_1_EQ_BIT";
1635   case PPCISD::ANDI_rec_1_GT_BIT:
1636     return "PPCISD::ANDI_rec_1_GT_BIT";
1637   case PPCISD::VCMP:            return "PPCISD::VCMP";
1638   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1639   case PPCISD::LBRX:            return "PPCISD::LBRX";
1640   case PPCISD::STBRX:           return "PPCISD::STBRX";
1641   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1642   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1643   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1644   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1645   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1646   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1647   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1648   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1649   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1650   case PPCISD::ST_VSR_SCAL_INT:
1651                                 return "PPCISD::ST_VSR_SCAL_INT";
1652   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1653   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1654   case PPCISD::BDZ:             return "PPCISD::BDZ";
1655   case PPCISD::MFFS:            return "PPCISD::MFFS";
1656   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1657   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1658   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1659   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1660   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1661   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1662   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1663   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1664   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1665   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1666   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1667   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1668   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1669   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1670   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1671   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1672   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1673   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1674   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1675   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1676   case PPCISD::PADDI_DTPREL:
1677     return "PPCISD::PADDI_DTPREL";
1678   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1679   case PPCISD::SC:              return "PPCISD::SC";
1680   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1681   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1682   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1683   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1684   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1685   case PPCISD::VABSD:           return "PPCISD::VABSD";
1686   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1687   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1688   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1689   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1690   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1691   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1692   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1693   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1694     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1695   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1696     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1697   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1698   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1699   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1700   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1701   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1702   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1703   case PPCISD::STRICT_FADDRTZ:
1704     return "PPCISD::STRICT_FADDRTZ";
1705   case PPCISD::STRICT_FCTIDZ:
1706     return "PPCISD::STRICT_FCTIDZ";
1707   case PPCISD::STRICT_FCTIWZ:
1708     return "PPCISD::STRICT_FCTIWZ";
1709   case PPCISD::STRICT_FCTIDUZ:
1710     return "PPCISD::STRICT_FCTIDUZ";
1711   case PPCISD::STRICT_FCTIWUZ:
1712     return "PPCISD::STRICT_FCTIWUZ";
1713   case PPCISD::STRICT_FCFID:
1714     return "PPCISD::STRICT_FCFID";
1715   case PPCISD::STRICT_FCFIDU:
1716     return "PPCISD::STRICT_FCFIDU";
1717   case PPCISD::STRICT_FCFIDS:
1718     return "PPCISD::STRICT_FCFIDS";
1719   case PPCISD::STRICT_FCFIDUS:
1720     return "PPCISD::STRICT_FCFIDUS";
1721   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1722   }
1723   return nullptr;
1724 }
1725 
1726 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1727                                           EVT VT) const {
1728   if (!VT.isVector())
1729     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1730 
1731   return VT.changeVectorElementTypeToInteger();
1732 }
1733 
1734 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1735   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1736   return true;
1737 }
1738 
1739 //===----------------------------------------------------------------------===//
1740 // Node matching predicates, for use by the tblgen matching code.
1741 //===----------------------------------------------------------------------===//
1742 
1743 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1744 static bool isFloatingPointZero(SDValue Op) {
1745   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1746     return CFP->getValueAPF().isZero();
1747   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1748     // Maybe this has already been legalized into the constant pool?
1749     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1750       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1751         return CFP->getValueAPF().isZero();
1752   }
1753   return false;
1754 }
1755 
1756 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1757 /// true if Op is undef or if it matches the specified value.
1758 static bool isConstantOrUndef(int Op, int Val) {
1759   return Op < 0 || Op == Val;
1760 }
1761 
1762 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1763 /// VPKUHUM instruction.
1764 /// The ShuffleKind distinguishes between big-endian operations with
1765 /// two different inputs (0), either-endian operations with two identical
1766 /// inputs (1), and little-endian operations with two different inputs (2).
1767 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1768 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1769                                SelectionDAG &DAG) {
1770   bool IsLE = DAG.getDataLayout().isLittleEndian();
1771   if (ShuffleKind == 0) {
1772     if (IsLE)
1773       return false;
1774     for (unsigned i = 0; i != 16; ++i)
1775       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1776         return false;
1777   } else if (ShuffleKind == 2) {
1778     if (!IsLE)
1779       return false;
1780     for (unsigned i = 0; i != 16; ++i)
1781       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1782         return false;
1783   } else if (ShuffleKind == 1) {
1784     unsigned j = IsLE ? 0 : 1;
1785     for (unsigned i = 0; i != 8; ++i)
1786       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1787           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1788         return false;
1789   }
1790   return true;
1791 }
1792 
1793 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1794 /// VPKUWUM instruction.
1795 /// The ShuffleKind distinguishes between big-endian operations with
1796 /// two different inputs (0), either-endian operations with two identical
1797 /// inputs (1), and little-endian operations with two different inputs (2).
1798 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1799 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1800                                SelectionDAG &DAG) {
1801   bool IsLE = DAG.getDataLayout().isLittleEndian();
1802   if (ShuffleKind == 0) {
1803     if (IsLE)
1804       return false;
1805     for (unsigned i = 0; i != 16; i += 2)
1806       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1807           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1808         return false;
1809   } else if (ShuffleKind == 2) {
1810     if (!IsLE)
1811       return false;
1812     for (unsigned i = 0; i != 16; i += 2)
1813       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1814           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1815         return false;
1816   } else if (ShuffleKind == 1) {
1817     unsigned j = IsLE ? 0 : 2;
1818     for (unsigned i = 0; i != 8; i += 2)
1819       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1820           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1821           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1822           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1823         return false;
1824   }
1825   return true;
1826 }
1827 
1828 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1829 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1830 /// current subtarget.
1831 ///
1832 /// The ShuffleKind distinguishes between big-endian operations with
1833 /// two different inputs (0), either-endian operations with two identical
1834 /// inputs (1), and little-endian operations with two different inputs (2).
1835 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1836 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1837                                SelectionDAG &DAG) {
1838   const PPCSubtarget& Subtarget =
1839       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1840   if (!Subtarget.hasP8Vector())
1841     return false;
1842 
1843   bool IsLE = DAG.getDataLayout().isLittleEndian();
1844   if (ShuffleKind == 0) {
1845     if (IsLE)
1846       return false;
1847     for (unsigned i = 0; i != 16; i += 4)
1848       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1849           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1850           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1851           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1852         return false;
1853   } else if (ShuffleKind == 2) {
1854     if (!IsLE)
1855       return false;
1856     for (unsigned i = 0; i != 16; i += 4)
1857       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1858           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1859           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1860           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1861         return false;
1862   } else if (ShuffleKind == 1) {
1863     unsigned j = IsLE ? 0 : 4;
1864     for (unsigned i = 0; i != 8; i += 4)
1865       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1866           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1867           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1868           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1869           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1870           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1871           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1872           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1873         return false;
1874   }
1875   return true;
1876 }
1877 
1878 /// isVMerge - Common function, used to match vmrg* shuffles.
1879 ///
1880 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1881                      unsigned LHSStart, unsigned RHSStart) {
1882   if (N->getValueType(0) != MVT::v16i8)
1883     return false;
1884   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1885          "Unsupported merge size!");
1886 
1887   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1888     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1889       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1890                              LHSStart+j+i*UnitSize) ||
1891           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1892                              RHSStart+j+i*UnitSize))
1893         return false;
1894     }
1895   return true;
1896 }
1897 
1898 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1899 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1900 /// The ShuffleKind distinguishes between big-endian merges with two
1901 /// different inputs (0), either-endian merges with two identical inputs (1),
1902 /// and little-endian merges with two different inputs (2).  For the latter,
1903 /// the input operands are swapped (see PPCInstrAltivec.td).
1904 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1905                              unsigned ShuffleKind, SelectionDAG &DAG) {
1906   if (DAG.getDataLayout().isLittleEndian()) {
1907     if (ShuffleKind == 1) // unary
1908       return isVMerge(N, UnitSize, 0, 0);
1909     else if (ShuffleKind == 2) // swapped
1910       return isVMerge(N, UnitSize, 0, 16);
1911     else
1912       return false;
1913   } else {
1914     if (ShuffleKind == 1) // unary
1915       return isVMerge(N, UnitSize, 8, 8);
1916     else if (ShuffleKind == 0) // normal
1917       return isVMerge(N, UnitSize, 8, 24);
1918     else
1919       return false;
1920   }
1921 }
1922 
1923 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1924 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1925 /// The ShuffleKind distinguishes between big-endian merges with two
1926 /// different inputs (0), either-endian merges with two identical inputs (1),
1927 /// and little-endian merges with two different inputs (2).  For the latter,
1928 /// the input operands are swapped (see PPCInstrAltivec.td).
1929 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1930                              unsigned ShuffleKind, SelectionDAG &DAG) {
1931   if (DAG.getDataLayout().isLittleEndian()) {
1932     if (ShuffleKind == 1) // unary
1933       return isVMerge(N, UnitSize, 8, 8);
1934     else if (ShuffleKind == 2) // swapped
1935       return isVMerge(N, UnitSize, 8, 24);
1936     else
1937       return false;
1938   } else {
1939     if (ShuffleKind == 1) // unary
1940       return isVMerge(N, UnitSize, 0, 0);
1941     else if (ShuffleKind == 0) // normal
1942       return isVMerge(N, UnitSize, 0, 16);
1943     else
1944       return false;
1945   }
1946 }
1947 
1948 /**
1949  * Common function used to match vmrgew and vmrgow shuffles
1950  *
1951  * The indexOffset determines whether to look for even or odd words in
1952  * the shuffle mask. This is based on the of the endianness of the target
1953  * machine.
1954  *   - Little Endian:
1955  *     - Use offset of 0 to check for odd elements
1956  *     - Use offset of 4 to check for even elements
1957  *   - Big Endian:
1958  *     - Use offset of 0 to check for even elements
1959  *     - Use offset of 4 to check for odd elements
1960  * A detailed description of the vector element ordering for little endian and
1961  * big endian can be found at
1962  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1963  * Targeting your applications - what little endian and big endian IBM XL C/C++
1964  * compiler differences mean to you
1965  *
1966  * The mask to the shuffle vector instruction specifies the indices of the
1967  * elements from the two input vectors to place in the result. The elements are
1968  * numbered in array-access order, starting with the first vector. These vectors
1969  * are always of type v16i8, thus each vector will contain 16 elements of size
1970  * 8. More info on the shuffle vector can be found in the
1971  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1972  * Language Reference.
1973  *
1974  * The RHSStartValue indicates whether the same input vectors are used (unary)
1975  * or two different input vectors are used, based on the following:
1976  *   - If the instruction uses the same vector for both inputs, the range of the
1977  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1978  *     be 0.
1979  *   - If the instruction has two different vectors then the range of the
1980  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1981  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1982  *     to 31 specify elements in the second vector).
1983  *
1984  * \param[in] N The shuffle vector SD Node to analyze
1985  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1986  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1987  * vector to the shuffle_vector instruction
1988  * \return true iff this shuffle vector represents an even or odd word merge
1989  */
1990 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1991                      unsigned RHSStartValue) {
1992   if (N->getValueType(0) != MVT::v16i8)
1993     return false;
1994 
1995   for (unsigned i = 0; i < 2; ++i)
1996     for (unsigned j = 0; j < 4; ++j)
1997       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1998                              i*RHSStartValue+j+IndexOffset) ||
1999           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2000                              i*RHSStartValue+j+IndexOffset+8))
2001         return false;
2002   return true;
2003 }
2004 
2005 /**
2006  * Determine if the specified shuffle mask is suitable for the vmrgew or
2007  * vmrgow instructions.
2008  *
2009  * \param[in] N The shuffle vector SD Node to analyze
2010  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2011  * \param[in] ShuffleKind Identify the type of merge:
2012  *   - 0 = big-endian merge with two different inputs;
2013  *   - 1 = either-endian merge with two identical inputs;
2014  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2015  *     little-endian merges).
2016  * \param[in] DAG The current SelectionDAG
2017  * \return true iff this shuffle mask
2018  */
2019 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2020                               unsigned ShuffleKind, SelectionDAG &DAG) {
2021   if (DAG.getDataLayout().isLittleEndian()) {
2022     unsigned indexOffset = CheckEven ? 4 : 0;
2023     if (ShuffleKind == 1) // Unary
2024       return isVMerge(N, indexOffset, 0);
2025     else if (ShuffleKind == 2) // swapped
2026       return isVMerge(N, indexOffset, 16);
2027     else
2028       return false;
2029   }
2030   else {
2031     unsigned indexOffset = CheckEven ? 0 : 4;
2032     if (ShuffleKind == 1) // Unary
2033       return isVMerge(N, indexOffset, 0);
2034     else if (ShuffleKind == 0) // Normal
2035       return isVMerge(N, indexOffset, 16);
2036     else
2037       return false;
2038   }
2039   return false;
2040 }
2041 
2042 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2043 /// amount, otherwise return -1.
2044 /// The ShuffleKind distinguishes between big-endian operations with two
2045 /// different inputs (0), either-endian operations with two identical inputs
2046 /// (1), and little-endian operations with two different inputs (2).  For the
2047 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2048 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2049                              SelectionDAG &DAG) {
2050   if (N->getValueType(0) != MVT::v16i8)
2051     return -1;
2052 
2053   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2054 
2055   // Find the first non-undef value in the shuffle mask.
2056   unsigned i;
2057   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2058     /*search*/;
2059 
2060   if (i == 16) return -1;  // all undef.
2061 
2062   // Otherwise, check to see if the rest of the elements are consecutively
2063   // numbered from this value.
2064   unsigned ShiftAmt = SVOp->getMaskElt(i);
2065   if (ShiftAmt < i) return -1;
2066 
2067   ShiftAmt -= i;
2068   bool isLE = DAG.getDataLayout().isLittleEndian();
2069 
2070   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2071     // Check the rest of the elements to see if they are consecutive.
2072     for (++i; i != 16; ++i)
2073       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2074         return -1;
2075   } else if (ShuffleKind == 1) {
2076     // Check the rest of the elements to see if they are consecutive.
2077     for (++i; i != 16; ++i)
2078       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2079         return -1;
2080   } else
2081     return -1;
2082 
2083   if (isLE)
2084     ShiftAmt = 16 - ShiftAmt;
2085 
2086   return ShiftAmt;
2087 }
2088 
2089 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2090 /// specifies a splat of a single element that is suitable for input to
2091 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2092 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2093   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2094          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2095 
2096   // The consecutive indices need to specify an element, not part of two
2097   // different elements.  So abandon ship early if this isn't the case.
2098   if (N->getMaskElt(0) % EltSize != 0)
2099     return false;
2100 
2101   // This is a splat operation if each element of the permute is the same, and
2102   // if the value doesn't reference the second vector.
2103   unsigned ElementBase = N->getMaskElt(0);
2104 
2105   // FIXME: Handle UNDEF elements too!
2106   if (ElementBase >= 16)
2107     return false;
2108 
2109   // Check that the indices are consecutive, in the case of a multi-byte element
2110   // splatted with a v16i8 mask.
2111   for (unsigned i = 1; i != EltSize; ++i)
2112     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2113       return false;
2114 
2115   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2116     if (N->getMaskElt(i) < 0) continue;
2117     for (unsigned j = 0; j != EltSize; ++j)
2118       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2119         return false;
2120   }
2121   return true;
2122 }
2123 
2124 /// Check that the mask is shuffling N byte elements. Within each N byte
2125 /// element of the mask, the indices could be either in increasing or
2126 /// decreasing order as long as they are consecutive.
2127 /// \param[in] N the shuffle vector SD Node to analyze
2128 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2129 /// Word/DoubleWord/QuadWord).
2130 /// \param[in] StepLen the delta indices number among the N byte element, if
2131 /// the mask is in increasing/decreasing order then it is 1/-1.
2132 /// \return true iff the mask is shuffling N byte elements.
2133 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2134                                    int StepLen) {
2135   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2136          "Unexpected element width.");
2137   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2138 
2139   unsigned NumOfElem = 16 / Width;
2140   unsigned MaskVal[16]; //  Width is never greater than 16
2141   for (unsigned i = 0; i < NumOfElem; ++i) {
2142     MaskVal[0] = N->getMaskElt(i * Width);
2143     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2144       return false;
2145     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2146       return false;
2147     }
2148 
2149     for (unsigned int j = 1; j < Width; ++j) {
2150       MaskVal[j] = N->getMaskElt(i * Width + j);
2151       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2152         return false;
2153       }
2154     }
2155   }
2156 
2157   return true;
2158 }
2159 
2160 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2161                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2162   if (!isNByteElemShuffleMask(N, 4, 1))
2163     return false;
2164 
2165   // Now we look at mask elements 0,4,8,12
2166   unsigned M0 = N->getMaskElt(0) / 4;
2167   unsigned M1 = N->getMaskElt(4) / 4;
2168   unsigned M2 = N->getMaskElt(8) / 4;
2169   unsigned M3 = N->getMaskElt(12) / 4;
2170   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2171   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2172 
2173   // Below, let H and L be arbitrary elements of the shuffle mask
2174   // where H is in the range [4,7] and L is in the range [0,3].
2175   // H, 1, 2, 3 or L, 5, 6, 7
2176   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2177       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2178     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2179     InsertAtByte = IsLE ? 12 : 0;
2180     Swap = M0 < 4;
2181     return true;
2182   }
2183   // 0, H, 2, 3 or 4, L, 6, 7
2184   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2185       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2186     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2187     InsertAtByte = IsLE ? 8 : 4;
2188     Swap = M1 < 4;
2189     return true;
2190   }
2191   // 0, 1, H, 3 or 4, 5, L, 7
2192   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2193       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2194     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2195     InsertAtByte = IsLE ? 4 : 8;
2196     Swap = M2 < 4;
2197     return true;
2198   }
2199   // 0, 1, 2, H or 4, 5, 6, L
2200   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2201       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2202     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2203     InsertAtByte = IsLE ? 0 : 12;
2204     Swap = M3 < 4;
2205     return true;
2206   }
2207 
2208   // If both vector operands for the shuffle are the same vector, the mask will
2209   // contain only elements from the first one and the second one will be undef.
2210   if (N->getOperand(1).isUndef()) {
2211     ShiftElts = 0;
2212     Swap = true;
2213     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2214     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2215       InsertAtByte = IsLE ? 12 : 0;
2216       return true;
2217     }
2218     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2219       InsertAtByte = IsLE ? 8 : 4;
2220       return true;
2221     }
2222     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2223       InsertAtByte = IsLE ? 4 : 8;
2224       return true;
2225     }
2226     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2227       InsertAtByte = IsLE ? 0 : 12;
2228       return true;
2229     }
2230   }
2231 
2232   return false;
2233 }
2234 
2235 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2236                                bool &Swap, bool IsLE) {
2237   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2238   // Ensure each byte index of the word is consecutive.
2239   if (!isNByteElemShuffleMask(N, 4, 1))
2240     return false;
2241 
2242   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2243   unsigned M0 = N->getMaskElt(0) / 4;
2244   unsigned M1 = N->getMaskElt(4) / 4;
2245   unsigned M2 = N->getMaskElt(8) / 4;
2246   unsigned M3 = N->getMaskElt(12) / 4;
2247 
2248   // If both vector operands for the shuffle are the same vector, the mask will
2249   // contain only elements from the first one and the second one will be undef.
2250   if (N->getOperand(1).isUndef()) {
2251     assert(M0 < 4 && "Indexing into an undef vector?");
2252     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2253       return false;
2254 
2255     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2256     Swap = false;
2257     return true;
2258   }
2259 
2260   // Ensure each word index of the ShuffleVector Mask is consecutive.
2261   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2262     return false;
2263 
2264   if (IsLE) {
2265     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2266       // Input vectors don't need to be swapped if the leading element
2267       // of the result is one of the 3 left elements of the second vector
2268       // (or if there is no shift to be done at all).
2269       Swap = false;
2270       ShiftElts = (8 - M0) % 8;
2271     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2272       // Input vectors need to be swapped if the leading element
2273       // of the result is one of the 3 left elements of the first vector
2274       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2275       Swap = true;
2276       ShiftElts = (4 - M0) % 4;
2277     }
2278 
2279     return true;
2280   } else {                                          // BE
2281     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2282       // Input vectors don't need to be swapped if the leading element
2283       // of the result is one of the 4 elements of the first vector.
2284       Swap = false;
2285       ShiftElts = M0;
2286     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2287       // Input vectors need to be swapped if the leading element
2288       // of the result is one of the 4 elements of the right vector.
2289       Swap = true;
2290       ShiftElts = M0 - 4;
2291     }
2292 
2293     return true;
2294   }
2295 }
2296 
2297 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2298   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2299 
2300   if (!isNByteElemShuffleMask(N, Width, -1))
2301     return false;
2302 
2303   for (int i = 0; i < 16; i += Width)
2304     if (N->getMaskElt(i) != i + Width - 1)
2305       return false;
2306 
2307   return true;
2308 }
2309 
2310 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2311   return isXXBRShuffleMaskHelper(N, 2);
2312 }
2313 
2314 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2315   return isXXBRShuffleMaskHelper(N, 4);
2316 }
2317 
2318 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2319   return isXXBRShuffleMaskHelper(N, 8);
2320 }
2321 
2322 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2323   return isXXBRShuffleMaskHelper(N, 16);
2324 }
2325 
2326 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2327 /// if the inputs to the instruction should be swapped and set \p DM to the
2328 /// value for the immediate.
2329 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2330 /// AND element 0 of the result comes from the first input (LE) or second input
2331 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2332 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2333 /// mask.
2334 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2335                                bool &Swap, bool IsLE) {
2336   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2337 
2338   // Ensure each byte index of the double word is consecutive.
2339   if (!isNByteElemShuffleMask(N, 8, 1))
2340     return false;
2341 
2342   unsigned M0 = N->getMaskElt(0) / 8;
2343   unsigned M1 = N->getMaskElt(8) / 8;
2344   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2345 
2346   // If both vector operands for the shuffle are the same vector, the mask will
2347   // contain only elements from the first one and the second one will be undef.
2348   if (N->getOperand(1).isUndef()) {
2349     if ((M0 | M1) < 2) {
2350       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2351       Swap = false;
2352       return true;
2353     } else
2354       return false;
2355   }
2356 
2357   if (IsLE) {
2358     if (M0 > 1 && M1 < 2) {
2359       Swap = false;
2360     } else if (M0 < 2 && M1 > 1) {
2361       M0 = (M0 + 2) % 4;
2362       M1 = (M1 + 2) % 4;
2363       Swap = true;
2364     } else
2365       return false;
2366 
2367     // Note: if control flow comes here that means Swap is already set above
2368     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2369     return true;
2370   } else { // BE
2371     if (M0 < 2 && M1 > 1) {
2372       Swap = false;
2373     } else if (M0 > 1 && M1 < 2) {
2374       M0 = (M0 + 2) % 4;
2375       M1 = (M1 + 2) % 4;
2376       Swap = true;
2377     } else
2378       return false;
2379 
2380     // Note: if control flow comes here that means Swap is already set above
2381     DM = (M0 << 1) + (M1 & 1);
2382     return true;
2383   }
2384 }
2385 
2386 
2387 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2388 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2389 /// elements are counted from the left of the vector register).
2390 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2391                                          SelectionDAG &DAG) {
2392   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2393   assert(isSplatShuffleMask(SVOp, EltSize));
2394   if (DAG.getDataLayout().isLittleEndian())
2395     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2396   else
2397     return SVOp->getMaskElt(0) / EltSize;
2398 }
2399 
2400 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2401 /// by using a vspltis[bhw] instruction of the specified element size, return
2402 /// the constant being splatted.  The ByteSize field indicates the number of
2403 /// bytes of each element [124] -> [bhw].
2404 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2405   SDValue OpVal(nullptr, 0);
2406 
2407   // If ByteSize of the splat is bigger than the element size of the
2408   // build_vector, then we have a case where we are checking for a splat where
2409   // multiple elements of the buildvector are folded together into a single
2410   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2411   unsigned EltSize = 16/N->getNumOperands();
2412   if (EltSize < ByteSize) {
2413     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2414     SDValue UniquedVals[4];
2415     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2416 
2417     // See if all of the elements in the buildvector agree across.
2418     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2419       if (N->getOperand(i).isUndef()) continue;
2420       // If the element isn't a constant, bail fully out.
2421       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2422 
2423       if (!UniquedVals[i&(Multiple-1)].getNode())
2424         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2425       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2426         return SDValue();  // no match.
2427     }
2428 
2429     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2430     // either constant or undef values that are identical for each chunk.  See
2431     // if these chunks can form into a larger vspltis*.
2432 
2433     // Check to see if all of the leading entries are either 0 or -1.  If
2434     // neither, then this won't fit into the immediate field.
2435     bool LeadingZero = true;
2436     bool LeadingOnes = true;
2437     for (unsigned i = 0; i != Multiple-1; ++i) {
2438       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2439 
2440       LeadingZero &= isNullConstant(UniquedVals[i]);
2441       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2442     }
2443     // Finally, check the least significant entry.
2444     if (LeadingZero) {
2445       if (!UniquedVals[Multiple-1].getNode())
2446         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2447       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2448       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2449         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2450     }
2451     if (LeadingOnes) {
2452       if (!UniquedVals[Multiple-1].getNode())
2453         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2454       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2455       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2456         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2457     }
2458 
2459     return SDValue();
2460   }
2461 
2462   // Check to see if this buildvec has a single non-undef value in its elements.
2463   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2464     if (N->getOperand(i).isUndef()) continue;
2465     if (!OpVal.getNode())
2466       OpVal = N->getOperand(i);
2467     else if (OpVal != N->getOperand(i))
2468       return SDValue();
2469   }
2470 
2471   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2472 
2473   unsigned ValSizeInBytes = EltSize;
2474   uint64_t Value = 0;
2475   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2476     Value = CN->getZExtValue();
2477   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2478     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2479     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2480   }
2481 
2482   // If the splat value is larger than the element value, then we can never do
2483   // this splat.  The only case that we could fit the replicated bits into our
2484   // immediate field for would be zero, and we prefer to use vxor for it.
2485   if (ValSizeInBytes < ByteSize) return SDValue();
2486 
2487   // If the element value is larger than the splat value, check if it consists
2488   // of a repeated bit pattern of size ByteSize.
2489   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2490     return SDValue();
2491 
2492   // Properly sign extend the value.
2493   int MaskVal = SignExtend32(Value, ByteSize * 8);
2494 
2495   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2496   if (MaskVal == 0) return SDValue();
2497 
2498   // Finally, if this value fits in a 5 bit sext field, return it
2499   if (SignExtend32<5>(MaskVal) == MaskVal)
2500     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2501   return SDValue();
2502 }
2503 
2504 //===----------------------------------------------------------------------===//
2505 //  Addressing Mode Selection
2506 //===----------------------------------------------------------------------===//
2507 
2508 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2509 /// or 64-bit immediate, and if the value can be accurately represented as a
2510 /// sign extension from a 16-bit value.  If so, this returns true and the
2511 /// immediate.
2512 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2513   if (!isa<ConstantSDNode>(N))
2514     return false;
2515 
2516   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2517   if (N->getValueType(0) == MVT::i32)
2518     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2519   else
2520     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2521 }
2522 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2523   return isIntS16Immediate(Op.getNode(), Imm);
2524 }
2525 
2526 /// Used when computing address flags for selecting loads and stores.
2527 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2528 /// An OR of two provably disjoint values is equivalent to an ADD.
2529 /// Most PPC load/store instructions compute the effective address as a sum,
2530 /// so doing this conversion is useful.
2531 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2532   if (N.getOpcode() != ISD::OR)
2533     return false;
2534   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2535   if (!LHSKnown.Zero.getBoolValue())
2536     return false;
2537   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2538   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2539 }
2540 
2541 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2542 /// be represented as an indexed [r+r] operation.
2543 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2544                                                SDValue &Index,
2545                                                SelectionDAG &DAG) const {
2546   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2547       UI != E; ++UI) {
2548     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2549       if (Memop->getMemoryVT() == MVT::f64) {
2550           Base = N.getOperand(0);
2551           Index = N.getOperand(1);
2552           return true;
2553       }
2554     }
2555   }
2556   return false;
2557 }
2558 
2559 /// isIntS34Immediate - This method tests if value of node given can be
2560 /// accurately represented as a sign extension from a 34-bit value.  If so,
2561 /// this returns true and the immediate.
2562 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2563   if (!isa<ConstantSDNode>(N))
2564     return false;
2565 
2566   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2567   return isInt<34>(Imm);
2568 }
2569 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2570   return isIntS34Immediate(Op.getNode(), Imm);
2571 }
2572 
2573 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2574 /// can be represented as an indexed [r+r] operation.  Returns false if it
2575 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2576 /// non-zero and N can be represented by a base register plus a signed 16-bit
2577 /// displacement, make a more precise judgement by checking (displacement % \p
2578 /// EncodingAlignment).
2579 bool PPCTargetLowering::SelectAddressRegReg(
2580     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2581     MaybeAlign EncodingAlignment) const {
2582   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2583   // a [pc+imm].
2584   if (SelectAddressPCRel(N, Base))
2585     return false;
2586 
2587   int16_t Imm = 0;
2588   if (N.getOpcode() == ISD::ADD) {
2589     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2590     // SPE load/store can only handle 8-bit offsets.
2591     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2592         return true;
2593     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2594         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2595       return false; // r+i
2596     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2597       return false;    // r+i
2598 
2599     Base = N.getOperand(0);
2600     Index = N.getOperand(1);
2601     return true;
2602   } else if (N.getOpcode() == ISD::OR) {
2603     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2604         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2605       return false; // r+i can fold it if we can.
2606 
2607     // If this is an or of disjoint bitfields, we can codegen this as an add
2608     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2609     // disjoint.
2610     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2611 
2612     if (LHSKnown.Zero.getBoolValue()) {
2613       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2614       // If all of the bits are known zero on the LHS or RHS, the add won't
2615       // carry.
2616       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2617         Base = N.getOperand(0);
2618         Index = N.getOperand(1);
2619         return true;
2620       }
2621     }
2622   }
2623 
2624   return false;
2625 }
2626 
2627 // If we happen to be doing an i64 load or store into a stack slot that has
2628 // less than a 4-byte alignment, then the frame-index elimination may need to
2629 // use an indexed load or store instruction (because the offset may not be a
2630 // multiple of 4). The extra register needed to hold the offset comes from the
2631 // register scavenger, and it is possible that the scavenger will need to use
2632 // an emergency spill slot. As a result, we need to make sure that a spill slot
2633 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2634 // stack slot.
2635 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2636   // FIXME: This does not handle the LWA case.
2637   if (VT != MVT::i64)
2638     return;
2639 
2640   // NOTE: We'll exclude negative FIs here, which come from argument
2641   // lowering, because there are no known test cases triggering this problem
2642   // using packed structures (or similar). We can remove this exclusion if
2643   // we find such a test case. The reason why this is so test-case driven is
2644   // because this entire 'fixup' is only to prevent crashes (from the
2645   // register scavenger) on not-really-valid inputs. For example, if we have:
2646   //   %a = alloca i1
2647   //   %b = bitcast i1* %a to i64*
2648   //   store i64* a, i64 b
2649   // then the store should really be marked as 'align 1', but is not. If it
2650   // were marked as 'align 1' then the indexed form would have been
2651   // instruction-selected initially, and the problem this 'fixup' is preventing
2652   // won't happen regardless.
2653   if (FrameIdx < 0)
2654     return;
2655 
2656   MachineFunction &MF = DAG.getMachineFunction();
2657   MachineFrameInfo &MFI = MF.getFrameInfo();
2658 
2659   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2660     return;
2661 
2662   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2663   FuncInfo->setHasNonRISpills();
2664 }
2665 
2666 /// Returns true if the address N can be represented by a base register plus
2667 /// a signed 16-bit displacement [r+imm], and if it is not better
2668 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2669 /// displacements that are multiples of that value.
2670 bool PPCTargetLowering::SelectAddressRegImm(
2671     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2672     MaybeAlign EncodingAlignment) const {
2673   // FIXME dl should come from parent load or store, not from address
2674   SDLoc dl(N);
2675 
2676   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2677   // a [pc+imm].
2678   if (SelectAddressPCRel(N, Base))
2679     return false;
2680 
2681   // If this can be more profitably realized as r+r, fail.
2682   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2683     return false;
2684 
2685   if (N.getOpcode() == ISD::ADD) {
2686     int16_t imm = 0;
2687     if (isIntS16Immediate(N.getOperand(1), imm) &&
2688         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2689       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2690       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2691         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2692         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2693       } else {
2694         Base = N.getOperand(0);
2695       }
2696       return true; // [r+i]
2697     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2698       // Match LOAD (ADD (X, Lo(G))).
2699       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2700              && "Cannot handle constant offsets yet!");
2701       Disp = N.getOperand(1).getOperand(0);  // The global address.
2702       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2703              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2704              Disp.getOpcode() == ISD::TargetConstantPool ||
2705              Disp.getOpcode() == ISD::TargetJumpTable);
2706       Base = N.getOperand(0);
2707       return true;  // [&g+r]
2708     }
2709   } else if (N.getOpcode() == ISD::OR) {
2710     int16_t imm = 0;
2711     if (isIntS16Immediate(N.getOperand(1), imm) &&
2712         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2713       // If this is an or of disjoint bitfields, we can codegen this as an add
2714       // (for better address arithmetic) if the LHS and RHS of the OR are
2715       // provably disjoint.
2716       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2717 
2718       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2719         // If all of the bits are known zero on the LHS or RHS, the add won't
2720         // carry.
2721         if (FrameIndexSDNode *FI =
2722               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2723           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2724           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2725         } else {
2726           Base = N.getOperand(0);
2727         }
2728         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2729         return true;
2730       }
2731     }
2732   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2733     // Loading from a constant address.
2734 
2735     // If this address fits entirely in a 16-bit sext immediate field, codegen
2736     // this as "d, 0"
2737     int16_t Imm;
2738     if (isIntS16Immediate(CN, Imm) &&
2739         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2740       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2741       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2742                              CN->getValueType(0));
2743       return true;
2744     }
2745 
2746     // Handle 32-bit sext immediates with LIS + addr mode.
2747     if ((CN->getValueType(0) == MVT::i32 ||
2748          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2749         (!EncodingAlignment ||
2750          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2751       int Addr = (int)CN->getZExtValue();
2752 
2753       // Otherwise, break this down into an LIS + disp.
2754       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2755 
2756       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2757                                    MVT::i32);
2758       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2759       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2760       return true;
2761     }
2762   }
2763 
2764   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2765   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2766     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2767     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2768   } else
2769     Base = N;
2770   return true;      // [r+0]
2771 }
2772 
2773 /// Similar to the 16-bit case but for instructions that take a 34-bit
2774 /// displacement field (prefixed loads/stores).
2775 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2776                                               SDValue &Base,
2777                                               SelectionDAG &DAG) const {
2778   // Only on 64-bit targets.
2779   if (N.getValueType() != MVT::i64)
2780     return false;
2781 
2782   SDLoc dl(N);
2783   int64_t Imm = 0;
2784 
2785   if (N.getOpcode() == ISD::ADD) {
2786     if (!isIntS34Immediate(N.getOperand(1), Imm))
2787       return false;
2788     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2789     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2790       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2791     else
2792       Base = N.getOperand(0);
2793     return true;
2794   }
2795 
2796   if (N.getOpcode() == ISD::OR) {
2797     if (!isIntS34Immediate(N.getOperand(1), Imm))
2798       return false;
2799     // If this is an or of disjoint bitfields, we can codegen this as an add
2800     // (for better address arithmetic) if the LHS and RHS of the OR are
2801     // provably disjoint.
2802     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2803     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2804       return false;
2805     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2806       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2807     else
2808       Base = N.getOperand(0);
2809     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2810     return true;
2811   }
2812 
2813   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2814     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2815     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2816     return true;
2817   }
2818 
2819   return false;
2820 }
2821 
2822 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2823 /// represented as an indexed [r+r] operation.
2824 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2825                                                 SDValue &Index,
2826                                                 SelectionDAG &DAG) const {
2827   // Check to see if we can easily represent this as an [r+r] address.  This
2828   // will fail if it thinks that the address is more profitably represented as
2829   // reg+imm, e.g. where imm = 0.
2830   if (SelectAddressRegReg(N, Base, Index, DAG))
2831     return true;
2832 
2833   // If the address is the result of an add, we will utilize the fact that the
2834   // address calculation includes an implicit add.  However, we can reduce
2835   // register pressure if we do not materialize a constant just for use as the
2836   // index register.  We only get rid of the add if it is not an add of a
2837   // value and a 16-bit signed constant and both have a single use.
2838   int16_t imm = 0;
2839   if (N.getOpcode() == ISD::ADD &&
2840       (!isIntS16Immediate(N.getOperand(1), imm) ||
2841        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2842     Base = N.getOperand(0);
2843     Index = N.getOperand(1);
2844     return true;
2845   }
2846 
2847   // Otherwise, do it the hard way, using R0 as the base register.
2848   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2849                          N.getValueType());
2850   Index = N;
2851   return true;
2852 }
2853 
2854 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2855   Ty *PCRelCand = dyn_cast<Ty>(N);
2856   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2857 }
2858 
2859 /// Returns true if this address is a PC Relative address.
2860 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2861 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2862 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2863   // This is a materialize PC Relative node. Always select this as PC Relative.
2864   Base = N;
2865   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2866     return true;
2867   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2868       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2869       isValidPCRelNode<JumpTableSDNode>(N) ||
2870       isValidPCRelNode<BlockAddressSDNode>(N))
2871     return true;
2872   return false;
2873 }
2874 
2875 /// Returns true if we should use a direct load into vector instruction
2876 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2877 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2878 
2879   // If there are any other uses other than scalar to vector, then we should
2880   // keep it as a scalar load -> direct move pattern to prevent multiple
2881   // loads.
2882   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2883   if (!LD)
2884     return false;
2885 
2886   EVT MemVT = LD->getMemoryVT();
2887   if (!MemVT.isSimple())
2888     return false;
2889   switch(MemVT.getSimpleVT().SimpleTy) {
2890   case MVT::i64:
2891     break;
2892   case MVT::i32:
2893     if (!ST.hasP8Vector())
2894       return false;
2895     break;
2896   case MVT::i16:
2897   case MVT::i8:
2898     if (!ST.hasP9Vector())
2899       return false;
2900     break;
2901   default:
2902     return false;
2903   }
2904 
2905   SDValue LoadedVal(N, 0);
2906   if (!LoadedVal.hasOneUse())
2907     return false;
2908 
2909   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2910        UI != UE; ++UI)
2911     if (UI.getUse().get().getResNo() == 0 &&
2912         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2913         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2914       return false;
2915 
2916   return true;
2917 }
2918 
2919 /// getPreIndexedAddressParts - returns true by value, base pointer and
2920 /// offset pointer and addressing mode by reference if the node's address
2921 /// can be legally represented as pre-indexed load / store address.
2922 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2923                                                   SDValue &Offset,
2924                                                   ISD::MemIndexedMode &AM,
2925                                                   SelectionDAG &DAG) const {
2926   if (DisablePPCPreinc) return false;
2927 
2928   bool isLoad = true;
2929   SDValue Ptr;
2930   EVT VT;
2931   unsigned Alignment;
2932   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2933     Ptr = LD->getBasePtr();
2934     VT = LD->getMemoryVT();
2935     Alignment = LD->getAlignment();
2936   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2937     Ptr = ST->getBasePtr();
2938     VT  = ST->getMemoryVT();
2939     Alignment = ST->getAlignment();
2940     isLoad = false;
2941   } else
2942     return false;
2943 
2944   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2945   // instructions because we can fold these into a more efficient instruction
2946   // instead, (such as LXSD).
2947   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2948     return false;
2949   }
2950 
2951   // PowerPC doesn't have preinc load/store instructions for vectors
2952   if (VT.isVector())
2953     return false;
2954 
2955   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2956     // Common code will reject creating a pre-inc form if the base pointer
2957     // is a frame index, or if N is a store and the base pointer is either
2958     // the same as or a predecessor of the value being stored.  Check for
2959     // those situations here, and try with swapped Base/Offset instead.
2960     bool Swap = false;
2961 
2962     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2963       Swap = true;
2964     else if (!isLoad) {
2965       SDValue Val = cast<StoreSDNode>(N)->getValue();
2966       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2967         Swap = true;
2968     }
2969 
2970     if (Swap)
2971       std::swap(Base, Offset);
2972 
2973     AM = ISD::PRE_INC;
2974     return true;
2975   }
2976 
2977   // LDU/STU can only handle immediates that are a multiple of 4.
2978   if (VT != MVT::i64) {
2979     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2980       return false;
2981   } else {
2982     // LDU/STU need an address with at least 4-byte alignment.
2983     if (Alignment < 4)
2984       return false;
2985 
2986     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2987       return false;
2988   }
2989 
2990   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2991     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2992     // sext i32 to i64 when addr mode is r+i.
2993     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2994         LD->getExtensionType() == ISD::SEXTLOAD &&
2995         isa<ConstantSDNode>(Offset))
2996       return false;
2997   }
2998 
2999   AM = ISD::PRE_INC;
3000   return true;
3001 }
3002 
3003 //===----------------------------------------------------------------------===//
3004 //  LowerOperation implementation
3005 //===----------------------------------------------------------------------===//
3006 
3007 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3008 /// and LoOpFlags to the target MO flags.
3009 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3010                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3011                                const GlobalValue *GV = nullptr) {
3012   HiOpFlags = PPCII::MO_HA;
3013   LoOpFlags = PPCII::MO_LO;
3014 
3015   // Don't use the pic base if not in PIC relocation model.
3016   if (IsPIC) {
3017     HiOpFlags |= PPCII::MO_PIC_FLAG;
3018     LoOpFlags |= PPCII::MO_PIC_FLAG;
3019   }
3020 }
3021 
3022 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3023                              SelectionDAG &DAG) {
3024   SDLoc DL(HiPart);
3025   EVT PtrVT = HiPart.getValueType();
3026   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3027 
3028   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3029   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3030 
3031   // With PIC, the first instruction is actually "GR+hi(&G)".
3032   if (isPIC)
3033     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3034                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3035 
3036   // Generate non-pic code that has direct accesses to the constant pool.
3037   // The address of the global is just (hi(&g)+lo(&g)).
3038   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3039 }
3040 
3041 static void setUsesTOCBasePtr(MachineFunction &MF) {
3042   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3043   FuncInfo->setUsesTOCBasePtr();
3044 }
3045 
3046 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3047   setUsesTOCBasePtr(DAG.getMachineFunction());
3048 }
3049 
3050 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3051                                        SDValue GA) const {
3052   const bool Is64Bit = Subtarget.isPPC64();
3053   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3054   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3055                         : Subtarget.isAIXABI()
3056                               ? DAG.getRegister(PPC::R2, VT)
3057                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3058   SDValue Ops[] = { GA, Reg };
3059   return DAG.getMemIntrinsicNode(
3060       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3061       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3062       MachineMemOperand::MOLoad);
3063 }
3064 
3065 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3066                                              SelectionDAG &DAG) const {
3067   EVT PtrVT = Op.getValueType();
3068   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3069   const Constant *C = CP->getConstVal();
3070 
3071   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3072   // The actual address of the GlobalValue is stored in the TOC.
3073   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3074     if (Subtarget.isUsingPCRelativeCalls()) {
3075       SDLoc DL(CP);
3076       EVT Ty = getPointerTy(DAG.getDataLayout());
3077       SDValue ConstPool = DAG.getTargetConstantPool(
3078           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3079       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3080     }
3081     setUsesTOCBasePtr(DAG);
3082     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3083     return getTOCEntry(DAG, SDLoc(CP), GA);
3084   }
3085 
3086   unsigned MOHiFlag, MOLoFlag;
3087   bool IsPIC = isPositionIndependent();
3088   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3089 
3090   if (IsPIC && Subtarget.isSVR4ABI()) {
3091     SDValue GA =
3092         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3093     return getTOCEntry(DAG, SDLoc(CP), GA);
3094   }
3095 
3096   SDValue CPIHi =
3097       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3098   SDValue CPILo =
3099       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3100   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3101 }
3102 
3103 // For 64-bit PowerPC, prefer the more compact relative encodings.
3104 // This trades 32 bits per jump table entry for one or two instructions
3105 // on the jump site.
3106 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3107   if (isJumpTableRelative())
3108     return MachineJumpTableInfo::EK_LabelDifference32;
3109 
3110   return TargetLowering::getJumpTableEncoding();
3111 }
3112 
3113 bool PPCTargetLowering::isJumpTableRelative() const {
3114   if (UseAbsoluteJumpTables)
3115     return false;
3116   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3117     return true;
3118   return TargetLowering::isJumpTableRelative();
3119 }
3120 
3121 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3122                                                     SelectionDAG &DAG) const {
3123   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3124     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3125 
3126   switch (getTargetMachine().getCodeModel()) {
3127   case CodeModel::Small:
3128   case CodeModel::Medium:
3129     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3130   default:
3131     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3132                        getPointerTy(DAG.getDataLayout()));
3133   }
3134 }
3135 
3136 const MCExpr *
3137 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3138                                                 unsigned JTI,
3139                                                 MCContext &Ctx) const {
3140   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3141     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3142 
3143   switch (getTargetMachine().getCodeModel()) {
3144   case CodeModel::Small:
3145   case CodeModel::Medium:
3146     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3147   default:
3148     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3149   }
3150 }
3151 
3152 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3153   EVT PtrVT = Op.getValueType();
3154   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3155 
3156   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3157   if (Subtarget.isUsingPCRelativeCalls()) {
3158     SDLoc DL(JT);
3159     EVT Ty = getPointerTy(DAG.getDataLayout());
3160     SDValue GA =
3161         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3162     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3163     return MatAddr;
3164   }
3165 
3166   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3167   // The actual address of the GlobalValue is stored in the TOC.
3168   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3169     setUsesTOCBasePtr(DAG);
3170     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3171     return getTOCEntry(DAG, SDLoc(JT), GA);
3172   }
3173 
3174   unsigned MOHiFlag, MOLoFlag;
3175   bool IsPIC = isPositionIndependent();
3176   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3177 
3178   if (IsPIC && Subtarget.isSVR4ABI()) {
3179     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3180                                         PPCII::MO_PIC_FLAG);
3181     return getTOCEntry(DAG, SDLoc(GA), GA);
3182   }
3183 
3184   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3185   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3186   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3187 }
3188 
3189 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3190                                              SelectionDAG &DAG) const {
3191   EVT PtrVT = Op.getValueType();
3192   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3193   const BlockAddress *BA = BASDN->getBlockAddress();
3194 
3195   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3196   if (Subtarget.isUsingPCRelativeCalls()) {
3197     SDLoc DL(BASDN);
3198     EVT Ty = getPointerTy(DAG.getDataLayout());
3199     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3200                                            PPCII::MO_PCREL_FLAG);
3201     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3202     return MatAddr;
3203   }
3204 
3205   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3206   // The actual BlockAddress is stored in the TOC.
3207   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3208     setUsesTOCBasePtr(DAG);
3209     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3210     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3211   }
3212 
3213   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3214   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3215     return getTOCEntry(
3216         DAG, SDLoc(BASDN),
3217         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3218 
3219   unsigned MOHiFlag, MOLoFlag;
3220   bool IsPIC = isPositionIndependent();
3221   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3222   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3223   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3224   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3225 }
3226 
3227 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3228                                               SelectionDAG &DAG) const {
3229   if (Subtarget.isAIXABI())
3230     return LowerGlobalTLSAddressAIX(Op, DAG);
3231 
3232   return LowerGlobalTLSAddressLinux(Op, DAG);
3233 }
3234 
3235 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3236                                                     SelectionDAG &DAG) const {
3237   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3238 
3239   if (DAG.getTarget().useEmulatedTLS())
3240     report_fatal_error("Emulated TLS is not yet supported on AIX");
3241 
3242   SDLoc dl(GA);
3243   const GlobalValue *GV = GA->getGlobal();
3244   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3245 
3246   // The general-dynamic model is the only access model supported for now, so
3247   // all the GlobalTLSAddress nodes are lowered with this model.
3248   // We need to generate two TOC entries, one for the variable offset, one for
3249   // the region handle. The global address for the TOC entry of the region
3250   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3251   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3252   SDValue VariableOffsetTGA =
3253       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3254   SDValue RegionHandleTGA =
3255       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3256   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3257   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3258   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3259                      RegionHandle);
3260 }
3261 
3262 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3263                                                       SelectionDAG &DAG) const {
3264   // FIXME: TLS addresses currently use medium model code sequences,
3265   // which is the most useful form.  Eventually support for small and
3266   // large models could be added if users need it, at the cost of
3267   // additional complexity.
3268   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3269   if (DAG.getTarget().useEmulatedTLS())
3270     return LowerToTLSEmulatedModel(GA, DAG);
3271 
3272   SDLoc dl(GA);
3273   const GlobalValue *GV = GA->getGlobal();
3274   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3275   bool is64bit = Subtarget.isPPC64();
3276   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3277   PICLevel::Level picLevel = M->getPICLevel();
3278 
3279   const TargetMachine &TM = getTargetMachine();
3280   TLSModel::Model Model = TM.getTLSModel(GV);
3281 
3282   if (Model == TLSModel::LocalExec) {
3283     if (Subtarget.isUsingPCRelativeCalls()) {
3284       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3285       SDValue TGA = DAG.getTargetGlobalAddress(
3286           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3287       SDValue MatAddr =
3288           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3289       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3290     }
3291 
3292     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3293                                                PPCII::MO_TPREL_HA);
3294     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3295                                                PPCII::MO_TPREL_LO);
3296     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3297                              : DAG.getRegister(PPC::R2, MVT::i32);
3298 
3299     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3300     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3301   }
3302 
3303   if (Model == TLSModel::InitialExec) {
3304     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3305     SDValue TGA = DAG.getTargetGlobalAddress(
3306         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3307     SDValue TGATLS = DAG.getTargetGlobalAddress(
3308         GV, dl, PtrVT, 0,
3309         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3310     SDValue TPOffset;
3311     if (IsPCRel) {
3312       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3313       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3314                              MachinePointerInfo());
3315     } else {
3316       SDValue GOTPtr;
3317       if (is64bit) {
3318         setUsesTOCBasePtr(DAG);
3319         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3320         GOTPtr =
3321             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3322       } else {
3323         if (!TM.isPositionIndependent())
3324           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3325         else if (picLevel == PICLevel::SmallPIC)
3326           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3327         else
3328           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3329       }
3330       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3331     }
3332     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3333   }
3334 
3335   if (Model == TLSModel::GeneralDynamic) {
3336     if (Subtarget.isUsingPCRelativeCalls()) {
3337       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3338                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3339       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3340     }
3341 
3342     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3343     SDValue GOTPtr;
3344     if (is64bit) {
3345       setUsesTOCBasePtr(DAG);
3346       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3347       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3348                                    GOTReg, TGA);
3349     } else {
3350       if (picLevel == PICLevel::SmallPIC)
3351         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3352       else
3353         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3354     }
3355     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3356                        GOTPtr, TGA, TGA);
3357   }
3358 
3359   if (Model == TLSModel::LocalDynamic) {
3360     if (Subtarget.isUsingPCRelativeCalls()) {
3361       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3362                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3363       SDValue MatPCRel =
3364           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3365       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3366     }
3367 
3368     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3369     SDValue GOTPtr;
3370     if (is64bit) {
3371       setUsesTOCBasePtr(DAG);
3372       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3373       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3374                            GOTReg, TGA);
3375     } else {
3376       if (picLevel == PICLevel::SmallPIC)
3377         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3378       else
3379         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3380     }
3381     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3382                                   PtrVT, GOTPtr, TGA, TGA);
3383     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3384                                       PtrVT, TLSAddr, TGA);
3385     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3386   }
3387 
3388   llvm_unreachable("Unknown TLS model!");
3389 }
3390 
3391 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3392                                               SelectionDAG &DAG) const {
3393   EVT PtrVT = Op.getValueType();
3394   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3395   SDLoc DL(GSDN);
3396   const GlobalValue *GV = GSDN->getGlobal();
3397 
3398   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3399   // The actual address of the GlobalValue is stored in the TOC.
3400   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3401     if (Subtarget.isUsingPCRelativeCalls()) {
3402       EVT Ty = getPointerTy(DAG.getDataLayout());
3403       if (isAccessedAsGotIndirect(Op)) {
3404         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3405                                                 PPCII::MO_PCREL_FLAG |
3406                                                     PPCII::MO_GOT_FLAG);
3407         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3408         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3409                                    MachinePointerInfo());
3410         return Load;
3411       } else {
3412         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3413                                                 PPCII::MO_PCREL_FLAG);
3414         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3415       }
3416     }
3417     setUsesTOCBasePtr(DAG);
3418     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3419     return getTOCEntry(DAG, DL, GA);
3420   }
3421 
3422   unsigned MOHiFlag, MOLoFlag;
3423   bool IsPIC = isPositionIndependent();
3424   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3425 
3426   if (IsPIC && Subtarget.isSVR4ABI()) {
3427     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3428                                             GSDN->getOffset(),
3429                                             PPCII::MO_PIC_FLAG);
3430     return getTOCEntry(DAG, DL, GA);
3431   }
3432 
3433   SDValue GAHi =
3434     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3435   SDValue GALo =
3436     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3437 
3438   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3439 }
3440 
3441 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3442   bool IsStrict = Op->isStrictFPOpcode();
3443   ISD::CondCode CC =
3444       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3445   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3446   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3447   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3448   EVT LHSVT = LHS.getValueType();
3449   SDLoc dl(Op);
3450 
3451   // Soften the setcc with libcall if it is fp128.
3452   if (LHSVT == MVT::f128) {
3453     assert(!Subtarget.hasP9Vector() &&
3454            "SETCC for f128 is already legal under Power9!");
3455     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3456                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3457     if (RHS.getNode())
3458       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3459                         DAG.getCondCode(CC));
3460     if (IsStrict)
3461       return DAG.getMergeValues({LHS, Chain}, dl);
3462     return LHS;
3463   }
3464 
3465   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3466 
3467   if (Op.getValueType() == MVT::v2i64) {
3468     // When the operands themselves are v2i64 values, we need to do something
3469     // special because VSX has no underlying comparison operations for these.
3470     if (LHS.getValueType() == MVT::v2i64) {
3471       // Equality can be handled by casting to the legal type for Altivec
3472       // comparisons, everything else needs to be expanded.
3473       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3474         return DAG.getNode(
3475             ISD::BITCAST, dl, MVT::v2i64,
3476             DAG.getSetCC(dl, MVT::v4i32,
3477                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3478                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC));
3479       }
3480 
3481       return SDValue();
3482     }
3483 
3484     // We handle most of these in the usual way.
3485     return Op;
3486   }
3487 
3488   // If we're comparing for equality to zero, expose the fact that this is
3489   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3490   // fold the new nodes.
3491   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3492     return V;
3493 
3494   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3495     // Leave comparisons against 0 and -1 alone for now, since they're usually
3496     // optimized.  FIXME: revisit this when we can custom lower all setcc
3497     // optimizations.
3498     if (C->isAllOnesValue() || C->isNullValue())
3499       return SDValue();
3500   }
3501 
3502   // If we have an integer seteq/setne, turn it into a compare against zero
3503   // by xor'ing the rhs with the lhs, which is faster than setting a
3504   // condition register, reading it back out, and masking the correct bit.  The
3505   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3506   // the result to other bit-twiddling opportunities.
3507   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3508     EVT VT = Op.getValueType();
3509     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3510     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3511   }
3512   return SDValue();
3513 }
3514 
3515 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3516   SDNode *Node = Op.getNode();
3517   EVT VT = Node->getValueType(0);
3518   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3519   SDValue InChain = Node->getOperand(0);
3520   SDValue VAListPtr = Node->getOperand(1);
3521   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3522   SDLoc dl(Node);
3523 
3524   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3525 
3526   // gpr_index
3527   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3528                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3529   InChain = GprIndex.getValue(1);
3530 
3531   if (VT == MVT::i64) {
3532     // Check if GprIndex is even
3533     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3534                                  DAG.getConstant(1, dl, MVT::i32));
3535     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3536                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3537     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3538                                           DAG.getConstant(1, dl, MVT::i32));
3539     // Align GprIndex to be even if it isn't
3540     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3541                            GprIndex);
3542   }
3543 
3544   // fpr index is 1 byte after gpr
3545   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3546                                DAG.getConstant(1, dl, MVT::i32));
3547 
3548   // fpr
3549   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3550                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3551   InChain = FprIndex.getValue(1);
3552 
3553   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3554                                        DAG.getConstant(8, dl, MVT::i32));
3555 
3556   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3557                                         DAG.getConstant(4, dl, MVT::i32));
3558 
3559   // areas
3560   SDValue OverflowArea =
3561       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3562   InChain = OverflowArea.getValue(1);
3563 
3564   SDValue RegSaveArea =
3565       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3566   InChain = RegSaveArea.getValue(1);
3567 
3568   // select overflow_area if index > 8
3569   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3570                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3571 
3572   // adjustment constant gpr_index * 4/8
3573   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3574                                     VT.isInteger() ? GprIndex : FprIndex,
3575                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3576                                                     MVT::i32));
3577 
3578   // OurReg = RegSaveArea + RegConstant
3579   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3580                                RegConstant);
3581 
3582   // Floating types are 32 bytes into RegSaveArea
3583   if (VT.isFloatingPoint())
3584     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3585                          DAG.getConstant(32, dl, MVT::i32));
3586 
3587   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3588   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3589                                    VT.isInteger() ? GprIndex : FprIndex,
3590                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3591                                                    MVT::i32));
3592 
3593   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3594                               VT.isInteger() ? VAListPtr : FprPtr,
3595                               MachinePointerInfo(SV), MVT::i8);
3596 
3597   // determine if we should load from reg_save_area or overflow_area
3598   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3599 
3600   // increase overflow_area by 4/8 if gpr/fpr > 8
3601   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3602                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3603                                           dl, MVT::i32));
3604 
3605   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3606                              OverflowAreaPlusN);
3607 
3608   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3609                               MachinePointerInfo(), MVT::i32);
3610 
3611   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3612 }
3613 
3614 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3615   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3616 
3617   // We have to copy the entire va_list struct:
3618   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3619   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3620                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3621                        false, true, false, MachinePointerInfo(),
3622                        MachinePointerInfo());
3623 }
3624 
3625 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3626                                                   SelectionDAG &DAG) const {
3627   if (Subtarget.isAIXABI())
3628     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3629 
3630   return Op.getOperand(0);
3631 }
3632 
3633 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3634   MachineFunction &MF = DAG.getMachineFunction();
3635   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3636 
3637   assert((Op.getOpcode() == ISD::INLINEASM ||
3638           Op.getOpcode() == ISD::INLINEASM_BR) &&
3639          "Expecting Inline ASM node.");
3640 
3641   // If an LR store is already known to be required then there is not point in
3642   // checking this ASM as well.
3643   if (MFI.isLRStoreRequired())
3644     return Op;
3645 
3646   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3647   // type MVT::Glue. We want to ignore this last operand if that is the case.
3648   unsigned NumOps = Op.getNumOperands();
3649   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3650     --NumOps;
3651 
3652   // Check all operands that may contain the LR.
3653   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3654     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3655     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3656     ++i; // Skip the ID value.
3657 
3658     switch (InlineAsm::getKind(Flags)) {
3659     default:
3660       llvm_unreachable("Bad flags!");
3661     case InlineAsm::Kind_RegUse:
3662     case InlineAsm::Kind_Imm:
3663     case InlineAsm::Kind_Mem:
3664       i += NumVals;
3665       break;
3666     case InlineAsm::Kind_Clobber:
3667     case InlineAsm::Kind_RegDef:
3668     case InlineAsm::Kind_RegDefEarlyClobber: {
3669       for (; NumVals; --NumVals, ++i) {
3670         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3671         if (Reg != PPC::LR && Reg != PPC::LR8)
3672           continue;
3673         MFI.setLRStoreRequired();
3674         return Op;
3675       }
3676       break;
3677     }
3678     }
3679   }
3680 
3681   return Op;
3682 }
3683 
3684 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3685                                                 SelectionDAG &DAG) const {
3686   if (Subtarget.isAIXABI())
3687     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3688 
3689   SDValue Chain = Op.getOperand(0);
3690   SDValue Trmp = Op.getOperand(1); // trampoline
3691   SDValue FPtr = Op.getOperand(2); // nested function
3692   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3693   SDLoc dl(Op);
3694 
3695   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3696   bool isPPC64 = (PtrVT == MVT::i64);
3697   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3698 
3699   TargetLowering::ArgListTy Args;
3700   TargetLowering::ArgListEntry Entry;
3701 
3702   Entry.Ty = IntPtrTy;
3703   Entry.Node = Trmp; Args.push_back(Entry);
3704 
3705   // TrampSize == (isPPC64 ? 48 : 40);
3706   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3707                                isPPC64 ? MVT::i64 : MVT::i32);
3708   Args.push_back(Entry);
3709 
3710   Entry.Node = FPtr; Args.push_back(Entry);
3711   Entry.Node = Nest; Args.push_back(Entry);
3712 
3713   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3714   TargetLowering::CallLoweringInfo CLI(DAG);
3715   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3716       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3717       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3718 
3719   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3720   return CallResult.second;
3721 }
3722 
3723 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3724   MachineFunction &MF = DAG.getMachineFunction();
3725   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3726   EVT PtrVT = getPointerTy(MF.getDataLayout());
3727 
3728   SDLoc dl(Op);
3729 
3730   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3731     // vastart just stores the address of the VarArgsFrameIndex slot into the
3732     // memory location argument.
3733     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3734     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3735     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3736                         MachinePointerInfo(SV));
3737   }
3738 
3739   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3740   // We suppose the given va_list is already allocated.
3741   //
3742   // typedef struct {
3743   //  char gpr;     /* index into the array of 8 GPRs
3744   //                 * stored in the register save area
3745   //                 * gpr=0 corresponds to r3,
3746   //                 * gpr=1 to r4, etc.
3747   //                 */
3748   //  char fpr;     /* index into the array of 8 FPRs
3749   //                 * stored in the register save area
3750   //                 * fpr=0 corresponds to f1,
3751   //                 * fpr=1 to f2, etc.
3752   //                 */
3753   //  char *overflow_arg_area;
3754   //                /* location on stack that holds
3755   //                 * the next overflow argument
3756   //                 */
3757   //  char *reg_save_area;
3758   //               /* where r3:r10 and f1:f8 (if saved)
3759   //                * are stored
3760   //                */
3761   // } va_list[1];
3762 
3763   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3764   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3765   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3766                                             PtrVT);
3767   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3768                                  PtrVT);
3769 
3770   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3771   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3772 
3773   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3774   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3775 
3776   uint64_t FPROffset = 1;
3777   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3778 
3779   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3780 
3781   // Store first byte : number of int regs
3782   SDValue firstStore =
3783       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3784                         MachinePointerInfo(SV), MVT::i8);
3785   uint64_t nextOffset = FPROffset;
3786   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3787                                   ConstFPROffset);
3788 
3789   // Store second byte : number of float regs
3790   SDValue secondStore =
3791       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3792                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3793   nextOffset += StackOffset;
3794   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3795 
3796   // Store second word : arguments given on stack
3797   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3798                                     MachinePointerInfo(SV, nextOffset));
3799   nextOffset += FrameOffset;
3800   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3801 
3802   // Store third word : arguments given in registers
3803   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3804                       MachinePointerInfo(SV, nextOffset));
3805 }
3806 
3807 /// FPR - The set of FP registers that should be allocated for arguments
3808 /// on Darwin and AIX.
3809 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3810                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3811                                 PPC::F11, PPC::F12, PPC::F13};
3812 
3813 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3814 /// the stack.
3815 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3816                                        unsigned PtrByteSize) {
3817   unsigned ArgSize = ArgVT.getStoreSize();
3818   if (Flags.isByVal())
3819     ArgSize = Flags.getByValSize();
3820 
3821   // Round up to multiples of the pointer size, except for array members,
3822   // which are always packed.
3823   if (!Flags.isInConsecutiveRegs())
3824     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3825 
3826   return ArgSize;
3827 }
3828 
3829 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3830 /// on the stack.
3831 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3832                                          ISD::ArgFlagsTy Flags,
3833                                          unsigned PtrByteSize) {
3834   Align Alignment(PtrByteSize);
3835 
3836   // Altivec parameters are padded to a 16 byte boundary.
3837   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3838       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3839       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3840       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3841     Alignment = Align(16);
3842 
3843   // ByVal parameters are aligned as requested.
3844   if (Flags.isByVal()) {
3845     auto BVAlign = Flags.getNonZeroByValAlign();
3846     if (BVAlign > PtrByteSize) {
3847       if (BVAlign.value() % PtrByteSize != 0)
3848         llvm_unreachable(
3849             "ByVal alignment is not a multiple of the pointer size");
3850 
3851       Alignment = BVAlign;
3852     }
3853   }
3854 
3855   // Array members are always packed to their original alignment.
3856   if (Flags.isInConsecutiveRegs()) {
3857     // If the array member was split into multiple registers, the first
3858     // needs to be aligned to the size of the full type.  (Except for
3859     // ppcf128, which is only aligned as its f64 components.)
3860     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3861       Alignment = Align(OrigVT.getStoreSize());
3862     else
3863       Alignment = Align(ArgVT.getStoreSize());
3864   }
3865 
3866   return Alignment;
3867 }
3868 
3869 /// CalculateStackSlotUsed - Return whether this argument will use its
3870 /// stack slot (instead of being passed in registers).  ArgOffset,
3871 /// AvailableFPRs, and AvailableVRs must hold the current argument
3872 /// position, and will be updated to account for this argument.
3873 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3874                                    unsigned PtrByteSize, unsigned LinkageSize,
3875                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3876                                    unsigned &AvailableFPRs,
3877                                    unsigned &AvailableVRs) {
3878   bool UseMemory = false;
3879 
3880   // Respect alignment of argument on the stack.
3881   Align Alignment =
3882       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3883   ArgOffset = alignTo(ArgOffset, Alignment);
3884   // If there's no space left in the argument save area, we must
3885   // use memory (this check also catches zero-sized arguments).
3886   if (ArgOffset >= LinkageSize + ParamAreaSize)
3887     UseMemory = true;
3888 
3889   // Allocate argument on the stack.
3890   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3891   if (Flags.isInConsecutiveRegsLast())
3892     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3893   // If we overran the argument save area, we must use memory
3894   // (this check catches arguments passed partially in memory)
3895   if (ArgOffset > LinkageSize + ParamAreaSize)
3896     UseMemory = true;
3897 
3898   // However, if the argument is actually passed in an FPR or a VR,
3899   // we don't use memory after all.
3900   if (!Flags.isByVal()) {
3901     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3902       if (AvailableFPRs > 0) {
3903         --AvailableFPRs;
3904         return false;
3905       }
3906     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3907         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3908         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3909         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3910       if (AvailableVRs > 0) {
3911         --AvailableVRs;
3912         return false;
3913       }
3914   }
3915 
3916   return UseMemory;
3917 }
3918 
3919 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3920 /// ensure minimum alignment required for target.
3921 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3922                                      unsigned NumBytes) {
3923   return alignTo(NumBytes, Lowering->getStackAlign());
3924 }
3925 
3926 SDValue PPCTargetLowering::LowerFormalArguments(
3927     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3928     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3929     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3930   if (Subtarget.isAIXABI())
3931     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3932                                     InVals);
3933   if (Subtarget.is64BitELFABI())
3934     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3935                                        InVals);
3936   assert(Subtarget.is32BitELFABI());
3937   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3938                                      InVals);
3939 }
3940 
3941 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3942     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3943     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3944     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3945 
3946   // 32-bit SVR4 ABI Stack Frame Layout:
3947   //              +-----------------------------------+
3948   //        +-->  |            Back chain             |
3949   //        |     +-----------------------------------+
3950   //        |     | Floating-point register save area |
3951   //        |     +-----------------------------------+
3952   //        |     |    General register save area     |
3953   //        |     +-----------------------------------+
3954   //        |     |          CR save word             |
3955   //        |     +-----------------------------------+
3956   //        |     |         VRSAVE save word          |
3957   //        |     +-----------------------------------+
3958   //        |     |         Alignment padding         |
3959   //        |     +-----------------------------------+
3960   //        |     |     Vector register save area     |
3961   //        |     +-----------------------------------+
3962   //        |     |       Local variable space        |
3963   //        |     +-----------------------------------+
3964   //        |     |        Parameter list area        |
3965   //        |     +-----------------------------------+
3966   //        |     |           LR save word            |
3967   //        |     +-----------------------------------+
3968   // SP-->  +---  |            Back chain             |
3969   //              +-----------------------------------+
3970   //
3971   // Specifications:
3972   //   System V Application Binary Interface PowerPC Processor Supplement
3973   //   AltiVec Technology Programming Interface Manual
3974 
3975   MachineFunction &MF = DAG.getMachineFunction();
3976   MachineFrameInfo &MFI = MF.getFrameInfo();
3977   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3978 
3979   EVT PtrVT = getPointerTy(MF.getDataLayout());
3980   // Potential tail calls could cause overwriting of argument stack slots.
3981   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3982                        (CallConv == CallingConv::Fast));
3983   const Align PtrAlign(4);
3984 
3985   // Assign locations to all of the incoming arguments.
3986   SmallVector<CCValAssign, 16> ArgLocs;
3987   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3988                  *DAG.getContext());
3989 
3990   // Reserve space for the linkage area on the stack.
3991   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3992   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3993   if (useSoftFloat())
3994     CCInfo.PreAnalyzeFormalArguments(Ins);
3995 
3996   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3997   CCInfo.clearWasPPCF128();
3998 
3999   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4000     CCValAssign &VA = ArgLocs[i];
4001 
4002     // Arguments stored in registers.
4003     if (VA.isRegLoc()) {
4004       const TargetRegisterClass *RC;
4005       EVT ValVT = VA.getValVT();
4006 
4007       switch (ValVT.getSimpleVT().SimpleTy) {
4008         default:
4009           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4010         case MVT::i1:
4011         case MVT::i32:
4012           RC = &PPC::GPRCRegClass;
4013           break;
4014         case MVT::f32:
4015           if (Subtarget.hasP8Vector())
4016             RC = &PPC::VSSRCRegClass;
4017           else if (Subtarget.hasSPE())
4018             RC = &PPC::GPRCRegClass;
4019           else
4020             RC = &PPC::F4RCRegClass;
4021           break;
4022         case MVT::f64:
4023           if (Subtarget.hasVSX())
4024             RC = &PPC::VSFRCRegClass;
4025           else if (Subtarget.hasSPE())
4026             // SPE passes doubles in GPR pairs.
4027             RC = &PPC::GPRCRegClass;
4028           else
4029             RC = &PPC::F8RCRegClass;
4030           break;
4031         case MVT::v16i8:
4032         case MVT::v8i16:
4033         case MVT::v4i32:
4034           RC = &PPC::VRRCRegClass;
4035           break;
4036         case MVT::v4f32:
4037           RC = &PPC::VRRCRegClass;
4038           break;
4039         case MVT::v2f64:
4040         case MVT::v2i64:
4041           RC = &PPC::VRRCRegClass;
4042           break;
4043       }
4044 
4045       SDValue ArgValue;
4046       // Transform the arguments stored in physical registers into
4047       // virtual ones.
4048       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4049         assert(i + 1 < e && "No second half of double precision argument");
4050         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4051         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4052         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4053         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4054         if (!Subtarget.isLittleEndian())
4055           std::swap (ArgValueLo, ArgValueHi);
4056         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4057                                ArgValueHi);
4058       } else {
4059         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4060         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4061                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4062         if (ValVT == MVT::i1)
4063           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4064       }
4065 
4066       InVals.push_back(ArgValue);
4067     } else {
4068       // Argument stored in memory.
4069       assert(VA.isMemLoc());
4070 
4071       // Get the extended size of the argument type in stack
4072       unsigned ArgSize = VA.getLocVT().getStoreSize();
4073       // Get the actual size of the argument type
4074       unsigned ObjSize = VA.getValVT().getStoreSize();
4075       unsigned ArgOffset = VA.getLocMemOffset();
4076       // Stack objects in PPC32 are right justified.
4077       ArgOffset += ArgSize - ObjSize;
4078       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4079 
4080       // Create load nodes to retrieve arguments from the stack.
4081       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4082       InVals.push_back(
4083           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4084     }
4085   }
4086 
4087   // Assign locations to all of the incoming aggregate by value arguments.
4088   // Aggregates passed by value are stored in the local variable space of the
4089   // caller's stack frame, right above the parameter list area.
4090   SmallVector<CCValAssign, 16> ByValArgLocs;
4091   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4092                       ByValArgLocs, *DAG.getContext());
4093 
4094   // Reserve stack space for the allocations in CCInfo.
4095   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4096 
4097   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4098 
4099   // Area that is at least reserved in the caller of this function.
4100   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4101   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4102 
4103   // Set the size that is at least reserved in caller of this function.  Tail
4104   // call optimized function's reserved stack space needs to be aligned so that
4105   // taking the difference between two stack areas will result in an aligned
4106   // stack.
4107   MinReservedArea =
4108       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4109   FuncInfo->setMinReservedArea(MinReservedArea);
4110 
4111   SmallVector<SDValue, 8> MemOps;
4112 
4113   // If the function takes variable number of arguments, make a frame index for
4114   // the start of the first vararg value... for expansion of llvm.va_start.
4115   if (isVarArg) {
4116     static const MCPhysReg GPArgRegs[] = {
4117       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4118       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4119     };
4120     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4121 
4122     static const MCPhysReg FPArgRegs[] = {
4123       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4124       PPC::F8
4125     };
4126     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4127 
4128     if (useSoftFloat() || hasSPE())
4129        NumFPArgRegs = 0;
4130 
4131     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4132     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4133 
4134     // Make room for NumGPArgRegs and NumFPArgRegs.
4135     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4136                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4137 
4138     FuncInfo->setVarArgsStackOffset(
4139       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4140                             CCInfo.getNextStackOffset(), true));
4141 
4142     FuncInfo->setVarArgsFrameIndex(
4143         MFI.CreateStackObject(Depth, Align(8), false));
4144     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4145 
4146     // The fixed integer arguments of a variadic function are stored to the
4147     // VarArgsFrameIndex on the stack so that they may be loaded by
4148     // dereferencing the result of va_next.
4149     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4150       // Get an existing live-in vreg, or add a new one.
4151       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4152       if (!VReg)
4153         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4154 
4155       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4156       SDValue Store =
4157           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4158       MemOps.push_back(Store);
4159       // Increment the address by four for the next argument to store
4160       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4161       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4162     }
4163 
4164     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4165     // is set.
4166     // The double arguments are stored to the VarArgsFrameIndex
4167     // on the stack.
4168     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4169       // Get an existing live-in vreg, or add a new one.
4170       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4171       if (!VReg)
4172         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4173 
4174       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4175       SDValue Store =
4176           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4177       MemOps.push_back(Store);
4178       // Increment the address by eight for the next argument to store
4179       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4180                                          PtrVT);
4181       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4182     }
4183   }
4184 
4185   if (!MemOps.empty())
4186     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4187 
4188   return Chain;
4189 }
4190 
4191 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4192 // value to MVT::i64 and then truncate to the correct register size.
4193 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4194                                              EVT ObjectVT, SelectionDAG &DAG,
4195                                              SDValue ArgVal,
4196                                              const SDLoc &dl) const {
4197   if (Flags.isSExt())
4198     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4199                          DAG.getValueType(ObjectVT));
4200   else if (Flags.isZExt())
4201     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4202                          DAG.getValueType(ObjectVT));
4203 
4204   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4205 }
4206 
4207 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4208     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4209     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4210     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4211   // TODO: add description of PPC stack frame format, or at least some docs.
4212   //
4213   bool isELFv2ABI = Subtarget.isELFv2ABI();
4214   bool isLittleEndian = Subtarget.isLittleEndian();
4215   MachineFunction &MF = DAG.getMachineFunction();
4216   MachineFrameInfo &MFI = MF.getFrameInfo();
4217   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4218 
4219   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4220          "fastcc not supported on varargs functions");
4221 
4222   EVT PtrVT = getPointerTy(MF.getDataLayout());
4223   // Potential tail calls could cause overwriting of argument stack slots.
4224   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4225                        (CallConv == CallingConv::Fast));
4226   unsigned PtrByteSize = 8;
4227   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4228 
4229   static const MCPhysReg GPR[] = {
4230     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4231     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4232   };
4233   static const MCPhysReg VR[] = {
4234     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4235     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4236   };
4237 
4238   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4239   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4240   const unsigned Num_VR_Regs  = array_lengthof(VR);
4241 
4242   // Do a first pass over the arguments to determine whether the ABI
4243   // guarantees that our caller has allocated the parameter save area
4244   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4245   // in the ELFv2 ABI, it is true if this is a vararg function or if
4246   // any parameter is located in a stack slot.
4247 
4248   bool HasParameterArea = !isELFv2ABI || isVarArg;
4249   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4250   unsigned NumBytes = LinkageSize;
4251   unsigned AvailableFPRs = Num_FPR_Regs;
4252   unsigned AvailableVRs = Num_VR_Regs;
4253   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4254     if (Ins[i].Flags.isNest())
4255       continue;
4256 
4257     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4258                                PtrByteSize, LinkageSize, ParamAreaSize,
4259                                NumBytes, AvailableFPRs, AvailableVRs))
4260       HasParameterArea = true;
4261   }
4262 
4263   // Add DAG nodes to load the arguments or copy them out of registers.  On
4264   // entry to a function on PPC, the arguments start after the linkage area,
4265   // although the first ones are often in registers.
4266 
4267   unsigned ArgOffset = LinkageSize;
4268   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4269   SmallVector<SDValue, 8> MemOps;
4270   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4271   unsigned CurArgIdx = 0;
4272   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4273     SDValue ArgVal;
4274     bool needsLoad = false;
4275     EVT ObjectVT = Ins[ArgNo].VT;
4276     EVT OrigVT = Ins[ArgNo].ArgVT;
4277     unsigned ObjSize = ObjectVT.getStoreSize();
4278     unsigned ArgSize = ObjSize;
4279     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4280     if (Ins[ArgNo].isOrigArg()) {
4281       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4282       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4283     }
4284     // We re-align the argument offset for each argument, except when using the
4285     // fast calling convention, when we need to make sure we do that only when
4286     // we'll actually use a stack slot.
4287     unsigned CurArgOffset;
4288     Align Alignment;
4289     auto ComputeArgOffset = [&]() {
4290       /* Respect alignment of argument on the stack.  */
4291       Alignment =
4292           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4293       ArgOffset = alignTo(ArgOffset, Alignment);
4294       CurArgOffset = ArgOffset;
4295     };
4296 
4297     if (CallConv != CallingConv::Fast) {
4298       ComputeArgOffset();
4299 
4300       /* Compute GPR index associated with argument offset.  */
4301       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4302       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4303     }
4304 
4305     // FIXME the codegen can be much improved in some cases.
4306     // We do not have to keep everything in memory.
4307     if (Flags.isByVal()) {
4308       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4309 
4310       if (CallConv == CallingConv::Fast)
4311         ComputeArgOffset();
4312 
4313       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4314       ObjSize = Flags.getByValSize();
4315       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4316       // Empty aggregate parameters do not take up registers.  Examples:
4317       //   struct { } a;
4318       //   union  { } b;
4319       //   int c[0];
4320       // etc.  However, we have to provide a place-holder in InVals, so
4321       // pretend we have an 8-byte item at the current address for that
4322       // purpose.
4323       if (!ObjSize) {
4324         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4325         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4326         InVals.push_back(FIN);
4327         continue;
4328       }
4329 
4330       // Create a stack object covering all stack doublewords occupied
4331       // by the argument.  If the argument is (fully or partially) on
4332       // the stack, or if the argument is fully in registers but the
4333       // caller has allocated the parameter save anyway, we can refer
4334       // directly to the caller's stack frame.  Otherwise, create a
4335       // local copy in our own frame.
4336       int FI;
4337       if (HasParameterArea ||
4338           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4339         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4340       else
4341         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4342       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4343 
4344       // Handle aggregates smaller than 8 bytes.
4345       if (ObjSize < PtrByteSize) {
4346         // The value of the object is its address, which differs from the
4347         // address of the enclosing doubleword on big-endian systems.
4348         SDValue Arg = FIN;
4349         if (!isLittleEndian) {
4350           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4351           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4352         }
4353         InVals.push_back(Arg);
4354 
4355         if (GPR_idx != Num_GPR_Regs) {
4356           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4357           FuncInfo->addLiveInAttr(VReg, Flags);
4358           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4359           SDValue Store;
4360 
4361           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4362             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4363                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4364             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4365                                       MachinePointerInfo(&*FuncArg), ObjType);
4366           } else {
4367             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4368             // store the whole register as-is to the parameter save area
4369             // slot.
4370             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4371                                  MachinePointerInfo(&*FuncArg));
4372           }
4373 
4374           MemOps.push_back(Store);
4375         }
4376         // Whether we copied from a register or not, advance the offset
4377         // into the parameter save area by a full doubleword.
4378         ArgOffset += PtrByteSize;
4379         continue;
4380       }
4381 
4382       // The value of the object is its address, which is the address of
4383       // its first stack doubleword.
4384       InVals.push_back(FIN);
4385 
4386       // Store whatever pieces of the object are in registers to memory.
4387       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4388         if (GPR_idx == Num_GPR_Regs)
4389           break;
4390 
4391         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4392         FuncInfo->addLiveInAttr(VReg, Flags);
4393         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4394         SDValue Addr = FIN;
4395         if (j) {
4396           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4397           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4398         }
4399         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4400                                      MachinePointerInfo(&*FuncArg, j));
4401         MemOps.push_back(Store);
4402         ++GPR_idx;
4403       }
4404       ArgOffset += ArgSize;
4405       continue;
4406     }
4407 
4408     switch (ObjectVT.getSimpleVT().SimpleTy) {
4409     default: llvm_unreachable("Unhandled argument type!");
4410     case MVT::i1:
4411     case MVT::i32:
4412     case MVT::i64:
4413       if (Flags.isNest()) {
4414         // The 'nest' parameter, if any, is passed in R11.
4415         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4416         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4417 
4418         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4419           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4420 
4421         break;
4422       }
4423 
4424       // These can be scalar arguments or elements of an integer array type
4425       // passed directly.  Clang may use those instead of "byval" aggregate
4426       // types to avoid forcing arguments to memory unnecessarily.
4427       if (GPR_idx != Num_GPR_Regs) {
4428         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4429         FuncInfo->addLiveInAttr(VReg, Flags);
4430         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4431 
4432         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4433           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4434           // value to MVT::i64 and then truncate to the correct register size.
4435           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4436       } else {
4437         if (CallConv == CallingConv::Fast)
4438           ComputeArgOffset();
4439 
4440         needsLoad = true;
4441         ArgSize = PtrByteSize;
4442       }
4443       if (CallConv != CallingConv::Fast || needsLoad)
4444         ArgOffset += 8;
4445       break;
4446 
4447     case MVT::f32:
4448     case MVT::f64:
4449       // These can be scalar arguments or elements of a float array type
4450       // passed directly.  The latter are used to implement ELFv2 homogenous
4451       // float aggregates.
4452       if (FPR_idx != Num_FPR_Regs) {
4453         unsigned VReg;
4454 
4455         if (ObjectVT == MVT::f32)
4456           VReg = MF.addLiveIn(FPR[FPR_idx],
4457                               Subtarget.hasP8Vector()
4458                                   ? &PPC::VSSRCRegClass
4459                                   : &PPC::F4RCRegClass);
4460         else
4461           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4462                                                 ? &PPC::VSFRCRegClass
4463                                                 : &PPC::F8RCRegClass);
4464 
4465         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4466         ++FPR_idx;
4467       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4468         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4469         // once we support fp <-> gpr moves.
4470 
4471         // This can only ever happen in the presence of f32 array types,
4472         // since otherwise we never run out of FPRs before running out
4473         // of GPRs.
4474         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4475         FuncInfo->addLiveInAttr(VReg, Flags);
4476         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4477 
4478         if (ObjectVT == MVT::f32) {
4479           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4480             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4481                                  DAG.getConstant(32, dl, MVT::i32));
4482           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4483         }
4484 
4485         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4486       } else {
4487         if (CallConv == CallingConv::Fast)
4488           ComputeArgOffset();
4489 
4490         needsLoad = true;
4491       }
4492 
4493       // When passing an array of floats, the array occupies consecutive
4494       // space in the argument area; only round up to the next doubleword
4495       // at the end of the array.  Otherwise, each float takes 8 bytes.
4496       if (CallConv != CallingConv::Fast || needsLoad) {
4497         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4498         ArgOffset += ArgSize;
4499         if (Flags.isInConsecutiveRegsLast())
4500           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4501       }
4502       break;
4503     case MVT::v4f32:
4504     case MVT::v4i32:
4505     case MVT::v8i16:
4506     case MVT::v16i8:
4507     case MVT::v2f64:
4508     case MVT::v2i64:
4509     case MVT::v1i128:
4510     case MVT::f128:
4511       // These can be scalar arguments or elements of a vector array type
4512       // passed directly.  The latter are used to implement ELFv2 homogenous
4513       // vector aggregates.
4514       if (VR_idx != Num_VR_Regs) {
4515         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4516         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4517         ++VR_idx;
4518       } else {
4519         if (CallConv == CallingConv::Fast)
4520           ComputeArgOffset();
4521         needsLoad = true;
4522       }
4523       if (CallConv != CallingConv::Fast || needsLoad)
4524         ArgOffset += 16;
4525       break;
4526     }
4527 
4528     // We need to load the argument to a virtual register if we determined
4529     // above that we ran out of physical registers of the appropriate type.
4530     if (needsLoad) {
4531       if (ObjSize < ArgSize && !isLittleEndian)
4532         CurArgOffset += ArgSize - ObjSize;
4533       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4534       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4535       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4536     }
4537 
4538     InVals.push_back(ArgVal);
4539   }
4540 
4541   // Area that is at least reserved in the caller of this function.
4542   unsigned MinReservedArea;
4543   if (HasParameterArea)
4544     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4545   else
4546     MinReservedArea = LinkageSize;
4547 
4548   // Set the size that is at least reserved in caller of this function.  Tail
4549   // call optimized functions' reserved stack space needs to be aligned so that
4550   // taking the difference between two stack areas will result in an aligned
4551   // stack.
4552   MinReservedArea =
4553       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4554   FuncInfo->setMinReservedArea(MinReservedArea);
4555 
4556   // If the function takes variable number of arguments, make a frame index for
4557   // the start of the first vararg value... for expansion of llvm.va_start.
4558   // On ELFv2ABI spec, it writes:
4559   // C programs that are intended to be *portable* across different compilers
4560   // and architectures must use the header file <stdarg.h> to deal with variable
4561   // argument lists.
4562   if (isVarArg && MFI.hasVAStart()) {
4563     int Depth = ArgOffset;
4564 
4565     FuncInfo->setVarArgsFrameIndex(
4566       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4567     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4568 
4569     // If this function is vararg, store any remaining integer argument regs
4570     // to their spots on the stack so that they may be loaded by dereferencing
4571     // the result of va_next.
4572     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4573          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4574       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4575       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4576       SDValue Store =
4577           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4578       MemOps.push_back(Store);
4579       // Increment the address by four for the next argument to store
4580       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4581       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4582     }
4583   }
4584 
4585   if (!MemOps.empty())
4586     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4587 
4588   return Chain;
4589 }
4590 
4591 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4592 /// adjusted to accommodate the arguments for the tailcall.
4593 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4594                                    unsigned ParamSize) {
4595 
4596   if (!isTailCall) return 0;
4597 
4598   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4599   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4600   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4601   // Remember only if the new adjustment is bigger.
4602   if (SPDiff < FI->getTailCallSPDelta())
4603     FI->setTailCallSPDelta(SPDiff);
4604 
4605   return SPDiff;
4606 }
4607 
4608 static bool isFunctionGlobalAddress(SDValue Callee);
4609 
4610 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4611                               const TargetMachine &TM) {
4612   // It does not make sense to call callsShareTOCBase() with a caller that
4613   // is PC Relative since PC Relative callers do not have a TOC.
4614 #ifndef NDEBUG
4615   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4616   assert(!STICaller->isUsingPCRelativeCalls() &&
4617          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4618 #endif
4619 
4620   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4621   // don't have enough information to determine if the caller and callee share
4622   // the same  TOC base, so we have to pessimistically assume they don't for
4623   // correctness.
4624   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4625   if (!G)
4626     return false;
4627 
4628   const GlobalValue *GV = G->getGlobal();
4629 
4630   // If the callee is preemptable, then the static linker will use a plt-stub
4631   // which saves the toc to the stack, and needs a nop after the call
4632   // instruction to convert to a toc-restore.
4633   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4634     return false;
4635 
4636   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4637   // We may need a TOC restore in the situation where the caller requires a
4638   // valid TOC but the callee is PC Relative and does not.
4639   const Function *F = dyn_cast<Function>(GV);
4640   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4641 
4642   // If we have an Alias we can try to get the function from there.
4643   if (Alias) {
4644     const GlobalObject *GlobalObj = Alias->getBaseObject();
4645     F = dyn_cast<Function>(GlobalObj);
4646   }
4647 
4648   // If we still have no valid function pointer we do not have enough
4649   // information to determine if the callee uses PC Relative calls so we must
4650   // assume that it does.
4651   if (!F)
4652     return false;
4653 
4654   // If the callee uses PC Relative we cannot guarantee that the callee won't
4655   // clobber the TOC of the caller and so we must assume that the two
4656   // functions do not share a TOC base.
4657   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4658   if (STICallee->isUsingPCRelativeCalls())
4659     return false;
4660 
4661   // If the GV is not a strong definition then we need to assume it can be
4662   // replaced by another function at link time. The function that replaces
4663   // it may not share the same TOC as the caller since the callee may be
4664   // replaced by a PC Relative version of the same function.
4665   if (!GV->isStrongDefinitionForLinker())
4666     return false;
4667 
4668   // The medium and large code models are expected to provide a sufficiently
4669   // large TOC to provide all data addressing needs of a module with a
4670   // single TOC.
4671   if (CodeModel::Medium == TM.getCodeModel() ||
4672       CodeModel::Large == TM.getCodeModel())
4673     return true;
4674 
4675   // Any explicitly-specified sections and section prefixes must also match.
4676   // Also, if we're using -ffunction-sections, then each function is always in
4677   // a different section (the same is true for COMDAT functions).
4678   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4679       GV->getSection() != Caller->getSection())
4680     return false;
4681   if (const auto *F = dyn_cast<Function>(GV)) {
4682     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4683       return false;
4684   }
4685 
4686   return true;
4687 }
4688 
4689 static bool
4690 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4691                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4692   assert(Subtarget.is64BitELFABI());
4693 
4694   const unsigned PtrByteSize = 8;
4695   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4696 
4697   static const MCPhysReg GPR[] = {
4698     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4699     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4700   };
4701   static const MCPhysReg VR[] = {
4702     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4703     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4704   };
4705 
4706   const unsigned NumGPRs = array_lengthof(GPR);
4707   const unsigned NumFPRs = 13;
4708   const unsigned NumVRs = array_lengthof(VR);
4709   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4710 
4711   unsigned NumBytes = LinkageSize;
4712   unsigned AvailableFPRs = NumFPRs;
4713   unsigned AvailableVRs = NumVRs;
4714 
4715   for (const ISD::OutputArg& Param : Outs) {
4716     if (Param.Flags.isNest()) continue;
4717 
4718     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4719                                LinkageSize, ParamAreaSize, NumBytes,
4720                                AvailableFPRs, AvailableVRs))
4721       return true;
4722   }
4723   return false;
4724 }
4725 
4726 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4727   if (CB.arg_size() != CallerFn->arg_size())
4728     return false;
4729 
4730   auto CalleeArgIter = CB.arg_begin();
4731   auto CalleeArgEnd = CB.arg_end();
4732   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4733 
4734   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4735     const Value* CalleeArg = *CalleeArgIter;
4736     const Value* CallerArg = &(*CallerArgIter);
4737     if (CalleeArg == CallerArg)
4738       continue;
4739 
4740     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4741     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4742     //      }
4743     // 1st argument of callee is undef and has the same type as caller.
4744     if (CalleeArg->getType() == CallerArg->getType() &&
4745         isa<UndefValue>(CalleeArg))
4746       continue;
4747 
4748     return false;
4749   }
4750 
4751   return true;
4752 }
4753 
4754 // Returns true if TCO is possible between the callers and callees
4755 // calling conventions.
4756 static bool
4757 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4758                                     CallingConv::ID CalleeCC) {
4759   // Tail calls are possible with fastcc and ccc.
4760   auto isTailCallableCC  = [] (CallingConv::ID CC){
4761       return  CC == CallingConv::C || CC == CallingConv::Fast;
4762   };
4763   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4764     return false;
4765 
4766   // We can safely tail call both fastcc and ccc callees from a c calling
4767   // convention caller. If the caller is fastcc, we may have less stack space
4768   // than a non-fastcc caller with the same signature so disable tail-calls in
4769   // that case.
4770   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4771 }
4772 
4773 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4774     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4775     const SmallVectorImpl<ISD::OutputArg> &Outs,
4776     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4777   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4778 
4779   if (DisableSCO && !TailCallOpt) return false;
4780 
4781   // Variadic argument functions are not supported.
4782   if (isVarArg) return false;
4783 
4784   auto &Caller = DAG.getMachineFunction().getFunction();
4785   // Check that the calling conventions are compatible for tco.
4786   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4787     return false;
4788 
4789   // Caller contains any byval parameter is not supported.
4790   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4791     return false;
4792 
4793   // Callee contains any byval parameter is not supported, too.
4794   // Note: This is a quick work around, because in some cases, e.g.
4795   // caller's stack size > callee's stack size, we are still able to apply
4796   // sibling call optimization. For example, gcc is able to do SCO for caller1
4797   // in the following example, but not for caller2.
4798   //   struct test {
4799   //     long int a;
4800   //     char ary[56];
4801   //   } gTest;
4802   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4803   //     b->a = v.a;
4804   //     return 0;
4805   //   }
4806   //   void caller1(struct test a, struct test c, struct test *b) {
4807   //     callee(gTest, b); }
4808   //   void caller2(struct test *b) { callee(gTest, b); }
4809   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4810     return false;
4811 
4812   // If callee and caller use different calling conventions, we cannot pass
4813   // parameters on stack since offsets for the parameter area may be different.
4814   if (Caller.getCallingConv() != CalleeCC &&
4815       needStackSlotPassParameters(Subtarget, Outs))
4816     return false;
4817 
4818   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4819   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4820   // callee potentially have different TOC bases then we cannot tail call since
4821   // we need to restore the TOC pointer after the call.
4822   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4823   // We cannot guarantee this for indirect calls or calls to external functions.
4824   // When PC-Relative addressing is used, the concept of the TOC is no longer
4825   // applicable so this check is not required.
4826   // Check first for indirect calls.
4827   if (!Subtarget.isUsingPCRelativeCalls() &&
4828       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4829     return false;
4830 
4831   // Check if we share the TOC base.
4832   if (!Subtarget.isUsingPCRelativeCalls() &&
4833       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4834     return false;
4835 
4836   // TCO allows altering callee ABI, so we don't have to check further.
4837   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4838     return true;
4839 
4840   if (DisableSCO) return false;
4841 
4842   // If callee use the same argument list that caller is using, then we can
4843   // apply SCO on this case. If it is not, then we need to check if callee needs
4844   // stack for passing arguments.
4845   // PC Relative tail calls may not have a CallBase.
4846   // If there is no CallBase we cannot verify if we have the same argument
4847   // list so assume that we don't have the same argument list.
4848   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4849       needStackSlotPassParameters(Subtarget, Outs))
4850     return false;
4851   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4852     return false;
4853 
4854   return true;
4855 }
4856 
4857 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4858 /// for tail call optimization. Targets which want to do tail call
4859 /// optimization should implement this function.
4860 bool
4861 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4862                                                      CallingConv::ID CalleeCC,
4863                                                      bool isVarArg,
4864                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4865                                                      SelectionDAG& DAG) const {
4866   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4867     return false;
4868 
4869   // Variable argument functions are not supported.
4870   if (isVarArg)
4871     return false;
4872 
4873   MachineFunction &MF = DAG.getMachineFunction();
4874   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4875   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4876     // Functions containing by val parameters are not supported.
4877     for (unsigned i = 0; i != Ins.size(); i++) {
4878        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4879        if (Flags.isByVal()) return false;
4880     }
4881 
4882     // Non-PIC/GOT tail calls are supported.
4883     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4884       return true;
4885 
4886     // At the moment we can only do local tail calls (in same module, hidden
4887     // or protected) if we are generating PIC.
4888     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4889       return G->getGlobal()->hasHiddenVisibility()
4890           || G->getGlobal()->hasProtectedVisibility();
4891   }
4892 
4893   return false;
4894 }
4895 
4896 /// isCallCompatibleAddress - Return the immediate to use if the specified
4897 /// 32-bit value is representable in the immediate field of a BxA instruction.
4898 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4899   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4900   if (!C) return nullptr;
4901 
4902   int Addr = C->getZExtValue();
4903   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4904       SignExtend32<26>(Addr) != Addr)
4905     return nullptr;  // Top 6 bits have to be sext of immediate.
4906 
4907   return DAG
4908       .getConstant(
4909           (int)C->getZExtValue() >> 2, SDLoc(Op),
4910           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4911       .getNode();
4912 }
4913 
4914 namespace {
4915 
4916 struct TailCallArgumentInfo {
4917   SDValue Arg;
4918   SDValue FrameIdxOp;
4919   int FrameIdx = 0;
4920 
4921   TailCallArgumentInfo() = default;
4922 };
4923 
4924 } // end anonymous namespace
4925 
4926 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4927 static void StoreTailCallArgumentsToStackSlot(
4928     SelectionDAG &DAG, SDValue Chain,
4929     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4930     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4931   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4932     SDValue Arg = TailCallArgs[i].Arg;
4933     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4934     int FI = TailCallArgs[i].FrameIdx;
4935     // Store relative to framepointer.
4936     MemOpChains.push_back(DAG.getStore(
4937         Chain, dl, Arg, FIN,
4938         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4939   }
4940 }
4941 
4942 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4943 /// the appropriate stack slot for the tail call optimized function call.
4944 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4945                                              SDValue OldRetAddr, SDValue OldFP,
4946                                              int SPDiff, const SDLoc &dl) {
4947   if (SPDiff) {
4948     // Calculate the new stack slot for the return address.
4949     MachineFunction &MF = DAG.getMachineFunction();
4950     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4951     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4952     bool isPPC64 = Subtarget.isPPC64();
4953     int SlotSize = isPPC64 ? 8 : 4;
4954     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4955     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4956                                                          NewRetAddrLoc, true);
4957     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4958     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4959     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4960                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4961   }
4962   return Chain;
4963 }
4964 
4965 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4966 /// the position of the argument.
4967 static void
4968 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4969                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4970                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4971   int Offset = ArgOffset + SPDiff;
4972   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4973   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4974   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4975   SDValue FIN = DAG.getFrameIndex(FI, VT);
4976   TailCallArgumentInfo Info;
4977   Info.Arg = Arg;
4978   Info.FrameIdxOp = FIN;
4979   Info.FrameIdx = FI;
4980   TailCallArguments.push_back(Info);
4981 }
4982 
4983 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4984 /// stack slot. Returns the chain as result and the loaded frame pointers in
4985 /// LROpOut/FPOpout. Used when tail calling.
4986 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4987     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4988     SDValue &FPOpOut, const SDLoc &dl) const {
4989   if (SPDiff) {
4990     // Load the LR and FP stack slot for later adjusting.
4991     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4992     LROpOut = getReturnAddrFrameIndex(DAG);
4993     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4994     Chain = SDValue(LROpOut.getNode(), 1);
4995   }
4996   return Chain;
4997 }
4998 
4999 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5000 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5001 /// specified by the specific parameter attribute. The copy will be passed as
5002 /// a byval function parameter.
5003 /// Sometimes what we are copying is the end of a larger object, the part that
5004 /// does not fit in registers.
5005 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5006                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5007                                          SelectionDAG &DAG, const SDLoc &dl) {
5008   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5009   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5010                        Flags.getNonZeroByValAlign(), false, false, false,
5011                        MachinePointerInfo(), MachinePointerInfo());
5012 }
5013 
5014 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5015 /// tail calls.
5016 static void LowerMemOpCallTo(
5017     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5018     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5019     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5020     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5021   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5022   if (!isTailCall) {
5023     if (isVector) {
5024       SDValue StackPtr;
5025       if (isPPC64)
5026         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5027       else
5028         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5029       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5030                            DAG.getConstant(ArgOffset, dl, PtrVT));
5031     }
5032     MemOpChains.push_back(
5033         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5034     // Calculate and remember argument location.
5035   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5036                                   TailCallArguments);
5037 }
5038 
5039 static void
5040 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5041                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5042                 SDValue FPOp,
5043                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5044   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5045   // might overwrite each other in case of tail call optimization.
5046   SmallVector<SDValue, 8> MemOpChains2;
5047   // Do not flag preceding copytoreg stuff together with the following stuff.
5048   InFlag = SDValue();
5049   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5050                                     MemOpChains2, dl);
5051   if (!MemOpChains2.empty())
5052     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5053 
5054   // Store the return address to the appropriate stack slot.
5055   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5056 
5057   // Emit callseq_end just before tailcall node.
5058   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5059                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5060   InFlag = Chain.getValue(1);
5061 }
5062 
5063 // Is this global address that of a function that can be called by name? (as
5064 // opposed to something that must hold a descriptor for an indirect call).
5065 static bool isFunctionGlobalAddress(SDValue Callee) {
5066   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5067     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5068         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5069       return false;
5070 
5071     return G->getGlobal()->getValueType()->isFunctionTy();
5072   }
5073 
5074   return false;
5075 }
5076 
5077 SDValue PPCTargetLowering::LowerCallResult(
5078     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5079     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5080     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5081   SmallVector<CCValAssign, 16> RVLocs;
5082   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5083                     *DAG.getContext());
5084 
5085   CCRetInfo.AnalyzeCallResult(
5086       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5087                ? RetCC_PPC_Cold
5088                : RetCC_PPC);
5089 
5090   // Copy all of the result registers out of their specified physreg.
5091   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5092     CCValAssign &VA = RVLocs[i];
5093     assert(VA.isRegLoc() && "Can only return in registers!");
5094 
5095     SDValue Val;
5096 
5097     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5098       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5099                                       InFlag);
5100       Chain = Lo.getValue(1);
5101       InFlag = Lo.getValue(2);
5102       VA = RVLocs[++i]; // skip ahead to next loc
5103       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5104                                       InFlag);
5105       Chain = Hi.getValue(1);
5106       InFlag = Hi.getValue(2);
5107       if (!Subtarget.isLittleEndian())
5108         std::swap (Lo, Hi);
5109       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5110     } else {
5111       Val = DAG.getCopyFromReg(Chain, dl,
5112                                VA.getLocReg(), VA.getLocVT(), InFlag);
5113       Chain = Val.getValue(1);
5114       InFlag = Val.getValue(2);
5115     }
5116 
5117     switch (VA.getLocInfo()) {
5118     default: llvm_unreachable("Unknown loc info!");
5119     case CCValAssign::Full: break;
5120     case CCValAssign::AExt:
5121       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5122       break;
5123     case CCValAssign::ZExt:
5124       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5125                         DAG.getValueType(VA.getValVT()));
5126       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5127       break;
5128     case CCValAssign::SExt:
5129       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5130                         DAG.getValueType(VA.getValVT()));
5131       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5132       break;
5133     }
5134 
5135     InVals.push_back(Val);
5136   }
5137 
5138   return Chain;
5139 }
5140 
5141 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5142                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5143   // PatchPoint calls are not indirect.
5144   if (isPatchPoint)
5145     return false;
5146 
5147   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5148     return false;
5149 
5150   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5151   // becuase the immediate function pointer points to a descriptor instead of
5152   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5153   // pointer immediate points to the global entry point, while the BLA would
5154   // need to jump to the local entry point (see rL211174).
5155   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5156       isBLACompatibleAddress(Callee, DAG))
5157     return false;
5158 
5159   return true;
5160 }
5161 
5162 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5163 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5164   return Subtarget.isAIXABI() ||
5165          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5166 }
5167 
5168 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5169                               const Function &Caller,
5170                               const SDValue &Callee,
5171                               const PPCSubtarget &Subtarget,
5172                               const TargetMachine &TM) {
5173   if (CFlags.IsTailCall)
5174     return PPCISD::TC_RETURN;
5175 
5176   // This is a call through a function pointer.
5177   if (CFlags.IsIndirect) {
5178     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5179     // indirect calls. The save of the caller's TOC pointer to the stack will be
5180     // inserted into the DAG as part of call lowering. The restore of the TOC
5181     // pointer is modeled by using a pseudo instruction for the call opcode that
5182     // represents the 2 instruction sequence of an indirect branch and link,
5183     // immediately followed by a load of the TOC pointer from the the stack save
5184     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5185     // as it is not saved or used.
5186     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5187                                                : PPCISD::BCTRL;
5188   }
5189 
5190   if (Subtarget.isUsingPCRelativeCalls()) {
5191     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5192     return PPCISD::CALL_NOTOC;
5193   }
5194 
5195   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5196   // immediately following the call instruction if the caller and callee may
5197   // have different TOC bases. At link time if the linker determines the calls
5198   // may not share a TOC base, the call is redirected to a trampoline inserted
5199   // by the linker. The trampoline will (among other things) save the callers
5200   // TOC pointer at an ABI designated offset in the linkage area and the linker
5201   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5202   // into gpr2.
5203   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5204     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5205                                                   : PPCISD::CALL_NOP;
5206 
5207   return PPCISD::CALL;
5208 }
5209 
5210 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5211                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5212   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5213     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5214       return SDValue(Dest, 0);
5215 
5216   // Returns true if the callee is local, and false otherwise.
5217   auto isLocalCallee = [&]() {
5218     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5219     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5220     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5221 
5222     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5223            !dyn_cast_or_null<GlobalIFunc>(GV);
5224   };
5225 
5226   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5227   // a static relocation model causes some versions of GNU LD (2.17.50, at
5228   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5229   // built with secure-PLT.
5230   bool UsePlt =
5231       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5232       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5233 
5234   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5235     const TargetMachine &TM = Subtarget.getTargetMachine();
5236     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5237     MCSymbolXCOFF *S =
5238         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5239 
5240     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5241     return DAG.getMCSymbol(S, PtrVT);
5242   };
5243 
5244   if (isFunctionGlobalAddress(Callee)) {
5245     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5246 
5247     if (Subtarget.isAIXABI()) {
5248       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5249       return getAIXFuncEntryPointSymbolSDNode(GV);
5250     }
5251     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5252                                       UsePlt ? PPCII::MO_PLT : 0);
5253   }
5254 
5255   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5256     const char *SymName = S->getSymbol();
5257     if (Subtarget.isAIXABI()) {
5258       // If there exists a user-declared function whose name is the same as the
5259       // ExternalSymbol's, then we pick up the user-declared version.
5260       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5261       if (const Function *F =
5262               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5263         return getAIXFuncEntryPointSymbolSDNode(F);
5264 
5265       // On AIX, direct function calls reference the symbol for the function's
5266       // entry point, which is named by prepending a "." before the function's
5267       // C-linkage name. A Qualname is returned here because an external
5268       // function entry point is a csect with XTY_ER property.
5269       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5270         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5271         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5272             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5273             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5274         return Sec->getQualNameSymbol();
5275       };
5276 
5277       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5278     }
5279     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5280                                        UsePlt ? PPCII::MO_PLT : 0);
5281   }
5282 
5283   // No transformation needed.
5284   assert(Callee.getNode() && "What no callee?");
5285   return Callee;
5286 }
5287 
5288 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5289   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5290          "Expected a CALLSEQ_STARTSDNode.");
5291 
5292   // The last operand is the chain, except when the node has glue. If the node
5293   // has glue, then the last operand is the glue, and the chain is the second
5294   // last operand.
5295   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5296   if (LastValue.getValueType() != MVT::Glue)
5297     return LastValue;
5298 
5299   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5300 }
5301 
5302 // Creates the node that moves a functions address into the count register
5303 // to prepare for an indirect call instruction.
5304 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5305                                 SDValue &Glue, SDValue &Chain,
5306                                 const SDLoc &dl) {
5307   SDValue MTCTROps[] = {Chain, Callee, Glue};
5308   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5309   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5310                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5311   // The glue is the second value produced.
5312   Glue = Chain.getValue(1);
5313 }
5314 
5315 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5316                                           SDValue &Glue, SDValue &Chain,
5317                                           SDValue CallSeqStart,
5318                                           const CallBase *CB, const SDLoc &dl,
5319                                           bool hasNest,
5320                                           const PPCSubtarget &Subtarget) {
5321   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5322   // entry point, but to the function descriptor (the function entry point
5323   // address is part of the function descriptor though).
5324   // The function descriptor is a three doubleword structure with the
5325   // following fields: function entry point, TOC base address and
5326   // environment pointer.
5327   // Thus for a call through a function pointer, the following actions need
5328   // to be performed:
5329   //   1. Save the TOC of the caller in the TOC save area of its stack
5330   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5331   //   2. Load the address of the function entry point from the function
5332   //      descriptor.
5333   //   3. Load the TOC of the callee from the function descriptor into r2.
5334   //   4. Load the environment pointer from the function descriptor into
5335   //      r11.
5336   //   5. Branch to the function entry point address.
5337   //   6. On return of the callee, the TOC of the caller needs to be
5338   //      restored (this is done in FinishCall()).
5339   //
5340   // The loads are scheduled at the beginning of the call sequence, and the
5341   // register copies are flagged together to ensure that no other
5342   // operations can be scheduled in between. E.g. without flagging the
5343   // copies together, a TOC access in the caller could be scheduled between
5344   // the assignment of the callee TOC and the branch to the callee, which leads
5345   // to incorrect code.
5346 
5347   // Start by loading the function address from the descriptor.
5348   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5349   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5350                       ? (MachineMemOperand::MODereferenceable |
5351                          MachineMemOperand::MOInvariant)
5352                       : MachineMemOperand::MONone;
5353 
5354   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5355 
5356   // Registers used in building the DAG.
5357   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5358   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5359 
5360   // Offsets of descriptor members.
5361   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5362   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5363 
5364   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5365   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5366 
5367   // One load for the functions entry point address.
5368   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5369                                     Alignment, MMOFlags);
5370 
5371   // One for loading the TOC anchor for the module that contains the called
5372   // function.
5373   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5374   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5375   SDValue TOCPtr =
5376       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5377                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5378 
5379   // One for loading the environment pointer.
5380   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5381   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5382   SDValue LoadEnvPtr =
5383       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5384                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5385 
5386 
5387   // Then copy the newly loaded TOC anchor to the TOC pointer.
5388   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5389   Chain = TOCVal.getValue(0);
5390   Glue = TOCVal.getValue(1);
5391 
5392   // If the function call has an explicit 'nest' parameter, it takes the
5393   // place of the environment pointer.
5394   assert((!hasNest || !Subtarget.isAIXABI()) &&
5395          "Nest parameter is not supported on AIX.");
5396   if (!hasNest) {
5397     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5398     Chain = EnvVal.getValue(0);
5399     Glue = EnvVal.getValue(1);
5400   }
5401 
5402   // The rest of the indirect call sequence is the same as the non-descriptor
5403   // DAG.
5404   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5405 }
5406 
5407 static void
5408 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5409                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5410                   SelectionDAG &DAG,
5411                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5412                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5413                   const PPCSubtarget &Subtarget) {
5414   const bool IsPPC64 = Subtarget.isPPC64();
5415   // MVT for a general purpose register.
5416   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5417 
5418   // First operand is always the chain.
5419   Ops.push_back(Chain);
5420 
5421   // If it's a direct call pass the callee as the second operand.
5422   if (!CFlags.IsIndirect)
5423     Ops.push_back(Callee);
5424   else {
5425     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5426 
5427     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5428     // on the stack (this would have been done in `LowerCall_64SVR4` or
5429     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5430     // represents both the indirect branch and a load that restores the TOC
5431     // pointer from the linkage area. The operand for the TOC restore is an add
5432     // of the TOC save offset to the stack pointer. This must be the second
5433     // operand: after the chain input but before any other variadic arguments.
5434     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5435     // saved or used.
5436     if (isTOCSaveRestoreRequired(Subtarget)) {
5437       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5438 
5439       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5440       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5441       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5442       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5443       Ops.push_back(AddTOC);
5444     }
5445 
5446     // Add the register used for the environment pointer.
5447     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5448       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5449                                     RegVT));
5450 
5451 
5452     // Add CTR register as callee so a bctr can be emitted later.
5453     if (CFlags.IsTailCall)
5454       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5455   }
5456 
5457   // If this is a tail call add stack pointer delta.
5458   if (CFlags.IsTailCall)
5459     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5460 
5461   // Add argument registers to the end of the list so that they are known live
5462   // into the call.
5463   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5464     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5465                                   RegsToPass[i].second.getValueType()));
5466 
5467   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5468   // no way to mark dependencies as implicit here.
5469   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5470   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5471        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5472     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5473 
5474   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5475   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5476     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5477 
5478   // Add a register mask operand representing the call-preserved registers.
5479   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5480   const uint32_t *Mask =
5481       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5482   assert(Mask && "Missing call preserved mask for calling convention");
5483   Ops.push_back(DAG.getRegisterMask(Mask));
5484 
5485   // If the glue is valid, it is the last operand.
5486   if (Glue.getNode())
5487     Ops.push_back(Glue);
5488 }
5489 
5490 SDValue PPCTargetLowering::FinishCall(
5491     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5492     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5493     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5494     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5495     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5496 
5497   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5498       Subtarget.isAIXABI())
5499     setUsesTOCBasePtr(DAG);
5500 
5501   unsigned CallOpc =
5502       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5503                     Subtarget, DAG.getTarget());
5504 
5505   if (!CFlags.IsIndirect)
5506     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5507   else if (Subtarget.usesFunctionDescriptors())
5508     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5509                                   dl, CFlags.HasNest, Subtarget);
5510   else
5511     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5512 
5513   // Build the operand list for the call instruction.
5514   SmallVector<SDValue, 8> Ops;
5515   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5516                     SPDiff, Subtarget);
5517 
5518   // Emit tail call.
5519   if (CFlags.IsTailCall) {
5520     // Indirect tail call when using PC Relative calls do not have the same
5521     // constraints.
5522     assert(((Callee.getOpcode() == ISD::Register &&
5523              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5524             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5525             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5526             isa<ConstantSDNode>(Callee) ||
5527             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5528            "Expecting a global address, external symbol, absolute value, "
5529            "register or an indirect tail call when PC Relative calls are "
5530            "used.");
5531     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5532     assert(CallOpc == PPCISD::TC_RETURN &&
5533            "Unexpected call opcode for a tail call.");
5534     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5535     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5536   }
5537 
5538   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5539   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5540   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5541   Glue = Chain.getValue(1);
5542 
5543   // When performing tail call optimization the callee pops its arguments off
5544   // the stack. Account for this here so these bytes can be pushed back on in
5545   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5546   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5547                          getTargetMachine().Options.GuaranteedTailCallOpt)
5548                             ? NumBytes
5549                             : 0;
5550 
5551   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5552                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5553                              Glue, dl);
5554   Glue = Chain.getValue(1);
5555 
5556   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5557                          DAG, InVals);
5558 }
5559 
5560 SDValue
5561 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5562                              SmallVectorImpl<SDValue> &InVals) const {
5563   SelectionDAG &DAG                     = CLI.DAG;
5564   SDLoc &dl                             = CLI.DL;
5565   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5566   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5567   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5568   SDValue Chain                         = CLI.Chain;
5569   SDValue Callee                        = CLI.Callee;
5570   bool &isTailCall                      = CLI.IsTailCall;
5571   CallingConv::ID CallConv              = CLI.CallConv;
5572   bool isVarArg                         = CLI.IsVarArg;
5573   bool isPatchPoint                     = CLI.IsPatchPoint;
5574   const CallBase *CB                    = CLI.CB;
5575 
5576   if (isTailCall) {
5577     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5578       isTailCall = false;
5579     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5580       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5581           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5582     else
5583       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5584                                                      Ins, DAG);
5585     if (isTailCall) {
5586       ++NumTailCalls;
5587       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5588         ++NumSiblingCalls;
5589 
5590       // PC Relative calls no longer guarantee that the callee is a Global
5591       // Address Node. The callee could be an indirect tail call in which
5592       // case the SDValue for the callee could be a load (to load the address
5593       // of a function pointer) or it may be a register copy (to move the
5594       // address of the callee from a function parameter into a virtual
5595       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5596       assert((Subtarget.isUsingPCRelativeCalls() ||
5597               isa<GlobalAddressSDNode>(Callee)) &&
5598              "Callee should be an llvm::Function object.");
5599 
5600       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5601                         << "\nTCO callee: ");
5602       LLVM_DEBUG(Callee.dump());
5603     }
5604   }
5605 
5606   if (!isTailCall && CB && CB->isMustTailCall())
5607     report_fatal_error("failed to perform tail call elimination on a call "
5608                        "site marked musttail");
5609 
5610   // When long calls (i.e. indirect calls) are always used, calls are always
5611   // made via function pointer. If we have a function name, first translate it
5612   // into a pointer.
5613   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5614       !isTailCall)
5615     Callee = LowerGlobalAddress(Callee, DAG);
5616 
5617   CallFlags CFlags(
5618       CallConv, isTailCall, isVarArg, isPatchPoint,
5619       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5620       // hasNest
5621       Subtarget.is64BitELFABI() &&
5622           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5623       CLI.NoMerge);
5624 
5625   if (Subtarget.isAIXABI())
5626     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5627                          InVals, CB);
5628 
5629   assert(Subtarget.isSVR4ABI());
5630   if (Subtarget.isPPC64())
5631     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5632                             InVals, CB);
5633   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5634                           InVals, CB);
5635 }
5636 
5637 SDValue PPCTargetLowering::LowerCall_32SVR4(
5638     SDValue Chain, SDValue Callee, CallFlags CFlags,
5639     const SmallVectorImpl<ISD::OutputArg> &Outs,
5640     const SmallVectorImpl<SDValue> &OutVals,
5641     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5642     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5643     const CallBase *CB) const {
5644   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5645   // of the 32-bit SVR4 ABI stack frame layout.
5646 
5647   const CallingConv::ID CallConv = CFlags.CallConv;
5648   const bool IsVarArg = CFlags.IsVarArg;
5649   const bool IsTailCall = CFlags.IsTailCall;
5650 
5651   assert((CallConv == CallingConv::C ||
5652           CallConv == CallingConv::Cold ||
5653           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5654 
5655   const Align PtrAlign(4);
5656 
5657   MachineFunction &MF = DAG.getMachineFunction();
5658 
5659   // Mark this function as potentially containing a function that contains a
5660   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5661   // and restoring the callers stack pointer in this functions epilog. This is
5662   // done because by tail calling the called function might overwrite the value
5663   // in this function's (MF) stack pointer stack slot 0(SP).
5664   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5665       CallConv == CallingConv::Fast)
5666     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5667 
5668   // Count how many bytes are to be pushed on the stack, including the linkage
5669   // area, parameter list area and the part of the local variable space which
5670   // contains copies of aggregates which are passed by value.
5671 
5672   // Assign locations to all of the outgoing arguments.
5673   SmallVector<CCValAssign, 16> ArgLocs;
5674   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5675 
5676   // Reserve space for the linkage area on the stack.
5677   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5678                        PtrAlign);
5679   if (useSoftFloat())
5680     CCInfo.PreAnalyzeCallOperands(Outs);
5681 
5682   if (IsVarArg) {
5683     // Handle fixed and variable vector arguments differently.
5684     // Fixed vector arguments go into registers as long as registers are
5685     // available. Variable vector arguments always go into memory.
5686     unsigned NumArgs = Outs.size();
5687 
5688     for (unsigned i = 0; i != NumArgs; ++i) {
5689       MVT ArgVT = Outs[i].VT;
5690       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5691       bool Result;
5692 
5693       if (Outs[i].IsFixed) {
5694         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5695                                CCInfo);
5696       } else {
5697         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5698                                       ArgFlags, CCInfo);
5699       }
5700 
5701       if (Result) {
5702 #ifndef NDEBUG
5703         errs() << "Call operand #" << i << " has unhandled type "
5704              << EVT(ArgVT).getEVTString() << "\n";
5705 #endif
5706         llvm_unreachable(nullptr);
5707       }
5708     }
5709   } else {
5710     // All arguments are treated the same.
5711     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5712   }
5713   CCInfo.clearWasPPCF128();
5714 
5715   // Assign locations to all of the outgoing aggregate by value arguments.
5716   SmallVector<CCValAssign, 16> ByValArgLocs;
5717   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5718 
5719   // Reserve stack space for the allocations in CCInfo.
5720   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5721 
5722   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5723 
5724   // Size of the linkage area, parameter list area and the part of the local
5725   // space variable where copies of aggregates which are passed by value are
5726   // stored.
5727   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5728 
5729   // Calculate by how many bytes the stack has to be adjusted in case of tail
5730   // call optimization.
5731   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5732 
5733   // Adjust the stack pointer for the new arguments...
5734   // These operations are automatically eliminated by the prolog/epilog pass
5735   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5736   SDValue CallSeqStart = Chain;
5737 
5738   // Load the return address and frame pointer so it can be moved somewhere else
5739   // later.
5740   SDValue LROp, FPOp;
5741   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5742 
5743   // Set up a copy of the stack pointer for use loading and storing any
5744   // arguments that may not fit in the registers available for argument
5745   // passing.
5746   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5747 
5748   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5749   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5750   SmallVector<SDValue, 8> MemOpChains;
5751 
5752   bool seenFloatArg = false;
5753   // Walk the register/memloc assignments, inserting copies/loads.
5754   // i - Tracks the index into the list of registers allocated for the call
5755   // RealArgIdx - Tracks the index into the list of actual function arguments
5756   // j - Tracks the index into the list of byval arguments
5757   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5758        i != e;
5759        ++i, ++RealArgIdx) {
5760     CCValAssign &VA = ArgLocs[i];
5761     SDValue Arg = OutVals[RealArgIdx];
5762     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5763 
5764     if (Flags.isByVal()) {
5765       // Argument is an aggregate which is passed by value, thus we need to
5766       // create a copy of it in the local variable space of the current stack
5767       // frame (which is the stack frame of the caller) and pass the address of
5768       // this copy to the callee.
5769       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5770       CCValAssign &ByValVA = ByValArgLocs[j++];
5771       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5772 
5773       // Memory reserved in the local variable space of the callers stack frame.
5774       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5775 
5776       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5777       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5778                            StackPtr, PtrOff);
5779 
5780       // Create a copy of the argument in the local area of the current
5781       // stack frame.
5782       SDValue MemcpyCall =
5783         CreateCopyOfByValArgument(Arg, PtrOff,
5784                                   CallSeqStart.getNode()->getOperand(0),
5785                                   Flags, DAG, dl);
5786 
5787       // This must go outside the CALLSEQ_START..END.
5788       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5789                                                      SDLoc(MemcpyCall));
5790       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5791                              NewCallSeqStart.getNode());
5792       Chain = CallSeqStart = NewCallSeqStart;
5793 
5794       // Pass the address of the aggregate copy on the stack either in a
5795       // physical register or in the parameter list area of the current stack
5796       // frame to the callee.
5797       Arg = PtrOff;
5798     }
5799 
5800     // When useCRBits() is true, there can be i1 arguments.
5801     // It is because getRegisterType(MVT::i1) => MVT::i1,
5802     // and for other integer types getRegisterType() => MVT::i32.
5803     // Extend i1 and ensure callee will get i32.
5804     if (Arg.getValueType() == MVT::i1)
5805       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5806                         dl, MVT::i32, Arg);
5807 
5808     if (VA.isRegLoc()) {
5809       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5810       // Put argument in a physical register.
5811       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5812         bool IsLE = Subtarget.isLittleEndian();
5813         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5814                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5815         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5816         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5817                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5818         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5819                              SVal.getValue(0)));
5820       } else
5821         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5822     } else {
5823       // Put argument in the parameter list area of the current stack frame.
5824       assert(VA.isMemLoc());
5825       unsigned LocMemOffset = VA.getLocMemOffset();
5826 
5827       if (!IsTailCall) {
5828         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5829         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5830                              StackPtr, PtrOff);
5831 
5832         MemOpChains.push_back(
5833             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5834       } else {
5835         // Calculate and remember argument location.
5836         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5837                                  TailCallArguments);
5838       }
5839     }
5840   }
5841 
5842   if (!MemOpChains.empty())
5843     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5844 
5845   // Build a sequence of copy-to-reg nodes chained together with token chain
5846   // and flag operands which copy the outgoing args into the appropriate regs.
5847   SDValue InFlag;
5848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5849     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5850                              RegsToPass[i].second, InFlag);
5851     InFlag = Chain.getValue(1);
5852   }
5853 
5854   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5855   // registers.
5856   if (IsVarArg) {
5857     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5858     SDValue Ops[] = { Chain, InFlag };
5859 
5860     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5861                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5862 
5863     InFlag = Chain.getValue(1);
5864   }
5865 
5866   if (IsTailCall)
5867     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5868                     TailCallArguments);
5869 
5870   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5871                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5872 }
5873 
5874 // Copy an argument into memory, being careful to do this outside the
5875 // call sequence for the call to which the argument belongs.
5876 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5877     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5878     SelectionDAG &DAG, const SDLoc &dl) const {
5879   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5880                         CallSeqStart.getNode()->getOperand(0),
5881                         Flags, DAG, dl);
5882   // The MEMCPY must go outside the CALLSEQ_START..END.
5883   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5884   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5885                                                  SDLoc(MemcpyCall));
5886   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5887                          NewCallSeqStart.getNode());
5888   return NewCallSeqStart;
5889 }
5890 
5891 SDValue PPCTargetLowering::LowerCall_64SVR4(
5892     SDValue Chain, SDValue Callee, CallFlags CFlags,
5893     const SmallVectorImpl<ISD::OutputArg> &Outs,
5894     const SmallVectorImpl<SDValue> &OutVals,
5895     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5896     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5897     const CallBase *CB) const {
5898   bool isELFv2ABI = Subtarget.isELFv2ABI();
5899   bool isLittleEndian = Subtarget.isLittleEndian();
5900   unsigned NumOps = Outs.size();
5901   bool IsSibCall = false;
5902   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5903 
5904   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5905   unsigned PtrByteSize = 8;
5906 
5907   MachineFunction &MF = DAG.getMachineFunction();
5908 
5909   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5910     IsSibCall = true;
5911 
5912   // Mark this function as potentially containing a function that contains a
5913   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5914   // and restoring the callers stack pointer in this functions epilog. This is
5915   // done because by tail calling the called function might overwrite the value
5916   // in this function's (MF) stack pointer stack slot 0(SP).
5917   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5918     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5919 
5920   assert(!(IsFastCall && CFlags.IsVarArg) &&
5921          "fastcc not supported on varargs functions");
5922 
5923   // Count how many bytes are to be pushed on the stack, including the linkage
5924   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5925   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5926   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5927   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5928   unsigned NumBytes = LinkageSize;
5929   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5930 
5931   static const MCPhysReg GPR[] = {
5932     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5933     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5934   };
5935   static const MCPhysReg VR[] = {
5936     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5937     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5938   };
5939 
5940   const unsigned NumGPRs = array_lengthof(GPR);
5941   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5942   const unsigned NumVRs  = array_lengthof(VR);
5943 
5944   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5945   // can be passed to the callee in registers.
5946   // For the fast calling convention, there is another check below.
5947   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5948   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5949   if (!HasParameterArea) {
5950     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5951     unsigned AvailableFPRs = NumFPRs;
5952     unsigned AvailableVRs = NumVRs;
5953     unsigned NumBytesTmp = NumBytes;
5954     for (unsigned i = 0; i != NumOps; ++i) {
5955       if (Outs[i].Flags.isNest()) continue;
5956       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5957                                  PtrByteSize, LinkageSize, ParamAreaSize,
5958                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5959         HasParameterArea = true;
5960     }
5961   }
5962 
5963   // When using the fast calling convention, we don't provide backing for
5964   // arguments that will be in registers.
5965   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5966 
5967   // Avoid allocating parameter area for fastcc functions if all the arguments
5968   // can be passed in the registers.
5969   if (IsFastCall)
5970     HasParameterArea = false;
5971 
5972   // Add up all the space actually used.
5973   for (unsigned i = 0; i != NumOps; ++i) {
5974     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5975     EVT ArgVT = Outs[i].VT;
5976     EVT OrigVT = Outs[i].ArgVT;
5977 
5978     if (Flags.isNest())
5979       continue;
5980 
5981     if (IsFastCall) {
5982       if (Flags.isByVal()) {
5983         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5984         if (NumGPRsUsed > NumGPRs)
5985           HasParameterArea = true;
5986       } else {
5987         switch (ArgVT.getSimpleVT().SimpleTy) {
5988         default: llvm_unreachable("Unexpected ValueType for argument!");
5989         case MVT::i1:
5990         case MVT::i32:
5991         case MVT::i64:
5992           if (++NumGPRsUsed <= NumGPRs)
5993             continue;
5994           break;
5995         case MVT::v4i32:
5996         case MVT::v8i16:
5997         case MVT::v16i8:
5998         case MVT::v2f64:
5999         case MVT::v2i64:
6000         case MVT::v1i128:
6001         case MVT::f128:
6002           if (++NumVRsUsed <= NumVRs)
6003             continue;
6004           break;
6005         case MVT::v4f32:
6006           if (++NumVRsUsed <= NumVRs)
6007             continue;
6008           break;
6009         case MVT::f32:
6010         case MVT::f64:
6011           if (++NumFPRsUsed <= NumFPRs)
6012             continue;
6013           break;
6014         }
6015         HasParameterArea = true;
6016       }
6017     }
6018 
6019     /* Respect alignment of argument on the stack.  */
6020     auto Alignement =
6021         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6022     NumBytes = alignTo(NumBytes, Alignement);
6023 
6024     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6025     if (Flags.isInConsecutiveRegsLast())
6026       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6027   }
6028 
6029   unsigned NumBytesActuallyUsed = NumBytes;
6030 
6031   // In the old ELFv1 ABI,
6032   // the prolog code of the callee may store up to 8 GPR argument registers to
6033   // the stack, allowing va_start to index over them in memory if its varargs.
6034   // Because we cannot tell if this is needed on the caller side, we have to
6035   // conservatively assume that it is needed.  As such, make sure we have at
6036   // least enough stack space for the caller to store the 8 GPRs.
6037   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6038   // really requires memory operands, e.g. a vararg function.
6039   if (HasParameterArea)
6040     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6041   else
6042     NumBytes = LinkageSize;
6043 
6044   // Tail call needs the stack to be aligned.
6045   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6046     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6047 
6048   int SPDiff = 0;
6049 
6050   // Calculate by how many bytes the stack has to be adjusted in case of tail
6051   // call optimization.
6052   if (!IsSibCall)
6053     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6054 
6055   // To protect arguments on the stack from being clobbered in a tail call,
6056   // force all the loads to happen before doing any other lowering.
6057   if (CFlags.IsTailCall)
6058     Chain = DAG.getStackArgumentTokenFactor(Chain);
6059 
6060   // Adjust the stack pointer for the new arguments...
6061   // These operations are automatically eliminated by the prolog/epilog pass
6062   if (!IsSibCall)
6063     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6064   SDValue CallSeqStart = Chain;
6065 
6066   // Load the return address and frame pointer so it can be move somewhere else
6067   // later.
6068   SDValue LROp, FPOp;
6069   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6070 
6071   // Set up a copy of the stack pointer for use loading and storing any
6072   // arguments that may not fit in the registers available for argument
6073   // passing.
6074   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6075 
6076   // Figure out which arguments are going to go in registers, and which in
6077   // memory.  Also, if this is a vararg function, floating point operations
6078   // must be stored to our stack, and loaded into integer regs as well, if
6079   // any integer regs are available for argument passing.
6080   unsigned ArgOffset = LinkageSize;
6081 
6082   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6083   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6084 
6085   SmallVector<SDValue, 8> MemOpChains;
6086   for (unsigned i = 0; i != NumOps; ++i) {
6087     SDValue Arg = OutVals[i];
6088     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6089     EVT ArgVT = Outs[i].VT;
6090     EVT OrigVT = Outs[i].ArgVT;
6091 
6092     // PtrOff will be used to store the current argument to the stack if a
6093     // register cannot be found for it.
6094     SDValue PtrOff;
6095 
6096     // We re-align the argument offset for each argument, except when using the
6097     // fast calling convention, when we need to make sure we do that only when
6098     // we'll actually use a stack slot.
6099     auto ComputePtrOff = [&]() {
6100       /* Respect alignment of argument on the stack.  */
6101       auto Alignment =
6102           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6103       ArgOffset = alignTo(ArgOffset, Alignment);
6104 
6105       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6106 
6107       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6108     };
6109 
6110     if (!IsFastCall) {
6111       ComputePtrOff();
6112 
6113       /* Compute GPR index associated with argument offset.  */
6114       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6115       GPR_idx = std::min(GPR_idx, NumGPRs);
6116     }
6117 
6118     // Promote integers to 64-bit values.
6119     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6120       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6121       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6122       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6123     }
6124 
6125     // FIXME memcpy is used way more than necessary.  Correctness first.
6126     // Note: "by value" is code for passing a structure by value, not
6127     // basic types.
6128     if (Flags.isByVal()) {
6129       // Note: Size includes alignment padding, so
6130       //   struct x { short a; char b; }
6131       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6132       // These are the proper values we need for right-justifying the
6133       // aggregate in a parameter register.
6134       unsigned Size = Flags.getByValSize();
6135 
6136       // An empty aggregate parameter takes up no storage and no
6137       // registers.
6138       if (Size == 0)
6139         continue;
6140 
6141       if (IsFastCall)
6142         ComputePtrOff();
6143 
6144       // All aggregates smaller than 8 bytes must be passed right-justified.
6145       if (Size==1 || Size==2 || Size==4) {
6146         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6147         if (GPR_idx != NumGPRs) {
6148           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6149                                         MachinePointerInfo(), VT);
6150           MemOpChains.push_back(Load.getValue(1));
6151           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6152 
6153           ArgOffset += PtrByteSize;
6154           continue;
6155         }
6156       }
6157 
6158       if (GPR_idx == NumGPRs && Size < 8) {
6159         SDValue AddPtr = PtrOff;
6160         if (!isLittleEndian) {
6161           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6162                                           PtrOff.getValueType());
6163           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6164         }
6165         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6166                                                           CallSeqStart,
6167                                                           Flags, DAG, dl);
6168         ArgOffset += PtrByteSize;
6169         continue;
6170       }
6171       // Copy entire object into memory.  There are cases where gcc-generated
6172       // code assumes it is there, even if it could be put entirely into
6173       // registers.  (This is not what the doc says.)
6174 
6175       // FIXME: The above statement is likely due to a misunderstanding of the
6176       // documents.  All arguments must be copied into the parameter area BY
6177       // THE CALLEE in the event that the callee takes the address of any
6178       // formal argument.  That has not yet been implemented.  However, it is
6179       // reasonable to use the stack area as a staging area for the register
6180       // load.
6181 
6182       // Skip this for small aggregates, as we will use the same slot for a
6183       // right-justified copy, below.
6184       if (Size >= 8)
6185         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6186                                                           CallSeqStart,
6187                                                           Flags, DAG, dl);
6188 
6189       // When a register is available, pass a small aggregate right-justified.
6190       if (Size < 8 && GPR_idx != NumGPRs) {
6191         // The easiest way to get this right-justified in a register
6192         // is to copy the structure into the rightmost portion of a
6193         // local variable slot, then load the whole slot into the
6194         // register.
6195         // FIXME: The memcpy seems to produce pretty awful code for
6196         // small aggregates, particularly for packed ones.
6197         // FIXME: It would be preferable to use the slot in the
6198         // parameter save area instead of a new local variable.
6199         SDValue AddPtr = PtrOff;
6200         if (!isLittleEndian) {
6201           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6202           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6203         }
6204         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6205                                                           CallSeqStart,
6206                                                           Flags, DAG, dl);
6207 
6208         // Load the slot into the register.
6209         SDValue Load =
6210             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6211         MemOpChains.push_back(Load.getValue(1));
6212         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6213 
6214         // Done with this argument.
6215         ArgOffset += PtrByteSize;
6216         continue;
6217       }
6218 
6219       // For aggregates larger than PtrByteSize, copy the pieces of the
6220       // object that fit into registers from the parameter save area.
6221       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6222         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6223         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6224         if (GPR_idx != NumGPRs) {
6225           SDValue Load =
6226               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6227           MemOpChains.push_back(Load.getValue(1));
6228           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6229           ArgOffset += PtrByteSize;
6230         } else {
6231           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6232           break;
6233         }
6234       }
6235       continue;
6236     }
6237 
6238     switch (Arg.getSimpleValueType().SimpleTy) {
6239     default: llvm_unreachable("Unexpected ValueType for argument!");
6240     case MVT::i1:
6241     case MVT::i32:
6242     case MVT::i64:
6243       if (Flags.isNest()) {
6244         // The 'nest' parameter, if any, is passed in R11.
6245         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6246         break;
6247       }
6248 
6249       // These can be scalar arguments or elements of an integer array type
6250       // passed directly.  Clang may use those instead of "byval" aggregate
6251       // types to avoid forcing arguments to memory unnecessarily.
6252       if (GPR_idx != NumGPRs) {
6253         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6254       } else {
6255         if (IsFastCall)
6256           ComputePtrOff();
6257 
6258         assert(HasParameterArea &&
6259                "Parameter area must exist to pass an argument in memory.");
6260         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6261                          true, CFlags.IsTailCall, false, MemOpChains,
6262                          TailCallArguments, dl);
6263         if (IsFastCall)
6264           ArgOffset += PtrByteSize;
6265       }
6266       if (!IsFastCall)
6267         ArgOffset += PtrByteSize;
6268       break;
6269     case MVT::f32:
6270     case MVT::f64: {
6271       // These can be scalar arguments or elements of a float array type
6272       // passed directly.  The latter are used to implement ELFv2 homogenous
6273       // float aggregates.
6274 
6275       // Named arguments go into FPRs first, and once they overflow, the
6276       // remaining arguments go into GPRs and then the parameter save area.
6277       // Unnamed arguments for vararg functions always go to GPRs and
6278       // then the parameter save area.  For now, put all arguments to vararg
6279       // routines always in both locations (FPR *and* GPR or stack slot).
6280       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6281       bool NeededLoad = false;
6282 
6283       // First load the argument into the next available FPR.
6284       if (FPR_idx != NumFPRs)
6285         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6286 
6287       // Next, load the argument into GPR or stack slot if needed.
6288       if (!NeedGPROrStack)
6289         ;
6290       else if (GPR_idx != NumGPRs && !IsFastCall) {
6291         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6292         // once we support fp <-> gpr moves.
6293 
6294         // In the non-vararg case, this can only ever happen in the
6295         // presence of f32 array types, since otherwise we never run
6296         // out of FPRs before running out of GPRs.
6297         SDValue ArgVal;
6298 
6299         // Double values are always passed in a single GPR.
6300         if (Arg.getValueType() != MVT::f32) {
6301           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6302 
6303         // Non-array float values are extended and passed in a GPR.
6304         } else if (!Flags.isInConsecutiveRegs()) {
6305           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6306           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6307 
6308         // If we have an array of floats, we collect every odd element
6309         // together with its predecessor into one GPR.
6310         } else if (ArgOffset % PtrByteSize != 0) {
6311           SDValue Lo, Hi;
6312           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6313           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6314           if (!isLittleEndian)
6315             std::swap(Lo, Hi);
6316           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6317 
6318         // The final element, if even, goes into the first half of a GPR.
6319         } else if (Flags.isInConsecutiveRegsLast()) {
6320           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6321           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6322           if (!isLittleEndian)
6323             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6324                                  DAG.getConstant(32, dl, MVT::i32));
6325 
6326         // Non-final even elements are skipped; they will be handled
6327         // together the with subsequent argument on the next go-around.
6328         } else
6329           ArgVal = SDValue();
6330 
6331         if (ArgVal.getNode())
6332           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6333       } else {
6334         if (IsFastCall)
6335           ComputePtrOff();
6336 
6337         // Single-precision floating-point values are mapped to the
6338         // second (rightmost) word of the stack doubleword.
6339         if (Arg.getValueType() == MVT::f32 &&
6340             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6341           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6342           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6343         }
6344 
6345         assert(HasParameterArea &&
6346                "Parameter area must exist to pass an argument in memory.");
6347         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6348                          true, CFlags.IsTailCall, false, MemOpChains,
6349                          TailCallArguments, dl);
6350 
6351         NeededLoad = true;
6352       }
6353       // When passing an array of floats, the array occupies consecutive
6354       // space in the argument area; only round up to the next doubleword
6355       // at the end of the array.  Otherwise, each float takes 8 bytes.
6356       if (!IsFastCall || NeededLoad) {
6357         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6358                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6359         if (Flags.isInConsecutiveRegsLast())
6360           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6361       }
6362       break;
6363     }
6364     case MVT::v4f32:
6365     case MVT::v4i32:
6366     case MVT::v8i16:
6367     case MVT::v16i8:
6368     case MVT::v2f64:
6369     case MVT::v2i64:
6370     case MVT::v1i128:
6371     case MVT::f128:
6372       // These can be scalar arguments or elements of a vector array type
6373       // passed directly.  The latter are used to implement ELFv2 homogenous
6374       // vector aggregates.
6375 
6376       // For a varargs call, named arguments go into VRs or on the stack as
6377       // usual; unnamed arguments always go to the stack or the corresponding
6378       // GPRs when within range.  For now, we always put the value in both
6379       // locations (or even all three).
6380       if (CFlags.IsVarArg) {
6381         assert(HasParameterArea &&
6382                "Parameter area must exist if we have a varargs call.");
6383         // We could elide this store in the case where the object fits
6384         // entirely in R registers.  Maybe later.
6385         SDValue Store =
6386             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6387         MemOpChains.push_back(Store);
6388         if (VR_idx != NumVRs) {
6389           SDValue Load =
6390               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6391           MemOpChains.push_back(Load.getValue(1));
6392           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6393         }
6394         ArgOffset += 16;
6395         for (unsigned i=0; i<16; i+=PtrByteSize) {
6396           if (GPR_idx == NumGPRs)
6397             break;
6398           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6399                                    DAG.getConstant(i, dl, PtrVT));
6400           SDValue Load =
6401               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6402           MemOpChains.push_back(Load.getValue(1));
6403           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6404         }
6405         break;
6406       }
6407 
6408       // Non-varargs Altivec params go into VRs or on the stack.
6409       if (VR_idx != NumVRs) {
6410         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6411       } else {
6412         if (IsFastCall)
6413           ComputePtrOff();
6414 
6415         assert(HasParameterArea &&
6416                "Parameter area must exist to pass an argument in memory.");
6417         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6418                          true, CFlags.IsTailCall, true, MemOpChains,
6419                          TailCallArguments, dl);
6420         if (IsFastCall)
6421           ArgOffset += 16;
6422       }
6423 
6424       if (!IsFastCall)
6425         ArgOffset += 16;
6426       break;
6427     }
6428   }
6429 
6430   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6431          "mismatch in size of parameter area");
6432   (void)NumBytesActuallyUsed;
6433 
6434   if (!MemOpChains.empty())
6435     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6436 
6437   // Check if this is an indirect call (MTCTR/BCTRL).
6438   // See prepareDescriptorIndirectCall and buildCallOperands for more
6439   // information about calls through function pointers in the 64-bit SVR4 ABI.
6440   if (CFlags.IsIndirect) {
6441     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6442     // caller in the TOC save area.
6443     if (isTOCSaveRestoreRequired(Subtarget)) {
6444       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6445       // Load r2 into a virtual register and store it to the TOC save area.
6446       setUsesTOCBasePtr(DAG);
6447       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6448       // TOC save area offset.
6449       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6450       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6451       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6452       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6453                            MachinePointerInfo::getStack(
6454                                DAG.getMachineFunction(), TOCSaveOffset));
6455     }
6456     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6457     // This does not mean the MTCTR instruction must use R12; it's easier
6458     // to model this as an extra parameter, so do that.
6459     if (isELFv2ABI && !CFlags.IsPatchPoint)
6460       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6461   }
6462 
6463   // Build a sequence of copy-to-reg nodes chained together with token chain
6464   // and flag operands which copy the outgoing args into the appropriate regs.
6465   SDValue InFlag;
6466   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6467     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6468                              RegsToPass[i].second, InFlag);
6469     InFlag = Chain.getValue(1);
6470   }
6471 
6472   if (CFlags.IsTailCall && !IsSibCall)
6473     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6474                     TailCallArguments);
6475 
6476   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6477                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6478 }
6479 
6480 // Returns true when the shadow of a general purpose argument register
6481 // in the parameter save area is aligned to at least 'RequiredAlign'.
6482 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6483   assert(RequiredAlign.value() <= 16 &&
6484          "Required alignment greater than stack alignment.");
6485   switch (Reg) {
6486   default:
6487     report_fatal_error("called on invalid register.");
6488   case PPC::R5:
6489   case PPC::R9:
6490   case PPC::X3:
6491   case PPC::X5:
6492   case PPC::X7:
6493   case PPC::X9:
6494     // These registers are 16 byte aligned which is the most strict aligment
6495     // we can support.
6496     return true;
6497   case PPC::R3:
6498   case PPC::R7:
6499   case PPC::X4:
6500   case PPC::X6:
6501   case PPC::X8:
6502   case PPC::X10:
6503     // The shadow of these registers in the PSA is 8 byte aligned.
6504     return RequiredAlign <= 8;
6505   case PPC::R4:
6506   case PPC::R6:
6507   case PPC::R8:
6508   case PPC::R10:
6509     return RequiredAlign <= 4;
6510   }
6511 }
6512 
6513 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6514                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6515                    CCState &S) {
6516   AIXCCState &State = static_cast<AIXCCState &>(S);
6517   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6518       State.getMachineFunction().getSubtarget());
6519   const bool IsPPC64 = Subtarget.isPPC64();
6520   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6521   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6522 
6523   if (ValVT == MVT::f128)
6524     report_fatal_error("f128 is unimplemented on AIX.");
6525 
6526   if (ArgFlags.isNest())
6527     report_fatal_error("Nest arguments are unimplemented.");
6528 
6529   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6530                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6531                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6532   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6533                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6534                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6535 
6536   static const MCPhysReg VR[] = {// Vector registers.
6537                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6538                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6539                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6540 
6541   if (ArgFlags.isByVal()) {
6542     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6543       report_fatal_error("Pass-by-value arguments with alignment greater than "
6544                          "register width are not supported.");
6545 
6546     const unsigned ByValSize = ArgFlags.getByValSize();
6547 
6548     // An empty aggregate parameter takes up no storage and no registers,
6549     // but needs a MemLoc for a stack slot for the formal arguments side.
6550     if (ByValSize == 0) {
6551       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6552                                        State.getNextStackOffset(), RegVT,
6553                                        LocInfo));
6554       return false;
6555     }
6556 
6557     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6558     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6559     for (const unsigned E = Offset + StackSize; Offset < E;
6560          Offset += PtrAlign.value()) {
6561       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6562         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6563       else {
6564         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6565                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6566                                          LocInfo));
6567         break;
6568       }
6569     }
6570     return false;
6571   }
6572 
6573   // Arguments always reserve parameter save area.
6574   switch (ValVT.SimpleTy) {
6575   default:
6576     report_fatal_error("Unhandled value type for argument.");
6577   case MVT::i64:
6578     // i64 arguments should have been split to i32 for PPC32.
6579     assert(IsPPC64 && "PPC32 should have split i64 values.");
6580     LLVM_FALLTHROUGH;
6581   case MVT::i1:
6582   case MVT::i32: {
6583     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6584     // AIX integer arguments are always passed in register width.
6585     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6586       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6587                                   : CCValAssign::LocInfo::ZExt;
6588     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6589       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6590     else
6591       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6592 
6593     return false;
6594   }
6595   case MVT::f32:
6596   case MVT::f64: {
6597     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6598     const unsigned StoreSize = LocVT.getStoreSize();
6599     // Floats are always 4-byte aligned in the PSA on AIX.
6600     // This includes f64 in 64-bit mode for ABI compatibility.
6601     const unsigned Offset =
6602         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6603     unsigned FReg = State.AllocateReg(FPR);
6604     if (FReg)
6605       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6606 
6607     // Reserve and initialize GPRs or initialize the PSA as required.
6608     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6609       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6610         assert(FReg && "An FPR should be available when a GPR is reserved.");
6611         if (State.isVarArg()) {
6612           // Successfully reserved GPRs are only initialized for vararg calls.
6613           // Custom handling is required for:
6614           //   f64 in PPC32 needs to be split into 2 GPRs.
6615           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6616           State.addLoc(
6617               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6618         }
6619       } else {
6620         // If there are insufficient GPRs, the PSA needs to be initialized.
6621         // Initialization occurs even if an FPR was initialized for
6622         // compatibility with the AIX XL compiler. The full memory for the
6623         // argument will be initialized even if a prior word is saved in GPR.
6624         // A custom memLoc is used when the argument also passes in FPR so
6625         // that the callee handling can skip over it easily.
6626         State.addLoc(
6627             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6628                                              LocInfo)
6629                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6630         break;
6631       }
6632     }
6633 
6634     return false;
6635   }
6636   case MVT::v4f32:
6637   case MVT::v4i32:
6638   case MVT::v8i16:
6639   case MVT::v16i8:
6640   case MVT::v2i64:
6641   case MVT::v2f64:
6642   case MVT::v1i128: {
6643     const unsigned VecSize = 16;
6644     const Align VecAlign(VecSize);
6645 
6646     if (!State.isVarArg()) {
6647       // If there are vector registers remaining we don't consume any stack
6648       // space.
6649       if (unsigned VReg = State.AllocateReg(VR)) {
6650         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6651         return false;
6652       }
6653       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6654       // might be allocated in the portion of the PSA that is shadowed by the
6655       // GPRs.
6656       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6657       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6658       return false;
6659     }
6660 
6661     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6662     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6663 
6664     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6665     // Burn any underaligned registers and their shadowed stack space until
6666     // we reach the required alignment.
6667     while (NextRegIndex != GPRs.size() &&
6668            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6669       // Shadow allocate register and its stack shadow.
6670       unsigned Reg = State.AllocateReg(GPRs);
6671       State.AllocateStack(PtrSize, PtrAlign);
6672       assert(Reg && "Allocating register unexpectedly failed.");
6673       (void)Reg;
6674       NextRegIndex = State.getFirstUnallocated(GPRs);
6675     }
6676 
6677     // Vectors that are passed as fixed arguments are handled differently.
6678     // They are passed in VRs if any are available (unlike arguments passed
6679     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6680     // functions)
6681     if (State.isFixed(ValNo)) {
6682       if (unsigned VReg = State.AllocateReg(VR)) {
6683         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6684         // Shadow allocate GPRs and stack space even though we pass in a VR.
6685         for (unsigned I = 0; I != VecSize; I += PtrSize)
6686           State.AllocateReg(GPRs);
6687         State.AllocateStack(VecSize, VecAlign);
6688         return false;
6689       }
6690       // No vector registers remain so pass on the stack.
6691       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6692       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6693       return false;
6694     }
6695 
6696     // If all GPRS are consumed then we pass the argument fully on the stack.
6697     if (NextRegIndex == GPRs.size()) {
6698       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6699       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6700       return false;
6701     }
6702 
6703     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6704     // half of the argument, and then need to pass the remaining half on the
6705     // stack.
6706     if (GPRs[NextRegIndex] == PPC::R9) {
6707       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6708       State.addLoc(
6709           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6710 
6711       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6712       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6713       assert(FirstReg && SecondReg &&
6714              "Allocating R9 or R10 unexpectedly failed.");
6715       State.addLoc(
6716           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6717       State.addLoc(
6718           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6719       return false;
6720     }
6721 
6722     // We have enough GPRs to fully pass the vector argument, and we have
6723     // already consumed any underaligned registers. Start with the custom
6724     // MemLoc and then the custom RegLocs.
6725     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6726     State.addLoc(
6727         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6728     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6729       const unsigned Reg = State.AllocateReg(GPRs);
6730       assert(Reg && "Failed to allocated register for vararg vector argument");
6731       State.addLoc(
6732           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6733     }
6734     return false;
6735   }
6736   }
6737   return true;
6738 }
6739 
6740 // So far, this function is only used by LowerFormalArguments_AIX()
6741 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6742                                                     bool IsPPC64,
6743                                                     bool HasP8Vector,
6744                                                     bool HasVSX) {
6745   assert((IsPPC64 || SVT != MVT::i64) &&
6746          "i64 should have been split for 32-bit codegen.");
6747 
6748   switch (SVT) {
6749   default:
6750     report_fatal_error("Unexpected value type for formal argument");
6751   case MVT::i1:
6752   case MVT::i32:
6753   case MVT::i64:
6754     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6755   case MVT::f32:
6756     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6757   case MVT::f64:
6758     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6759   case MVT::v4f32:
6760   case MVT::v4i32:
6761   case MVT::v8i16:
6762   case MVT::v16i8:
6763   case MVT::v2i64:
6764   case MVT::v2f64:
6765   case MVT::v1i128:
6766     return &PPC::VRRCRegClass;
6767   }
6768 }
6769 
6770 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6771                                         SelectionDAG &DAG, SDValue ArgValue,
6772                                         MVT LocVT, const SDLoc &dl) {
6773   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6774   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6775 
6776   if (Flags.isSExt())
6777     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6778                            DAG.getValueType(ValVT));
6779   else if (Flags.isZExt())
6780     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6781                            DAG.getValueType(ValVT));
6782 
6783   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6784 }
6785 
6786 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6787   const unsigned LASize = FL->getLinkageSize();
6788 
6789   if (PPC::GPRCRegClass.contains(Reg)) {
6790     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6791            "Reg must be a valid argument register!");
6792     return LASize + 4 * (Reg - PPC::R3);
6793   }
6794 
6795   if (PPC::G8RCRegClass.contains(Reg)) {
6796     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6797            "Reg must be a valid argument register!");
6798     return LASize + 8 * (Reg - PPC::X3);
6799   }
6800 
6801   llvm_unreachable("Only general purpose registers expected.");
6802 }
6803 
6804 //   AIX ABI Stack Frame Layout:
6805 //
6806 //   Low Memory +--------------------------------------------+
6807 //   SP   +---> | Back chain                                 | ---+
6808 //        |     +--------------------------------------------+    |
6809 //        |     | Saved Condition Register                   |    |
6810 //        |     +--------------------------------------------+    |
6811 //        |     | Saved Linkage Register                     |    |
6812 //        |     +--------------------------------------------+    | Linkage Area
6813 //        |     | Reserved for compilers                     |    |
6814 //        |     +--------------------------------------------+    |
6815 //        |     | Reserved for binders                       |    |
6816 //        |     +--------------------------------------------+    |
6817 //        |     | Saved TOC pointer                          | ---+
6818 //        |     +--------------------------------------------+
6819 //        |     | Parameter save area                        |
6820 //        |     +--------------------------------------------+
6821 //        |     | Alloca space                               |
6822 //        |     +--------------------------------------------+
6823 //        |     | Local variable space                       |
6824 //        |     +--------------------------------------------+
6825 //        |     | Float/int conversion temporary             |
6826 //        |     +--------------------------------------------+
6827 //        |     | Save area for AltiVec registers            |
6828 //        |     +--------------------------------------------+
6829 //        |     | AltiVec alignment padding                  |
6830 //        |     +--------------------------------------------+
6831 //        |     | Save area for VRSAVE register              |
6832 //        |     +--------------------------------------------+
6833 //        |     | Save area for General Purpose registers    |
6834 //        |     +--------------------------------------------+
6835 //        |     | Save area for Floating Point registers     |
6836 //        |     +--------------------------------------------+
6837 //        +---- | Back chain                                 |
6838 // High Memory  +--------------------------------------------+
6839 //
6840 //  Specifications:
6841 //  AIX 7.2 Assembler Language Reference
6842 //  Subroutine linkage convention
6843 
6844 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6845     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6846     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6847     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6848 
6849   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6850           CallConv == CallingConv::Fast) &&
6851          "Unexpected calling convention!");
6852 
6853   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6854     report_fatal_error("Tail call support is unimplemented on AIX.");
6855 
6856   if (useSoftFloat())
6857     report_fatal_error("Soft float support is unimplemented on AIX.");
6858 
6859   const PPCSubtarget &Subtarget =
6860       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6861 
6862   const bool IsPPC64 = Subtarget.isPPC64();
6863   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6864 
6865   // Assign locations to all of the incoming arguments.
6866   SmallVector<CCValAssign, 16> ArgLocs;
6867   MachineFunction &MF = DAG.getMachineFunction();
6868   MachineFrameInfo &MFI = MF.getFrameInfo();
6869   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6870   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6871 
6872   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6873   // Reserve space for the linkage area on the stack.
6874   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6875   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6876   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6877 
6878   SmallVector<SDValue, 8> MemOps;
6879 
6880   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6881     CCValAssign &VA = ArgLocs[I++];
6882     MVT LocVT = VA.getLocVT();
6883     MVT ValVT = VA.getValVT();
6884     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6885     // For compatibility with the AIX XL compiler, the float args in the
6886     // parameter save area are initialized even if the argument is available
6887     // in register.  The caller is required to initialize both the register
6888     // and memory, however, the callee can choose to expect it in either.
6889     // The memloc is dismissed here because the argument is retrieved from
6890     // the register.
6891     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6892       continue;
6893 
6894     auto HandleMemLoc = [&]() {
6895       const unsigned LocSize = LocVT.getStoreSize();
6896       const unsigned ValSize = ValVT.getStoreSize();
6897       assert((ValSize <= LocSize) &&
6898              "Object size is larger than size of MemLoc");
6899       int CurArgOffset = VA.getLocMemOffset();
6900       // Objects are right-justified because AIX is big-endian.
6901       if (LocSize > ValSize)
6902         CurArgOffset += LocSize - ValSize;
6903       // Potential tail calls could cause overwriting of argument stack slots.
6904       const bool IsImmutable =
6905           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6906             (CallConv == CallingConv::Fast));
6907       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6908       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6909       SDValue ArgValue =
6910           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6911       InVals.push_back(ArgValue);
6912     };
6913 
6914     // Vector arguments to VaArg functions are passed both on the stack, and
6915     // in any available GPRs. Load the value from the stack and add the GPRs
6916     // as live ins.
6917     if (VA.isMemLoc() && VA.needsCustom()) {
6918       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6919       assert(isVarArg && "Only use custom memloc for vararg.");
6920       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6921       // matching custom RegLocs.
6922       const unsigned OriginalValNo = VA.getValNo();
6923       (void)OriginalValNo;
6924 
6925       auto HandleCustomVecRegLoc = [&]() {
6926         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6927                "Missing custom RegLoc.");
6928         VA = ArgLocs[I++];
6929         assert(VA.getValVT().isVector() &&
6930                "Unexpected Val type for custom RegLoc.");
6931         assert(VA.getValNo() == OriginalValNo &&
6932                "ValNo mismatch between custom MemLoc and RegLoc.");
6933         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6934         MF.addLiveIn(VA.getLocReg(),
6935                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6936                                        Subtarget.hasVSX()));
6937       };
6938 
6939       HandleMemLoc();
6940       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6941       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6942       // R10.
6943       HandleCustomVecRegLoc();
6944       HandleCustomVecRegLoc();
6945 
6946       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
6947       // we passed the vector in R5, R6, R7 and R8.
6948       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
6949         assert(!IsPPC64 &&
6950                "Only 2 custom RegLocs expected for 64-bit codegen.");
6951         HandleCustomVecRegLoc();
6952         HandleCustomVecRegLoc();
6953       }
6954 
6955       continue;
6956     }
6957 
6958     if (VA.isRegLoc()) {
6959       if (VA.getValVT().isScalarInteger())
6960         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6961       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
6962         switch (VA.getValVT().SimpleTy) {
6963         default:
6964           report_fatal_error("Unhandled value type for argument.");
6965         case MVT::f32:
6966           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
6967           break;
6968         case MVT::f64:
6969           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
6970           break;
6971         }
6972       } else if (VA.getValVT().isVector()) {
6973         switch (VA.getValVT().SimpleTy) {
6974         default:
6975           report_fatal_error("Unhandled value type for argument.");
6976         case MVT::v16i8:
6977           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
6978           break;
6979         case MVT::v8i16:
6980           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
6981           break;
6982         case MVT::v4i32:
6983         case MVT::v2i64:
6984         case MVT::v1i128:
6985           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
6986           break;
6987         case MVT::v4f32:
6988         case MVT::v2f64:
6989           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
6990           break;
6991         }
6992       }
6993     }
6994 
6995     if (Flags.isByVal() && VA.isMemLoc()) {
6996       const unsigned Size =
6997           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
6998                   PtrByteSize);
6999       const int FI = MF.getFrameInfo().CreateFixedObject(
7000           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7001           /* IsAliased */ true);
7002       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7003       InVals.push_back(FIN);
7004 
7005       continue;
7006     }
7007 
7008     if (Flags.isByVal()) {
7009       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7010 
7011       const MCPhysReg ArgReg = VA.getLocReg();
7012       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7013 
7014       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7015         report_fatal_error("Over aligned byvals not supported yet.");
7016 
7017       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7018       const int FI = MF.getFrameInfo().CreateFixedObject(
7019           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7020           /* IsAliased */ true);
7021       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7022       InVals.push_back(FIN);
7023 
7024       // Add live ins for all the RegLocs for the same ByVal.
7025       const TargetRegisterClass *RegClass =
7026           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7027 
7028       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7029                                                unsigned Offset) {
7030         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7031         // Since the callers side has left justified the aggregate in the
7032         // register, we can simply store the entire register into the stack
7033         // slot.
7034         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7035         // The store to the fixedstack object is needed becuase accessing a
7036         // field of the ByVal will use a gep and load. Ideally we will optimize
7037         // to extracting the value from the register directly, and elide the
7038         // stores when the arguments address is not taken, but that will need to
7039         // be future work.
7040         SDValue Store = DAG.getStore(
7041             CopyFrom.getValue(1), dl, CopyFrom,
7042             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7043             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7044 
7045         MemOps.push_back(Store);
7046       };
7047 
7048       unsigned Offset = 0;
7049       HandleRegLoc(VA.getLocReg(), Offset);
7050       Offset += PtrByteSize;
7051       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7052            Offset += PtrByteSize) {
7053         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7054                "RegLocs should be for ByVal argument.");
7055 
7056         const CCValAssign RL = ArgLocs[I++];
7057         HandleRegLoc(RL.getLocReg(), Offset);
7058         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7059       }
7060 
7061       if (Offset != StackSize) {
7062         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7063                "Expected MemLoc for remaining bytes.");
7064         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7065         // Consume the MemLoc.The InVal has already been emitted, so nothing
7066         // more needs to be done.
7067         ++I;
7068       }
7069 
7070       continue;
7071     }
7072 
7073     if (VA.isRegLoc() && !VA.needsCustom()) {
7074       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7075       Register VReg =
7076           MF.addLiveIn(VA.getLocReg(),
7077                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7078                                          Subtarget.hasVSX()));
7079       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7080       if (ValVT.isScalarInteger() &&
7081           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7082         ArgValue =
7083             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7084       }
7085       InVals.push_back(ArgValue);
7086       continue;
7087     }
7088     if (VA.isMemLoc()) {
7089       HandleMemLoc();
7090       continue;
7091     }
7092   }
7093 
7094   // On AIX a minimum of 8 words is saved to the parameter save area.
7095   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7096   // Area that is at least reserved in the caller of this function.
7097   unsigned CallerReservedArea =
7098       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7099 
7100   // Set the size that is at least reserved in caller of this function. Tail
7101   // call optimized function's reserved stack space needs to be aligned so
7102   // that taking the difference between two stack areas will result in an
7103   // aligned stack.
7104   CallerReservedArea =
7105       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7106   FuncInfo->setMinReservedArea(CallerReservedArea);
7107 
7108   if (isVarArg) {
7109     FuncInfo->setVarArgsFrameIndex(
7110         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7111     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7112 
7113     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7114                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7115 
7116     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7117                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7118     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7119 
7120     // The fixed integer arguments of a variadic function are stored to the
7121     // VarArgsFrameIndex on the stack so that they may be loaded by
7122     // dereferencing the result of va_next.
7123     for (unsigned GPRIndex =
7124              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7125          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7126 
7127       const unsigned VReg =
7128           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7129                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7130 
7131       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7132       SDValue Store =
7133           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7134       MemOps.push_back(Store);
7135       // Increment the address for the next argument to store.
7136       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7137       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7138     }
7139   }
7140 
7141   if (!MemOps.empty())
7142     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7143 
7144   return Chain;
7145 }
7146 
7147 SDValue PPCTargetLowering::LowerCall_AIX(
7148     SDValue Chain, SDValue Callee, CallFlags CFlags,
7149     const SmallVectorImpl<ISD::OutputArg> &Outs,
7150     const SmallVectorImpl<SDValue> &OutVals,
7151     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7152     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7153     const CallBase *CB) const {
7154   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7155   // AIX ABI stack frame layout.
7156 
7157   assert((CFlags.CallConv == CallingConv::C ||
7158           CFlags.CallConv == CallingConv::Cold ||
7159           CFlags.CallConv == CallingConv::Fast) &&
7160          "Unexpected calling convention!");
7161 
7162   if (CFlags.IsPatchPoint)
7163     report_fatal_error("This call type is unimplemented on AIX.");
7164 
7165   const PPCSubtarget& Subtarget =
7166       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7167 
7168   MachineFunction &MF = DAG.getMachineFunction();
7169   SmallVector<CCValAssign, 16> ArgLocs;
7170   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7171                     *DAG.getContext());
7172 
7173   // Reserve space for the linkage save area (LSA) on the stack.
7174   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7175   //   [SP][CR][LR][2 x reserved][TOC].
7176   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7177   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7178   const bool IsPPC64 = Subtarget.isPPC64();
7179   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7180   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7181   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7182   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7183 
7184   // The prolog code of the callee may store up to 8 GPR argument registers to
7185   // the stack, allowing va_start to index over them in memory if the callee
7186   // is variadic.
7187   // Because we cannot tell if this is needed on the caller side, we have to
7188   // conservatively assume that it is needed.  As such, make sure we have at
7189   // least enough stack space for the caller to store the 8 GPRs.
7190   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7191   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7192                                      CCInfo.getNextStackOffset());
7193 
7194   // Adjust the stack pointer for the new arguments...
7195   // These operations are automatically eliminated by the prolog/epilog pass.
7196   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7197   SDValue CallSeqStart = Chain;
7198 
7199   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7200   SmallVector<SDValue, 8> MemOpChains;
7201 
7202   // Set up a copy of the stack pointer for loading and storing any
7203   // arguments that may not fit in the registers available for argument
7204   // passing.
7205   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7206                                    : DAG.getRegister(PPC::R1, MVT::i32);
7207 
7208   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7209     const unsigned ValNo = ArgLocs[I].getValNo();
7210     SDValue Arg = OutVals[ValNo];
7211     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7212 
7213     if (Flags.isByVal()) {
7214       const unsigned ByValSize = Flags.getByValSize();
7215 
7216       // Nothing to do for zero-sized ByVals on the caller side.
7217       if (!ByValSize) {
7218         ++I;
7219         continue;
7220       }
7221 
7222       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7223         return DAG.getExtLoad(
7224             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7225             (LoadOffset != 0)
7226                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7227                 : Arg,
7228             MachinePointerInfo(), VT);
7229       };
7230 
7231       unsigned LoadOffset = 0;
7232 
7233       // Initialize registers, which are fully occupied by the by-val argument.
7234       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7235         SDValue Load = GetLoad(PtrVT, LoadOffset);
7236         MemOpChains.push_back(Load.getValue(1));
7237         LoadOffset += PtrByteSize;
7238         const CCValAssign &ByValVA = ArgLocs[I++];
7239         assert(ByValVA.getValNo() == ValNo &&
7240                "Unexpected location for pass-by-value argument.");
7241         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7242       }
7243 
7244       if (LoadOffset == ByValSize)
7245         continue;
7246 
7247       // There must be one more loc to handle the remainder.
7248       assert(ArgLocs[I].getValNo() == ValNo &&
7249              "Expected additional location for by-value argument.");
7250 
7251       if (ArgLocs[I].isMemLoc()) {
7252         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7253         const CCValAssign &ByValVA = ArgLocs[I++];
7254         ISD::ArgFlagsTy MemcpyFlags = Flags;
7255         // Only memcpy the bytes that don't pass in register.
7256         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7257         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7258             (LoadOffset != 0)
7259                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7260                 : Arg,
7261             DAG.getObjectPtrOffset(dl, StackPtr,
7262                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7263             CallSeqStart, MemcpyFlags, DAG, dl);
7264         continue;
7265       }
7266 
7267       // Initialize the final register residue.
7268       // Any residue that occupies the final by-val arg register must be
7269       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7270       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7271       // 2 and 1 byte loads.
7272       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7273       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7274              "Unexpected register residue for by-value argument.");
7275       SDValue ResidueVal;
7276       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7277         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7278         const MVT VT =
7279             N == 1 ? MVT::i8
7280                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7281         SDValue Load = GetLoad(VT, LoadOffset);
7282         MemOpChains.push_back(Load.getValue(1));
7283         LoadOffset += N;
7284         Bytes += N;
7285 
7286         // By-val arguments are passed left-justfied in register.
7287         // Every load here needs to be shifted, otherwise a full register load
7288         // should have been used.
7289         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7290                "Unexpected load emitted during handling of pass-by-value "
7291                "argument.");
7292         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7293         EVT ShiftAmountTy =
7294             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7295         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7296         SDValue ShiftedLoad =
7297             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7298         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7299                                               ShiftedLoad)
7300                                 : ShiftedLoad;
7301       }
7302 
7303       const CCValAssign &ByValVA = ArgLocs[I++];
7304       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7305       continue;
7306     }
7307 
7308     CCValAssign &VA = ArgLocs[I++];
7309     const MVT LocVT = VA.getLocVT();
7310     const MVT ValVT = VA.getValVT();
7311 
7312     switch (VA.getLocInfo()) {
7313     default:
7314       report_fatal_error("Unexpected argument extension type.");
7315     case CCValAssign::Full:
7316       break;
7317     case CCValAssign::ZExt:
7318       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7319       break;
7320     case CCValAssign::SExt:
7321       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7322       break;
7323     }
7324 
7325     if (VA.isRegLoc() && !VA.needsCustom()) {
7326       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7327       continue;
7328     }
7329 
7330     // Vector arguments passed to VarArg functions need custom handling when
7331     // they are passed (at least partially) in GPRs.
7332     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7333       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7334       // Store value to its stack slot.
7335       SDValue PtrOff =
7336           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7337       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7338       SDValue Store =
7339           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7340       MemOpChains.push_back(Store);
7341       const unsigned OriginalValNo = VA.getValNo();
7342       // Then load the GPRs from the stack
7343       unsigned LoadOffset = 0;
7344       auto HandleCustomVecRegLoc = [&]() {
7345         assert(I != E && "Unexpected end of CCvalAssigns.");
7346         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7347                "Expected custom RegLoc.");
7348         CCValAssign RegVA = ArgLocs[I++];
7349         assert(RegVA.getValNo() == OriginalValNo &&
7350                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7351         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7352                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7353         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7354         MemOpChains.push_back(Load.getValue(1));
7355         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7356         LoadOffset += PtrByteSize;
7357       };
7358 
7359       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7360       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7361       // R10.
7362       HandleCustomVecRegLoc();
7363       HandleCustomVecRegLoc();
7364 
7365       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7366           ArgLocs[I].getValNo() == OriginalValNo) {
7367         assert(!IsPPC64 &&
7368                "Only 2 custom RegLocs expected for 64-bit codegen.");
7369         HandleCustomVecRegLoc();
7370         HandleCustomVecRegLoc();
7371       }
7372 
7373       continue;
7374     }
7375 
7376     if (VA.isMemLoc()) {
7377       SDValue PtrOff =
7378           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7379       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7380       MemOpChains.push_back(
7381           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7382 
7383       continue;
7384     }
7385 
7386     if (!ValVT.isFloatingPoint())
7387       report_fatal_error(
7388           "Unexpected register handling for calling convention.");
7389 
7390     // Custom handling is used for GPR initializations for vararg float
7391     // arguments.
7392     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7393            LocVT.isInteger() &&
7394            "Custom register handling only expected for VarArg.");
7395 
7396     SDValue ArgAsInt =
7397         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7398 
7399     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7400       // f32 in 32-bit GPR
7401       // f64 in 64-bit GPR
7402       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7403     else if (Arg.getValueType().getFixedSizeInBits() <
7404              LocVT.getFixedSizeInBits())
7405       // f32 in 64-bit GPR.
7406       RegsToPass.push_back(std::make_pair(
7407           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7408     else {
7409       // f64 in two 32-bit GPRs
7410       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7411       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7412              "Unexpected custom register for argument!");
7413       CCValAssign &GPR1 = VA;
7414       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7415                                      DAG.getConstant(32, dl, MVT::i8));
7416       RegsToPass.push_back(std::make_pair(
7417           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7418 
7419       if (I != E) {
7420         // If only 1 GPR was available, there will only be one custom GPR and
7421         // the argument will also pass in memory.
7422         CCValAssign &PeekArg = ArgLocs[I];
7423         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7424           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7425           CCValAssign &GPR2 = ArgLocs[I++];
7426           RegsToPass.push_back(std::make_pair(
7427               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7428         }
7429       }
7430     }
7431   }
7432 
7433   if (!MemOpChains.empty())
7434     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7435 
7436   // For indirect calls, we need to save the TOC base to the stack for
7437   // restoration after the call.
7438   if (CFlags.IsIndirect) {
7439     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7440     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7441     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7442     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7443     const unsigned TOCSaveOffset =
7444         Subtarget.getFrameLowering()->getTOCSaveOffset();
7445 
7446     setUsesTOCBasePtr(DAG);
7447     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7448     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7449     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7450     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7451     Chain = DAG.getStore(
7452         Val.getValue(1), dl, Val, AddPtr,
7453         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7454   }
7455 
7456   // Build a sequence of copy-to-reg nodes chained together with token chain
7457   // and flag operands which copy the outgoing args into the appropriate regs.
7458   SDValue InFlag;
7459   for (auto Reg : RegsToPass) {
7460     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7461     InFlag = Chain.getValue(1);
7462   }
7463 
7464   const int SPDiff = 0;
7465   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7466                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7467 }
7468 
7469 bool
7470 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7471                                   MachineFunction &MF, bool isVarArg,
7472                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7473                                   LLVMContext &Context) const {
7474   SmallVector<CCValAssign, 16> RVLocs;
7475   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7476   return CCInfo.CheckReturn(
7477       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7478                 ? RetCC_PPC_Cold
7479                 : RetCC_PPC);
7480 }
7481 
7482 SDValue
7483 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7484                                bool isVarArg,
7485                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7486                                const SmallVectorImpl<SDValue> &OutVals,
7487                                const SDLoc &dl, SelectionDAG &DAG) const {
7488   SmallVector<CCValAssign, 16> RVLocs;
7489   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7490                  *DAG.getContext());
7491   CCInfo.AnalyzeReturn(Outs,
7492                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7493                            ? RetCC_PPC_Cold
7494                            : RetCC_PPC);
7495 
7496   SDValue Flag;
7497   SmallVector<SDValue, 4> RetOps(1, Chain);
7498 
7499   // Copy the result values into the output registers.
7500   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7501     CCValAssign &VA = RVLocs[i];
7502     assert(VA.isRegLoc() && "Can only return in registers!");
7503 
7504     SDValue Arg = OutVals[RealResIdx];
7505 
7506     switch (VA.getLocInfo()) {
7507     default: llvm_unreachable("Unknown loc info!");
7508     case CCValAssign::Full: break;
7509     case CCValAssign::AExt:
7510       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7511       break;
7512     case CCValAssign::ZExt:
7513       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7514       break;
7515     case CCValAssign::SExt:
7516       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7517       break;
7518     }
7519     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7520       bool isLittleEndian = Subtarget.isLittleEndian();
7521       // Legalize ret f64 -> ret 2 x i32.
7522       SDValue SVal =
7523           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7524                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7525       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7526       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7527       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7528                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7529       Flag = Chain.getValue(1);
7530       VA = RVLocs[++i]; // skip ahead to next loc
7531       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7532     } else
7533       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7534     Flag = Chain.getValue(1);
7535     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7536   }
7537 
7538   RetOps[0] = Chain;  // Update chain.
7539 
7540   // Add the flag if we have it.
7541   if (Flag.getNode())
7542     RetOps.push_back(Flag);
7543 
7544   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7545 }
7546 
7547 SDValue
7548 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7549                                                 SelectionDAG &DAG) const {
7550   SDLoc dl(Op);
7551 
7552   // Get the correct type for integers.
7553   EVT IntVT = Op.getValueType();
7554 
7555   // Get the inputs.
7556   SDValue Chain = Op.getOperand(0);
7557   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7558   // Build a DYNAREAOFFSET node.
7559   SDValue Ops[2] = {Chain, FPSIdx};
7560   SDVTList VTs = DAG.getVTList(IntVT);
7561   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7562 }
7563 
7564 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7565                                              SelectionDAG &DAG) const {
7566   // When we pop the dynamic allocation we need to restore the SP link.
7567   SDLoc dl(Op);
7568 
7569   // Get the correct type for pointers.
7570   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7571 
7572   // Construct the stack pointer operand.
7573   bool isPPC64 = Subtarget.isPPC64();
7574   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7575   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7576 
7577   // Get the operands for the STACKRESTORE.
7578   SDValue Chain = Op.getOperand(0);
7579   SDValue SaveSP = Op.getOperand(1);
7580 
7581   // Load the old link SP.
7582   SDValue LoadLinkSP =
7583       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7584 
7585   // Restore the stack pointer.
7586   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7587 
7588   // Store the old link SP.
7589   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7590 }
7591 
7592 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7593   MachineFunction &MF = DAG.getMachineFunction();
7594   bool isPPC64 = Subtarget.isPPC64();
7595   EVT PtrVT = getPointerTy(MF.getDataLayout());
7596 
7597   // Get current frame pointer save index.  The users of this index will be
7598   // primarily DYNALLOC instructions.
7599   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7600   int RASI = FI->getReturnAddrSaveIndex();
7601 
7602   // If the frame pointer save index hasn't been defined yet.
7603   if (!RASI) {
7604     // Find out what the fix offset of the frame pointer save area.
7605     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7606     // Allocate the frame index for frame pointer save area.
7607     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7608     // Save the result.
7609     FI->setReturnAddrSaveIndex(RASI);
7610   }
7611   return DAG.getFrameIndex(RASI, PtrVT);
7612 }
7613 
7614 SDValue
7615 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7616   MachineFunction &MF = DAG.getMachineFunction();
7617   bool isPPC64 = Subtarget.isPPC64();
7618   EVT PtrVT = getPointerTy(MF.getDataLayout());
7619 
7620   // Get current frame pointer save index.  The users of this index will be
7621   // primarily DYNALLOC instructions.
7622   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7623   int FPSI = FI->getFramePointerSaveIndex();
7624 
7625   // If the frame pointer save index hasn't been defined yet.
7626   if (!FPSI) {
7627     // Find out what the fix offset of the frame pointer save area.
7628     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7629     // Allocate the frame index for frame pointer save area.
7630     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7631     // Save the result.
7632     FI->setFramePointerSaveIndex(FPSI);
7633   }
7634   return DAG.getFrameIndex(FPSI, PtrVT);
7635 }
7636 
7637 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7638                                                    SelectionDAG &DAG) const {
7639   MachineFunction &MF = DAG.getMachineFunction();
7640   // Get the inputs.
7641   SDValue Chain = Op.getOperand(0);
7642   SDValue Size  = Op.getOperand(1);
7643   SDLoc dl(Op);
7644 
7645   // Get the correct type for pointers.
7646   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7647   // Negate the size.
7648   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7649                                 DAG.getConstant(0, dl, PtrVT), Size);
7650   // Construct a node for the frame pointer save index.
7651   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7652   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7653   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7654   if (hasInlineStackProbe(MF))
7655     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7656   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7657 }
7658 
7659 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7660                                                      SelectionDAG &DAG) const {
7661   MachineFunction &MF = DAG.getMachineFunction();
7662 
7663   bool isPPC64 = Subtarget.isPPC64();
7664   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7665 
7666   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7667   return DAG.getFrameIndex(FI, PtrVT);
7668 }
7669 
7670 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7671                                                SelectionDAG &DAG) const {
7672   SDLoc DL(Op);
7673   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7674                      DAG.getVTList(MVT::i32, MVT::Other),
7675                      Op.getOperand(0), Op.getOperand(1));
7676 }
7677 
7678 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7679                                                 SelectionDAG &DAG) const {
7680   SDLoc DL(Op);
7681   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7682                      Op.getOperand(0), Op.getOperand(1));
7683 }
7684 
7685 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7686   if (Op.getValueType().isVector())
7687     return LowerVectorLoad(Op, DAG);
7688 
7689   assert(Op.getValueType() == MVT::i1 &&
7690          "Custom lowering only for i1 loads");
7691 
7692   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7693 
7694   SDLoc dl(Op);
7695   LoadSDNode *LD = cast<LoadSDNode>(Op);
7696 
7697   SDValue Chain = LD->getChain();
7698   SDValue BasePtr = LD->getBasePtr();
7699   MachineMemOperand *MMO = LD->getMemOperand();
7700 
7701   SDValue NewLD =
7702       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7703                      BasePtr, MVT::i8, MMO);
7704   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7705 
7706   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7707   return DAG.getMergeValues(Ops, dl);
7708 }
7709 
7710 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7711   if (Op.getOperand(1).getValueType().isVector())
7712     return LowerVectorStore(Op, DAG);
7713 
7714   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7715          "Custom lowering only for i1 stores");
7716 
7717   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7718 
7719   SDLoc dl(Op);
7720   StoreSDNode *ST = cast<StoreSDNode>(Op);
7721 
7722   SDValue Chain = ST->getChain();
7723   SDValue BasePtr = ST->getBasePtr();
7724   SDValue Value = ST->getValue();
7725   MachineMemOperand *MMO = ST->getMemOperand();
7726 
7727   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7728                       Value);
7729   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7730 }
7731 
7732 // FIXME: Remove this once the ANDI glue bug is fixed:
7733 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7734   assert(Op.getValueType() == MVT::i1 &&
7735          "Custom lowering only for i1 results");
7736 
7737   SDLoc DL(Op);
7738   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7739 }
7740 
7741 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7742                                                SelectionDAG &DAG) const {
7743 
7744   // Implements a vector truncate that fits in a vector register as a shuffle.
7745   // We want to legalize vector truncates down to where the source fits in
7746   // a vector register (and target is therefore smaller than vector register
7747   // size).  At that point legalization will try to custom lower the sub-legal
7748   // result and get here - where we can contain the truncate as a single target
7749   // operation.
7750 
7751   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7752   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7753   //
7754   // We will implement it for big-endian ordering as this (where x denotes
7755   // undefined):
7756   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7757   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7758   //
7759   // The same operation in little-endian ordering will be:
7760   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7761   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7762 
7763   EVT TrgVT = Op.getValueType();
7764   assert(TrgVT.isVector() && "Vector type expected.");
7765   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7766   EVT EltVT = TrgVT.getVectorElementType();
7767   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7768       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7769       !isPowerOf2_32(EltVT.getSizeInBits()))
7770     return SDValue();
7771 
7772   SDValue N1 = Op.getOperand(0);
7773   EVT SrcVT = N1.getValueType();
7774   unsigned SrcSize = SrcVT.getSizeInBits();
7775   if (SrcSize > 256 ||
7776       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7777       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7778     return SDValue();
7779   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7780     return SDValue();
7781 
7782   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7783   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7784 
7785   SDLoc DL(Op);
7786   SDValue Op1, Op2;
7787   if (SrcSize == 256) {
7788     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7789     EVT SplitVT =
7790         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7791     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7792     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7793                       DAG.getConstant(0, DL, VecIdxTy));
7794     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7795                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7796   }
7797   else {
7798     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7799     Op2 = DAG.getUNDEF(WideVT);
7800   }
7801 
7802   // First list the elements we want to keep.
7803   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7804   SmallVector<int, 16> ShuffV;
7805   if (Subtarget.isLittleEndian())
7806     for (unsigned i = 0; i < TrgNumElts; ++i)
7807       ShuffV.push_back(i * SizeMult);
7808   else
7809     for (unsigned i = 1; i <= TrgNumElts; ++i)
7810       ShuffV.push_back(i * SizeMult - 1);
7811 
7812   // Populate the remaining elements with undefs.
7813   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7814     // ShuffV.push_back(i + WideNumElts);
7815     ShuffV.push_back(WideNumElts + 1);
7816 
7817   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7818   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7819   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7820 }
7821 
7822 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7823 /// possible.
7824 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7825   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7826   EVT ResVT = Op.getValueType();
7827   EVT CmpVT = Op.getOperand(0).getValueType();
7828   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7829   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7830   SDLoc dl(Op);
7831 
7832   // Without power9-vector, we don't have native instruction for f128 comparison.
7833   // Following transformation to libcall is needed for setcc:
7834   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7835   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7836     SDValue Z = DAG.getSetCC(
7837         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7838         LHS, RHS, CC);
7839     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7840     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7841   }
7842 
7843   // Not FP, or using SPE? Not a fsel.
7844   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7845       Subtarget.hasSPE())
7846     return Op;
7847 
7848   SDNodeFlags Flags = Op.getNode()->getFlags();
7849 
7850   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7851   // presence of infinities.
7852   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7853     switch (CC) {
7854     default:
7855       break;
7856     case ISD::SETOGT:
7857     case ISD::SETGT:
7858       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7859     case ISD::SETOLT:
7860     case ISD::SETLT:
7861       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7862     }
7863   }
7864 
7865   // We might be able to do better than this under some circumstances, but in
7866   // general, fsel-based lowering of select is a finite-math-only optimization.
7867   // For more information, see section F.3 of the 2.06 ISA specification.
7868   // With ISA 3.0
7869   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7870       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7871     return Op;
7872 
7873   // If the RHS of the comparison is a 0.0, we don't need to do the
7874   // subtraction at all.
7875   SDValue Sel1;
7876   if (isFloatingPointZero(RHS))
7877     switch (CC) {
7878     default: break;       // SETUO etc aren't handled by fsel.
7879     case ISD::SETNE:
7880       std::swap(TV, FV);
7881       LLVM_FALLTHROUGH;
7882     case ISD::SETEQ:
7883       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7884         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7885       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7886       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7887         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7888       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7889                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7890     case ISD::SETULT:
7891     case ISD::SETLT:
7892       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7893       LLVM_FALLTHROUGH;
7894     case ISD::SETOGE:
7895     case ISD::SETGE:
7896       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7897         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7898       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7899     case ISD::SETUGT:
7900     case ISD::SETGT:
7901       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7902       LLVM_FALLTHROUGH;
7903     case ISD::SETOLE:
7904     case ISD::SETLE:
7905       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7906         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7907       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7908                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7909     }
7910 
7911   SDValue Cmp;
7912   switch (CC) {
7913   default: break;       // SETUO etc aren't handled by fsel.
7914   case ISD::SETNE:
7915     std::swap(TV, FV);
7916     LLVM_FALLTHROUGH;
7917   case ISD::SETEQ:
7918     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7919     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7920       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7921     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7922     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7923       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7924     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7925                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7926   case ISD::SETULT:
7927   case ISD::SETLT:
7928     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7929     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7930       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7931     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7932   case ISD::SETOGE:
7933   case ISD::SETGE:
7934     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7935     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7936       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7937     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7938   case ISD::SETUGT:
7939   case ISD::SETGT:
7940     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7941     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7942       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7943     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7944   case ISD::SETOLE:
7945   case ISD::SETLE:
7946     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7947     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7948       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7949     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7950   }
7951   return Op;
7952 }
7953 
7954 static unsigned getPPCStrictOpcode(unsigned Opc) {
7955   switch (Opc) {
7956   default:
7957     llvm_unreachable("No strict version of this opcode!");
7958   case PPCISD::FCTIDZ:
7959     return PPCISD::STRICT_FCTIDZ;
7960   case PPCISD::FCTIWZ:
7961     return PPCISD::STRICT_FCTIWZ;
7962   case PPCISD::FCTIDUZ:
7963     return PPCISD::STRICT_FCTIDUZ;
7964   case PPCISD::FCTIWUZ:
7965     return PPCISD::STRICT_FCTIWUZ;
7966   case PPCISD::FCFID:
7967     return PPCISD::STRICT_FCFID;
7968   case PPCISD::FCFIDU:
7969     return PPCISD::STRICT_FCFIDU;
7970   case PPCISD::FCFIDS:
7971     return PPCISD::STRICT_FCFIDS;
7972   case PPCISD::FCFIDUS:
7973     return PPCISD::STRICT_FCFIDUS;
7974   }
7975 }
7976 
7977 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7978                               const PPCSubtarget &Subtarget) {
7979   SDLoc dl(Op);
7980   bool IsStrict = Op->isStrictFPOpcode();
7981   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7982                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7983 
7984   // TODO: Any other flags to propagate?
7985   SDNodeFlags Flags;
7986   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7987 
7988   // For strict nodes, source is the second operand.
7989   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7990   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
7991   assert(Src.getValueType().isFloatingPoint());
7992   if (Src.getValueType() == MVT::f32) {
7993     if (IsStrict) {
7994       Src =
7995           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
7996                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
7997       Chain = Src.getValue(1);
7998     } else
7999       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8000   }
8001   SDValue Conv;
8002   unsigned Opc = ISD::DELETED_NODE;
8003   switch (Op.getSimpleValueType().SimpleTy) {
8004   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8005   case MVT::i32:
8006     Opc = IsSigned ? PPCISD::FCTIWZ
8007                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8008     break;
8009   case MVT::i64:
8010     assert((IsSigned || Subtarget.hasFPCVT()) &&
8011            "i64 FP_TO_UINT is supported only with FPCVT");
8012     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8013   }
8014   if (IsStrict) {
8015     Opc = getPPCStrictOpcode(Opc);
8016     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8017                        {Chain, Src}, Flags);
8018   } else {
8019     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8020   }
8021   return Conv;
8022 }
8023 
8024 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8025                                                SelectionDAG &DAG,
8026                                                const SDLoc &dl) const {
8027   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8028   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8029                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8030   bool IsStrict = Op->isStrictFPOpcode();
8031 
8032   // Convert the FP value to an int value through memory.
8033   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8034                   (IsSigned || Subtarget.hasFPCVT());
8035   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8036   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8037   MachinePointerInfo MPI =
8038       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8039 
8040   // Emit a store to the stack slot.
8041   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8042   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8043   if (i32Stack) {
8044     MachineFunction &MF = DAG.getMachineFunction();
8045     Alignment = Align(4);
8046     MachineMemOperand *MMO =
8047         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8048     SDValue Ops[] = { Chain, Tmp, FIPtr };
8049     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8050               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8051   } else
8052     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8053 
8054   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8055   // add in a bias on big endian.
8056   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8057     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8058                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8059     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8060   }
8061 
8062   RLI.Chain = Chain;
8063   RLI.Ptr = FIPtr;
8064   RLI.MPI = MPI;
8065   RLI.Alignment = Alignment;
8066 }
8067 
8068 /// Custom lowers floating point to integer conversions to use
8069 /// the direct move instructions available in ISA 2.07 to avoid the
8070 /// need for load/store combinations.
8071 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8072                                                     SelectionDAG &DAG,
8073                                                     const SDLoc &dl) const {
8074   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8075   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8076   if (Op->isStrictFPOpcode())
8077     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8078   else
8079     return Mov;
8080 }
8081 
8082 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8083                                           const SDLoc &dl) const {
8084   bool IsStrict = Op->isStrictFPOpcode();
8085   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8086                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8087   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8088   EVT SrcVT = Src.getValueType();
8089   EVT DstVT = Op.getValueType();
8090 
8091   // FP to INT conversions are legal for f128.
8092   if (SrcVT == MVT::f128)
8093     return Subtarget.hasP9Vector() ? Op : SDValue();
8094 
8095   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8096   // PPC (the libcall is not available).
8097   if (SrcVT == MVT::ppcf128) {
8098     if (DstVT == MVT::i32) {
8099       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8100       // set other fast-math flags to FP operations in both strict and
8101       // non-strict cases. (FP_TO_SINT, FSUB)
8102       SDNodeFlags Flags;
8103       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8104 
8105       if (IsSigned) {
8106         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8107                                  DAG.getIntPtrConstant(0, dl));
8108         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8109                                  DAG.getIntPtrConstant(1, dl));
8110 
8111         // Add the two halves of the long double in round-to-zero mode, and use
8112         // a smaller FP_TO_SINT.
8113         if (IsStrict) {
8114           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8115                                     DAG.getVTList(MVT::f64, MVT::Other),
8116                                     {Op.getOperand(0), Lo, Hi}, Flags);
8117           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8118                              DAG.getVTList(MVT::i32, MVT::Other),
8119                              {Res.getValue(1), Res}, Flags);
8120         } else {
8121           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8122           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8123         }
8124       } else {
8125         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8126         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8127         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8128         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8129         if (IsStrict) {
8130           // Sel = Src < 0x80000000
8131           // FltOfs = select Sel, 0.0, 0x80000000
8132           // IntOfs = select Sel, 0, 0x80000000
8133           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8134           SDValue Chain = Op.getOperand(0);
8135           EVT SetCCVT =
8136               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8137           EVT DstSetCCVT =
8138               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8139           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8140                                      Chain, true);
8141           Chain = Sel.getValue(1);
8142 
8143           SDValue FltOfs = DAG.getSelect(
8144               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8145           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8146 
8147           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8148                                     DAG.getVTList(SrcVT, MVT::Other),
8149                                     {Chain, Src, FltOfs}, Flags);
8150           Chain = Val.getValue(1);
8151           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8152                                      DAG.getVTList(DstVT, MVT::Other),
8153                                      {Chain, Val}, Flags);
8154           Chain = SInt.getValue(1);
8155           SDValue IntOfs = DAG.getSelect(
8156               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8157           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8158           return DAG.getMergeValues({Result, Chain}, dl);
8159         } else {
8160           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8161           // FIXME: generated code sucks.
8162           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8163           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8164           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8165           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8166           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8167         }
8168       }
8169     }
8170 
8171     return SDValue();
8172   }
8173 
8174   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8175     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8176 
8177   ReuseLoadInfo RLI;
8178   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8179 
8180   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8181                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8182 }
8183 
8184 // We're trying to insert a regular store, S, and then a load, L. If the
8185 // incoming value, O, is a load, we might just be able to have our load use the
8186 // address used by O. However, we don't know if anything else will store to
8187 // that address before we can load from it. To prevent this situation, we need
8188 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8189 // the same chain operand as O, we create a token factor from the chain results
8190 // of O and L, and we replace all uses of O's chain result with that token
8191 // factor (see spliceIntoChain below for this last part).
8192 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8193                                             ReuseLoadInfo &RLI,
8194                                             SelectionDAG &DAG,
8195                                             ISD::LoadExtType ET) const {
8196   // Conservatively skip reusing for constrained FP nodes.
8197   if (Op->isStrictFPOpcode())
8198     return false;
8199 
8200   SDLoc dl(Op);
8201   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8202                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8203   if (ET == ISD::NON_EXTLOAD &&
8204       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8205       isOperationLegalOrCustom(Op.getOpcode(),
8206                                Op.getOperand(0).getValueType())) {
8207 
8208     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8209     return true;
8210   }
8211 
8212   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8213   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8214       LD->isNonTemporal())
8215     return false;
8216   if (LD->getMemoryVT() != MemVT)
8217     return false;
8218 
8219   // If the result of the load is an illegal type, then we can't build a
8220   // valid chain for reuse since the legalised loads and token factor node that
8221   // ties the legalised loads together uses a different output chain then the
8222   // illegal load.
8223   if (!isTypeLegal(LD->getValueType(0)))
8224     return false;
8225 
8226   RLI.Ptr = LD->getBasePtr();
8227   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8228     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8229            "Non-pre-inc AM on PPC?");
8230     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8231                           LD->getOffset());
8232   }
8233 
8234   RLI.Chain = LD->getChain();
8235   RLI.MPI = LD->getPointerInfo();
8236   RLI.IsDereferenceable = LD->isDereferenceable();
8237   RLI.IsInvariant = LD->isInvariant();
8238   RLI.Alignment = LD->getAlign();
8239   RLI.AAInfo = LD->getAAInfo();
8240   RLI.Ranges = LD->getRanges();
8241 
8242   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8243   return true;
8244 }
8245 
8246 // Given the head of the old chain, ResChain, insert a token factor containing
8247 // it and NewResChain, and make users of ResChain now be users of that token
8248 // factor.
8249 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8250 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8251                                         SDValue NewResChain,
8252                                         SelectionDAG &DAG) const {
8253   if (!ResChain)
8254     return;
8255 
8256   SDLoc dl(NewResChain);
8257 
8258   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8259                            NewResChain, DAG.getUNDEF(MVT::Other));
8260   assert(TF.getNode() != NewResChain.getNode() &&
8261          "A new TF really is required here");
8262 
8263   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8264   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8265 }
8266 
8267 /// Analyze profitability of direct move
8268 /// prefer float load to int load plus direct move
8269 /// when there is no integer use of int load
8270 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8271   SDNode *Origin = Op.getOperand(0).getNode();
8272   if (Origin->getOpcode() != ISD::LOAD)
8273     return true;
8274 
8275   // If there is no LXSIBZX/LXSIHZX, like Power8,
8276   // prefer direct move if the memory size is 1 or 2 bytes.
8277   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8278   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8279     return true;
8280 
8281   for (SDNode::use_iterator UI = Origin->use_begin(),
8282                             UE = Origin->use_end();
8283        UI != UE; ++UI) {
8284 
8285     // Only look at the users of the loaded value.
8286     if (UI.getUse().get().getResNo() != 0)
8287       continue;
8288 
8289     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8290         UI->getOpcode() != ISD::UINT_TO_FP &&
8291         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8292         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8293       return true;
8294   }
8295 
8296   return false;
8297 }
8298 
8299 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8300                               const PPCSubtarget &Subtarget,
8301                               SDValue Chain = SDValue()) {
8302   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8303                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8304   SDLoc dl(Op);
8305 
8306   // TODO: Any other flags to propagate?
8307   SDNodeFlags Flags;
8308   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8309 
8310   // If we have FCFIDS, then use it when converting to single-precision.
8311   // Otherwise, convert to double-precision and then round.
8312   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8313   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8314                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8315   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8316   if (Op->isStrictFPOpcode()) {
8317     if (!Chain)
8318       Chain = Op.getOperand(0);
8319     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8320                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8321   } else
8322     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8323 }
8324 
8325 /// Custom lowers integer to floating point conversions to use
8326 /// the direct move instructions available in ISA 2.07 to avoid the
8327 /// need for load/store combinations.
8328 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8329                                                     SelectionDAG &DAG,
8330                                                     const SDLoc &dl) const {
8331   assert((Op.getValueType() == MVT::f32 ||
8332           Op.getValueType() == MVT::f64) &&
8333          "Invalid floating point type as target of conversion");
8334   assert(Subtarget.hasFPCVT() &&
8335          "Int to FP conversions with direct moves require FPCVT");
8336   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8337   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8338   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8339                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8340   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8341   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8342   return convertIntToFP(Op, Mov, DAG, Subtarget);
8343 }
8344 
8345 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8346 
8347   EVT VecVT = Vec.getValueType();
8348   assert(VecVT.isVector() && "Expected a vector type.");
8349   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8350 
8351   EVT EltVT = VecVT.getVectorElementType();
8352   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8353   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8354 
8355   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8356   SmallVector<SDValue, 16> Ops(NumConcat);
8357   Ops[0] = Vec;
8358   SDValue UndefVec = DAG.getUNDEF(VecVT);
8359   for (unsigned i = 1; i < NumConcat; ++i)
8360     Ops[i] = UndefVec;
8361 
8362   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8363 }
8364 
8365 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8366                                                 const SDLoc &dl) const {
8367   bool IsStrict = Op->isStrictFPOpcode();
8368   unsigned Opc = Op.getOpcode();
8369   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8370   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8371           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8372          "Unexpected conversion type");
8373   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8374          "Supports conversions to v2f64/v4f32 only.");
8375 
8376   // TODO: Any other flags to propagate?
8377   SDNodeFlags Flags;
8378   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8379 
8380   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8381   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8382 
8383   SDValue Wide = widenVec(DAG, Src, dl);
8384   EVT WideVT = Wide.getValueType();
8385   unsigned WideNumElts = WideVT.getVectorNumElements();
8386   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8387 
8388   SmallVector<int, 16> ShuffV;
8389   for (unsigned i = 0; i < WideNumElts; ++i)
8390     ShuffV.push_back(i + WideNumElts);
8391 
8392   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8393   int SaveElts = FourEltRes ? 4 : 2;
8394   if (Subtarget.isLittleEndian())
8395     for (int i = 0; i < SaveElts; i++)
8396       ShuffV[i * Stride] = i;
8397   else
8398     for (int i = 1; i <= SaveElts; i++)
8399       ShuffV[i * Stride - 1] = i - 1;
8400 
8401   SDValue ShuffleSrc2 =
8402       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8403   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8404 
8405   SDValue Extend;
8406   if (SignedConv) {
8407     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8408     EVT ExtVT = Src.getValueType();
8409     if (Subtarget.hasP9Altivec())
8410       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8411                                IntermediateVT.getVectorNumElements());
8412 
8413     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8414                          DAG.getValueType(ExtVT));
8415   } else
8416     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8417 
8418   if (IsStrict)
8419     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8420                        {Op.getOperand(0), Extend}, Flags);
8421 
8422   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8423 }
8424 
8425 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8426                                           SelectionDAG &DAG) const {
8427   SDLoc dl(Op);
8428   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8429                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8430   bool IsStrict = Op->isStrictFPOpcode();
8431   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8432   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8433 
8434   // TODO: Any other flags to propagate?
8435   SDNodeFlags Flags;
8436   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8437 
8438   EVT InVT = Src.getValueType();
8439   EVT OutVT = Op.getValueType();
8440   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8441       isOperationCustom(Op.getOpcode(), InVT))
8442     return LowerINT_TO_FPVector(Op, DAG, dl);
8443 
8444   // Conversions to f128 are legal.
8445   if (Op.getValueType() == MVT::f128)
8446     return Subtarget.hasP9Vector() ? Op : SDValue();
8447 
8448   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8449   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8450     return SDValue();
8451 
8452   if (Src.getValueType() == MVT::i1) {
8453     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8454                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8455                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8456     if (IsStrict)
8457       return DAG.getMergeValues({Sel, Chain}, dl);
8458     else
8459       return Sel;
8460   }
8461 
8462   // If we have direct moves, we can do all the conversion, skip the store/load
8463   // however, without FPCVT we can't do most conversions.
8464   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8465       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8466     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8467 
8468   assert((IsSigned || Subtarget.hasFPCVT()) &&
8469          "UINT_TO_FP is supported only with FPCVT");
8470 
8471   if (Src.getValueType() == MVT::i64) {
8472     SDValue SINT = Src;
8473     // When converting to single-precision, we actually need to convert
8474     // to double-precision first and then round to single-precision.
8475     // To avoid double-rounding effects during that operation, we have
8476     // to prepare the input operand.  Bits that might be truncated when
8477     // converting to double-precision are replaced by a bit that won't
8478     // be lost at this stage, but is below the single-precision rounding
8479     // position.
8480     //
8481     // However, if -enable-unsafe-fp-math is in effect, accept double
8482     // rounding to avoid the extra overhead.
8483     if (Op.getValueType() == MVT::f32 &&
8484         !Subtarget.hasFPCVT() &&
8485         !DAG.getTarget().Options.UnsafeFPMath) {
8486 
8487       // Twiddle input to make sure the low 11 bits are zero.  (If this
8488       // is the case, we are guaranteed the value will fit into the 53 bit
8489       // mantissa of an IEEE double-precision value without rounding.)
8490       // If any of those low 11 bits were not zero originally, make sure
8491       // bit 12 (value 2048) is set instead, so that the final rounding
8492       // to single-precision gets the correct result.
8493       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8494                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8495       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8496                           Round, DAG.getConstant(2047, dl, MVT::i64));
8497       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8498       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8499                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8500 
8501       // However, we cannot use that value unconditionally: if the magnitude
8502       // of the input value is small, the bit-twiddling we did above might
8503       // end up visibly changing the output.  Fortunately, in that case, we
8504       // don't need to twiddle bits since the original input will convert
8505       // exactly to double-precision floating-point already.  Therefore,
8506       // construct a conditional to use the original value if the top 11
8507       // bits are all sign-bit copies, and use the rounded value computed
8508       // above otherwise.
8509       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8510                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8511       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8512                          Cond, DAG.getConstant(1, dl, MVT::i64));
8513       Cond = DAG.getSetCC(
8514           dl,
8515           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8516           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8517 
8518       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8519     }
8520 
8521     ReuseLoadInfo RLI;
8522     SDValue Bits;
8523 
8524     MachineFunction &MF = DAG.getMachineFunction();
8525     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8526       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8527                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8528       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8529     } else if (Subtarget.hasLFIWAX() &&
8530                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8531       MachineMemOperand *MMO =
8532         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8533                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8534       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8535       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8536                                      DAG.getVTList(MVT::f64, MVT::Other),
8537                                      Ops, MVT::i32, MMO);
8538       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8539     } else if (Subtarget.hasFPCVT() &&
8540                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8541       MachineMemOperand *MMO =
8542         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8543                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8544       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8545       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8546                                      DAG.getVTList(MVT::f64, MVT::Other),
8547                                      Ops, MVT::i32, MMO);
8548       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8549     } else if (((Subtarget.hasLFIWAX() &&
8550                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8551                 (Subtarget.hasFPCVT() &&
8552                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8553                SINT.getOperand(0).getValueType() == MVT::i32) {
8554       MachineFrameInfo &MFI = MF.getFrameInfo();
8555       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8556 
8557       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8558       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8559 
8560       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8561                                    MachinePointerInfo::getFixedStack(
8562                                        DAG.getMachineFunction(), FrameIdx));
8563       Chain = Store;
8564 
8565       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8566              "Expected an i32 store");
8567 
8568       RLI.Ptr = FIdx;
8569       RLI.Chain = Chain;
8570       RLI.MPI =
8571           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8572       RLI.Alignment = Align(4);
8573 
8574       MachineMemOperand *MMO =
8575         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8576                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8577       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8578       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8579                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8580                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8581                                      Ops, MVT::i32, MMO);
8582       Chain = Bits.getValue(1);
8583     } else
8584       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8585 
8586     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8587     if (IsStrict)
8588       Chain = FP.getValue(1);
8589 
8590     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8591       if (IsStrict)
8592         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8593                          DAG.getVTList(MVT::f32, MVT::Other),
8594                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8595       else
8596         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8597                          DAG.getIntPtrConstant(0, dl));
8598     }
8599     return FP;
8600   }
8601 
8602   assert(Src.getValueType() == MVT::i32 &&
8603          "Unhandled INT_TO_FP type in custom expander!");
8604   // Since we only generate this in 64-bit mode, we can take advantage of
8605   // 64-bit registers.  In particular, sign extend the input value into the
8606   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8607   // then lfd it and fcfid it.
8608   MachineFunction &MF = DAG.getMachineFunction();
8609   MachineFrameInfo &MFI = MF.getFrameInfo();
8610   EVT PtrVT = getPointerTy(MF.getDataLayout());
8611 
8612   SDValue Ld;
8613   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8614     ReuseLoadInfo RLI;
8615     bool ReusingLoad;
8616     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8617       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8618       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8619 
8620       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8621                                    MachinePointerInfo::getFixedStack(
8622                                        DAG.getMachineFunction(), FrameIdx));
8623       Chain = Store;
8624 
8625       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8626              "Expected an i32 store");
8627 
8628       RLI.Ptr = FIdx;
8629       RLI.Chain = Chain;
8630       RLI.MPI =
8631           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8632       RLI.Alignment = Align(4);
8633     }
8634 
8635     MachineMemOperand *MMO =
8636       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8637                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8638     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8639     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8640                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8641                                  MVT::i32, MMO);
8642     Chain = Ld.getValue(1);
8643     if (ReusingLoad)
8644       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8645   } else {
8646     assert(Subtarget.isPPC64() &&
8647            "i32->FP without LFIWAX supported only on PPC64");
8648 
8649     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8650     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8651 
8652     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8653 
8654     // STD the extended value into the stack slot.
8655     SDValue Store = DAG.getStore(
8656         Chain, dl, Ext64, FIdx,
8657         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8658     Chain = Store;
8659 
8660     // Load the value as a double.
8661     Ld = DAG.getLoad(
8662         MVT::f64, dl, Chain, FIdx,
8663         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8664     Chain = Ld.getValue(1);
8665   }
8666 
8667   // FCFID it and return it.
8668   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8669   if (IsStrict)
8670     Chain = FP.getValue(1);
8671   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8672     if (IsStrict)
8673       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8674                        DAG.getVTList(MVT::f32, MVT::Other),
8675                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8676     else
8677       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8678                        DAG.getIntPtrConstant(0, dl));
8679   }
8680   return FP;
8681 }
8682 
8683 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8684                                             SelectionDAG &DAG) const {
8685   SDLoc dl(Op);
8686   /*
8687    The rounding mode is in bits 30:31 of FPSR, and has the following
8688    settings:
8689      00 Round to nearest
8690      01 Round to 0
8691      10 Round to +inf
8692      11 Round to -inf
8693 
8694   FLT_ROUNDS, on the other hand, expects the following:
8695     -1 Undefined
8696      0 Round to 0
8697      1 Round to nearest
8698      2 Round to +inf
8699      3 Round to -inf
8700 
8701   To perform the conversion, we do:
8702     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8703   */
8704 
8705   MachineFunction &MF = DAG.getMachineFunction();
8706   EVT VT = Op.getValueType();
8707   EVT PtrVT = getPointerTy(MF.getDataLayout());
8708 
8709   // Save FP Control Word to register
8710   SDValue Chain = Op.getOperand(0);
8711   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8712   Chain = MFFS.getValue(1);
8713 
8714   SDValue CWD;
8715   if (isTypeLegal(MVT::i64)) {
8716     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8717                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8718   } else {
8719     // Save FP register to stack slot
8720     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8721     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8722     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8723 
8724     // Load FP Control Word from low 32 bits of stack slot.
8725     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8726            "Stack slot adjustment is valid only on big endian subtargets!");
8727     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8728     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8729     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8730     Chain = CWD.getValue(1);
8731   }
8732 
8733   // Transform as necessary
8734   SDValue CWD1 =
8735     DAG.getNode(ISD::AND, dl, MVT::i32,
8736                 CWD, DAG.getConstant(3, dl, MVT::i32));
8737   SDValue CWD2 =
8738     DAG.getNode(ISD::SRL, dl, MVT::i32,
8739                 DAG.getNode(ISD::AND, dl, MVT::i32,
8740                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8741                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8742                             DAG.getConstant(3, dl, MVT::i32)),
8743                 DAG.getConstant(1, dl, MVT::i32));
8744 
8745   SDValue RetVal =
8746     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8747 
8748   RetVal =
8749       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8750                   dl, VT, RetVal);
8751 
8752   return DAG.getMergeValues({RetVal, Chain}, dl);
8753 }
8754 
8755 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8756   EVT VT = Op.getValueType();
8757   unsigned BitWidth = VT.getSizeInBits();
8758   SDLoc dl(Op);
8759   assert(Op.getNumOperands() == 3 &&
8760          VT == Op.getOperand(1).getValueType() &&
8761          "Unexpected SHL!");
8762 
8763   // Expand into a bunch of logical ops.  Note that these ops
8764   // depend on the PPC behavior for oversized shift amounts.
8765   SDValue Lo = Op.getOperand(0);
8766   SDValue Hi = Op.getOperand(1);
8767   SDValue Amt = Op.getOperand(2);
8768   EVT AmtVT = Amt.getValueType();
8769 
8770   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8771                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8772   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8773   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8774   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8775   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8776                              DAG.getConstant(-BitWidth, dl, AmtVT));
8777   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8778   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8779   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8780   SDValue OutOps[] = { OutLo, OutHi };
8781   return DAG.getMergeValues(OutOps, dl);
8782 }
8783 
8784 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8785   EVT VT = Op.getValueType();
8786   SDLoc dl(Op);
8787   unsigned BitWidth = VT.getSizeInBits();
8788   assert(Op.getNumOperands() == 3 &&
8789          VT == Op.getOperand(1).getValueType() &&
8790          "Unexpected SRL!");
8791 
8792   // Expand into a bunch of logical ops.  Note that these ops
8793   // depend on the PPC behavior for oversized shift amounts.
8794   SDValue Lo = Op.getOperand(0);
8795   SDValue Hi = Op.getOperand(1);
8796   SDValue Amt = Op.getOperand(2);
8797   EVT AmtVT = Amt.getValueType();
8798 
8799   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8800                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8801   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8802   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8803   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8804   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8805                              DAG.getConstant(-BitWidth, dl, AmtVT));
8806   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8807   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8808   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8809   SDValue OutOps[] = { OutLo, OutHi };
8810   return DAG.getMergeValues(OutOps, dl);
8811 }
8812 
8813 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8814   SDLoc dl(Op);
8815   EVT VT = Op.getValueType();
8816   unsigned BitWidth = VT.getSizeInBits();
8817   assert(Op.getNumOperands() == 3 &&
8818          VT == Op.getOperand(1).getValueType() &&
8819          "Unexpected SRA!");
8820 
8821   // Expand into a bunch of logical ops, followed by a select_cc.
8822   SDValue Lo = Op.getOperand(0);
8823   SDValue Hi = Op.getOperand(1);
8824   SDValue Amt = Op.getOperand(2);
8825   EVT AmtVT = Amt.getValueType();
8826 
8827   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8828                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8829   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8830   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8831   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8832   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8833                              DAG.getConstant(-BitWidth, dl, AmtVT));
8834   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8835   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8836   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8837                                   Tmp4, Tmp6, ISD::SETLE);
8838   SDValue OutOps[] = { OutLo, OutHi };
8839   return DAG.getMergeValues(OutOps, dl);
8840 }
8841 
8842 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8843                                             SelectionDAG &DAG) const {
8844   SDLoc dl(Op);
8845   EVT VT = Op.getValueType();
8846   unsigned BitWidth = VT.getSizeInBits();
8847 
8848   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8849   SDValue X = Op.getOperand(0);
8850   SDValue Y = Op.getOperand(1);
8851   SDValue Z = Op.getOperand(2);
8852   EVT AmtVT = Z.getValueType();
8853 
8854   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8855   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8856   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8857   // on PowerPC shift by BW being well defined.
8858   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8859                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8860   SDValue SubZ =
8861       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8862   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8863   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8864   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8865 }
8866 
8867 //===----------------------------------------------------------------------===//
8868 // Vector related lowering.
8869 //
8870 
8871 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8872 /// element size of SplatSize. Cast the result to VT.
8873 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8874                                       SelectionDAG &DAG, const SDLoc &dl) {
8875   static const MVT VTys[] = { // canonical VT to use for each size.
8876     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8877   };
8878 
8879   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8880 
8881   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8882   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8883     SplatSize = 1;
8884     Val = 0xFF;
8885   }
8886 
8887   EVT CanonicalVT = VTys[SplatSize-1];
8888 
8889   // Build a canonical splat for this value.
8890   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8891 }
8892 
8893 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8894 /// specified intrinsic ID.
8895 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8896                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8897   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8898   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8899                      DAG.getConstant(IID, dl, MVT::i32), Op);
8900 }
8901 
8902 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8903 /// specified intrinsic ID.
8904 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8905                                 SelectionDAG &DAG, const SDLoc &dl,
8906                                 EVT DestVT = MVT::Other) {
8907   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8908   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8909                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8910 }
8911 
8912 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8913 /// specified intrinsic ID.
8914 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8915                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8916                                 EVT DestVT = MVT::Other) {
8917   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8918   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8919                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8920 }
8921 
8922 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8923 /// amount.  The result has the specified value type.
8924 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8925                            SelectionDAG &DAG, const SDLoc &dl) {
8926   // Force LHS/RHS to be the right type.
8927   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8928   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8929 
8930   int Ops[16];
8931   for (unsigned i = 0; i != 16; ++i)
8932     Ops[i] = i + Amt;
8933   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8934   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8935 }
8936 
8937 /// Do we have an efficient pattern in a .td file for this node?
8938 ///
8939 /// \param V - pointer to the BuildVectorSDNode being matched
8940 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8941 ///
8942 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8943 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8944 /// the opposite is true (expansion is beneficial) are:
8945 /// - The node builds a vector out of integers that are not 32 or 64-bits
8946 /// - The node builds a vector out of constants
8947 /// - The node is a "load-and-splat"
8948 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8949 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8950                                             bool HasDirectMove,
8951                                             bool HasP8Vector) {
8952   EVT VecVT = V->getValueType(0);
8953   bool RightType = VecVT == MVT::v2f64 ||
8954     (HasP8Vector && VecVT == MVT::v4f32) ||
8955     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8956   if (!RightType)
8957     return false;
8958 
8959   bool IsSplat = true;
8960   bool IsLoad = false;
8961   SDValue Op0 = V->getOperand(0);
8962 
8963   // This function is called in a block that confirms the node is not a constant
8964   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8965   // different constants.
8966   if (V->isConstant())
8967     return false;
8968   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8969     if (V->getOperand(i).isUndef())
8970       return false;
8971     // We want to expand nodes that represent load-and-splat even if the
8972     // loaded value is a floating point truncation or conversion to int.
8973     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8974         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8975          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8976         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8977          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8978         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8979          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8980       IsLoad = true;
8981     // If the operands are different or the input is not a load and has more
8982     // uses than just this BV node, then it isn't a splat.
8983     if (V->getOperand(i) != Op0 ||
8984         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8985       IsSplat = false;
8986   }
8987   return !(IsSplat && IsLoad);
8988 }
8989 
8990 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8991 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8992 
8993   SDLoc dl(Op);
8994   SDValue Op0 = Op->getOperand(0);
8995 
8996   if ((Op.getValueType() != MVT::f128) ||
8997       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8998       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8999       (Op0.getOperand(1).getValueType() != MVT::i64))
9000     return SDValue();
9001 
9002   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9003                      Op0.getOperand(1));
9004 }
9005 
9006 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9007   const SDValue *InputLoad = &Op;
9008   if (InputLoad->getOpcode() == ISD::BITCAST)
9009     InputLoad = &InputLoad->getOperand(0);
9010   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9011       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9012     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9013     InputLoad = &InputLoad->getOperand(0);
9014   }
9015   if (InputLoad->getOpcode() != ISD::LOAD)
9016     return nullptr;
9017   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9018   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9019 }
9020 
9021 // Convert the argument APFloat to a single precision APFloat if there is no
9022 // loss in information during the conversion to single precision APFloat and the
9023 // resulting number is not a denormal number. Return true if successful.
9024 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9025   APFloat APFloatToConvert = ArgAPFloat;
9026   bool LosesInfo = true;
9027   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9028                            &LosesInfo);
9029   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9030   if (Success)
9031     ArgAPFloat = APFloatToConvert;
9032   return Success;
9033 }
9034 
9035 // Bitcast the argument APInt to a double and convert it to a single precision
9036 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9037 // argument if there is no loss in information during the conversion from
9038 // double to single precision APFloat and the resulting number is not a denormal
9039 // number. Return true if successful.
9040 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9041   double DpValue = ArgAPInt.bitsToDouble();
9042   APFloat APFloatDp(DpValue);
9043   bool Success = convertToNonDenormSingle(APFloatDp);
9044   if (Success)
9045     ArgAPInt = APFloatDp.bitcastToAPInt();
9046   return Success;
9047 }
9048 
9049 // Nondestructive check for convertTonNonDenormSingle.
9050 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9051   // Only convert if it loses info, since XXSPLTIDP should
9052   // handle the other case.
9053   APFloat APFloatToConvert = ArgAPFloat;
9054   bool LosesInfo = true;
9055   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9056                            &LosesInfo);
9057 
9058   return (!LosesInfo && !APFloatToConvert.isDenormal());
9059 }
9060 
9061 // If this is a case we can't handle, return null and let the default
9062 // expansion code take care of it.  If we CAN select this case, and if it
9063 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9064 // this case more efficiently than a constant pool load, lower it to the
9065 // sequence of ops that should be used.
9066 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9067                                              SelectionDAG &DAG) const {
9068   SDLoc dl(Op);
9069   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9070   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9071 
9072   // Check if this is a splat of a constant value.
9073   APInt APSplatBits, APSplatUndef;
9074   unsigned SplatBitSize;
9075   bool HasAnyUndefs;
9076   bool BVNIsConstantSplat =
9077       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9078                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9079 
9080   // If it is a splat of a double, check if we can shrink it to a 32 bit
9081   // non-denormal float which when converted back to double gives us the same
9082   // double. This is to exploit the XXSPLTIDP instruction.
9083   // If we lose precision, we use XXSPLTI32DX.
9084   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9085       Subtarget.hasPrefixInstrs()) {
9086     // Check the type first to short-circuit so we don't modify APSplatBits if
9087     // this block isn't executed.
9088     if ((Op->getValueType(0) == MVT::v2f64) &&
9089         convertToNonDenormSingle(APSplatBits)) {
9090       SDValue SplatNode = DAG.getNode(
9091           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9092           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9093       return DAG.getBitcast(Op.getValueType(), SplatNode);
9094     } else {
9095       // We may lose precision, so we have to use XXSPLTI32DX.
9096 
9097       uint32_t Hi =
9098           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9099       uint32_t Lo =
9100           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9101       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9102 
9103       if (!Hi || !Lo)
9104         // If either load is 0, then we should generate XXLXOR to set to 0.
9105         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9106 
9107       if (Hi)
9108         SplatNode = DAG.getNode(
9109             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9110             DAG.getTargetConstant(0, dl, MVT::i32),
9111             DAG.getTargetConstant(Hi, dl, MVT::i32));
9112 
9113       if (Lo)
9114         SplatNode =
9115             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9116                         DAG.getTargetConstant(1, dl, MVT::i32),
9117                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9118 
9119       return DAG.getBitcast(Op.getValueType(), SplatNode);
9120     }
9121   }
9122 
9123   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9124 
9125     bool IsPermutedLoad = false;
9126     const SDValue *InputLoad =
9127         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9128     // Handle load-and-splat patterns as we have instructions that will do this
9129     // in one go.
9130     if (InputLoad && DAG.isSplatValue(Op, true)) {
9131       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9132 
9133       // We have handling for 4 and 8 byte elements.
9134       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9135 
9136       // Checking for a single use of this load, we have to check for vector
9137       // width (128 bits) / ElementSize uses (since each operand of the
9138       // BUILD_VECTOR is a separate use of the value.
9139       unsigned NumUsesOfInputLD = 128 / ElementSize;
9140       for (SDValue BVInOp : Op->ops())
9141         if (BVInOp.isUndef())
9142           NumUsesOfInputLD--;
9143       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9144       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9145           ((Subtarget.hasVSX() && ElementSize == 64) ||
9146            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9147         SDValue Ops[] = {
9148           LD->getChain(),    // Chain
9149           LD->getBasePtr(),  // Ptr
9150           DAG.getValueType(Op.getValueType()) // VT
9151         };
9152         SDValue LdSplt = DAG.getMemIntrinsicNode(
9153             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
9154             Ops, LD->getMemoryVT(), LD->getMemOperand());
9155         // Replace all uses of the output chain of the original load with the
9156         // output chain of the new load.
9157         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9158                                       LdSplt.getValue(1));
9159         return LdSplt;
9160       }
9161     }
9162 
9163     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9164     // 32-bits can be lowered to VSX instructions under certain conditions.
9165     // Without VSX, there is no pattern more efficient than expanding the node.
9166     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9167         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9168                                         Subtarget.hasP8Vector()))
9169       return Op;
9170     return SDValue();
9171   }
9172 
9173   uint64_t SplatBits = APSplatBits.getZExtValue();
9174   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9175   unsigned SplatSize = SplatBitSize / 8;
9176 
9177   // First, handle single instruction cases.
9178 
9179   // All zeros?
9180   if (SplatBits == 0) {
9181     // Canonicalize all zero vectors to be v4i32.
9182     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9183       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9184       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9185     }
9186     return Op;
9187   }
9188 
9189   // We have XXSPLTIW for constant splats four bytes wide.
9190   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9191   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9192   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9193   // turned into a 4-byte splat of 0xABABABAB.
9194   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9195     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9196                                   Op.getValueType(), DAG, dl);
9197 
9198   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9199     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9200                                   dl);
9201 
9202   // We have XXSPLTIB for constant splats one byte wide.
9203   if (Subtarget.hasP9Vector() && SplatSize == 1)
9204     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9205                                   dl);
9206 
9207   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9208   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9209                     (32-SplatBitSize));
9210   if (SextVal >= -16 && SextVal <= 15)
9211     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9212                                   dl);
9213 
9214   // Two instruction sequences.
9215 
9216   // If this value is in the range [-32,30] and is even, use:
9217   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9218   // If this value is in the range [17,31] and is odd, use:
9219   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9220   // If this value is in the range [-31,-17] and is odd, use:
9221   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9222   // Note the last two are three-instruction sequences.
9223   if (SextVal >= -32 && SextVal <= 31) {
9224     // To avoid having these optimizations undone by constant folding,
9225     // we convert to a pseudo that will be expanded later into one of
9226     // the above forms.
9227     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9228     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9229               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9230     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9231     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9232     if (VT == Op.getValueType())
9233       return RetVal;
9234     else
9235       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9236   }
9237 
9238   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9239   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9240   // for fneg/fabs.
9241   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9242     // Make -1 and vspltisw -1:
9243     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9244 
9245     // Make the VSLW intrinsic, computing 0x8000_0000.
9246     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9247                                    OnesV, DAG, dl);
9248 
9249     // xor by OnesV to invert it.
9250     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9251     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9252   }
9253 
9254   // Check to see if this is a wide variety of vsplti*, binop self cases.
9255   static const signed char SplatCsts[] = {
9256     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9257     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9258   };
9259 
9260   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9261     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9262     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9263     int i = SplatCsts[idx];
9264 
9265     // Figure out what shift amount will be used by altivec if shifted by i in
9266     // this splat size.
9267     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9268 
9269     // vsplti + shl self.
9270     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9271       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9272       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9273         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9274         Intrinsic::ppc_altivec_vslw
9275       };
9276       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9277       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9278     }
9279 
9280     // vsplti + srl self.
9281     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9282       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9283       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9284         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9285         Intrinsic::ppc_altivec_vsrw
9286       };
9287       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9288       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9289     }
9290 
9291     // vsplti + rol self.
9292     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9293                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9294       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9295       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9296         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9297         Intrinsic::ppc_altivec_vrlw
9298       };
9299       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9300       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9301     }
9302 
9303     // t = vsplti c, result = vsldoi t, t, 1
9304     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9305       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9306       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9307       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9308     }
9309     // t = vsplti c, result = vsldoi t, t, 2
9310     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9311       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9312       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9313       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9314     }
9315     // t = vsplti c, result = vsldoi t, t, 3
9316     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9317       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9318       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9319       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9320     }
9321   }
9322 
9323   return SDValue();
9324 }
9325 
9326 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9327 /// the specified operations to build the shuffle.
9328 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9329                                       SDValue RHS, SelectionDAG &DAG,
9330                                       const SDLoc &dl) {
9331   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9332   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9333   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9334 
9335   enum {
9336     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9337     OP_VMRGHW,
9338     OP_VMRGLW,
9339     OP_VSPLTISW0,
9340     OP_VSPLTISW1,
9341     OP_VSPLTISW2,
9342     OP_VSPLTISW3,
9343     OP_VSLDOI4,
9344     OP_VSLDOI8,
9345     OP_VSLDOI12
9346   };
9347 
9348   if (OpNum == OP_COPY) {
9349     if (LHSID == (1*9+2)*9+3) return LHS;
9350     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9351     return RHS;
9352   }
9353 
9354   SDValue OpLHS, OpRHS;
9355   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9356   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9357 
9358   int ShufIdxs[16];
9359   switch (OpNum) {
9360   default: llvm_unreachable("Unknown i32 permute!");
9361   case OP_VMRGHW:
9362     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9363     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9364     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9365     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9366     break;
9367   case OP_VMRGLW:
9368     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9369     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9370     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9371     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9372     break;
9373   case OP_VSPLTISW0:
9374     for (unsigned i = 0; i != 16; ++i)
9375       ShufIdxs[i] = (i&3)+0;
9376     break;
9377   case OP_VSPLTISW1:
9378     for (unsigned i = 0; i != 16; ++i)
9379       ShufIdxs[i] = (i&3)+4;
9380     break;
9381   case OP_VSPLTISW2:
9382     for (unsigned i = 0; i != 16; ++i)
9383       ShufIdxs[i] = (i&3)+8;
9384     break;
9385   case OP_VSPLTISW3:
9386     for (unsigned i = 0; i != 16; ++i)
9387       ShufIdxs[i] = (i&3)+12;
9388     break;
9389   case OP_VSLDOI4:
9390     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9391   case OP_VSLDOI8:
9392     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9393   case OP_VSLDOI12:
9394     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9395   }
9396   EVT VT = OpLHS.getValueType();
9397   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9398   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9399   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9400   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9401 }
9402 
9403 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9404 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9405 /// SDValue.
9406 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9407                                            SelectionDAG &DAG) const {
9408   const unsigned BytesInVector = 16;
9409   bool IsLE = Subtarget.isLittleEndian();
9410   SDLoc dl(N);
9411   SDValue V1 = N->getOperand(0);
9412   SDValue V2 = N->getOperand(1);
9413   unsigned ShiftElts = 0, InsertAtByte = 0;
9414   bool Swap = false;
9415 
9416   // Shifts required to get the byte we want at element 7.
9417   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9418                                    0, 15, 14, 13, 12, 11, 10, 9};
9419   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9420                                 1, 2,  3,  4,  5,  6,  7,  8};
9421 
9422   ArrayRef<int> Mask = N->getMask();
9423   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9424 
9425   // For each mask element, find out if we're just inserting something
9426   // from V2 into V1 or vice versa.
9427   // Possible permutations inserting an element from V2 into V1:
9428   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9429   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9430   //   ...
9431   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9432   // Inserting from V1 into V2 will be similar, except mask range will be
9433   // [16,31].
9434 
9435   bool FoundCandidate = false;
9436   // If both vector operands for the shuffle are the same vector, the mask
9437   // will contain only elements from the first one and the second one will be
9438   // undef.
9439   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9440   // Go through the mask of half-words to find an element that's being moved
9441   // from one vector to the other.
9442   for (unsigned i = 0; i < BytesInVector; ++i) {
9443     unsigned CurrentElement = Mask[i];
9444     // If 2nd operand is undefined, we should only look for element 7 in the
9445     // Mask.
9446     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9447       continue;
9448 
9449     bool OtherElementsInOrder = true;
9450     // Examine the other elements in the Mask to see if they're in original
9451     // order.
9452     for (unsigned j = 0; j < BytesInVector; ++j) {
9453       if (j == i)
9454         continue;
9455       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9456       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9457       // in which we always assume we're always picking from the 1st operand.
9458       int MaskOffset =
9459           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9460       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9461         OtherElementsInOrder = false;
9462         break;
9463       }
9464     }
9465     // If other elements are in original order, we record the number of shifts
9466     // we need to get the element we want into element 7. Also record which byte
9467     // in the vector we should insert into.
9468     if (OtherElementsInOrder) {
9469       // If 2nd operand is undefined, we assume no shifts and no swapping.
9470       if (V2.isUndef()) {
9471         ShiftElts = 0;
9472         Swap = false;
9473       } else {
9474         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9475         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9476                          : BigEndianShifts[CurrentElement & 0xF];
9477         Swap = CurrentElement < BytesInVector;
9478       }
9479       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9480       FoundCandidate = true;
9481       break;
9482     }
9483   }
9484 
9485   if (!FoundCandidate)
9486     return SDValue();
9487 
9488   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9489   // optionally with VECSHL if shift is required.
9490   if (Swap)
9491     std::swap(V1, V2);
9492   if (V2.isUndef())
9493     V2 = V1;
9494   if (ShiftElts) {
9495     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9496                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9497     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9498                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9499   }
9500   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9501                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9502 }
9503 
9504 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9505 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9506 /// SDValue.
9507 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9508                                            SelectionDAG &DAG) const {
9509   const unsigned NumHalfWords = 8;
9510   const unsigned BytesInVector = NumHalfWords * 2;
9511   // Check that the shuffle is on half-words.
9512   if (!isNByteElemShuffleMask(N, 2, 1))
9513     return SDValue();
9514 
9515   bool IsLE = Subtarget.isLittleEndian();
9516   SDLoc dl(N);
9517   SDValue V1 = N->getOperand(0);
9518   SDValue V2 = N->getOperand(1);
9519   unsigned ShiftElts = 0, InsertAtByte = 0;
9520   bool Swap = false;
9521 
9522   // Shifts required to get the half-word we want at element 3.
9523   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9524   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9525 
9526   uint32_t Mask = 0;
9527   uint32_t OriginalOrderLow = 0x1234567;
9528   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9529   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9530   // 32-bit space, only need 4-bit nibbles per element.
9531   for (unsigned i = 0; i < NumHalfWords; ++i) {
9532     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9533     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9534   }
9535 
9536   // For each mask element, find out if we're just inserting something
9537   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9538   // from V2 into V1:
9539   //   X, 1, 2, 3, 4, 5, 6, 7
9540   //   0, X, 2, 3, 4, 5, 6, 7
9541   //   0, 1, X, 3, 4, 5, 6, 7
9542   //   0, 1, 2, X, 4, 5, 6, 7
9543   //   0, 1, 2, 3, X, 5, 6, 7
9544   //   0, 1, 2, 3, 4, X, 6, 7
9545   //   0, 1, 2, 3, 4, 5, X, 7
9546   //   0, 1, 2, 3, 4, 5, 6, X
9547   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9548 
9549   bool FoundCandidate = false;
9550   // Go through the mask of half-words to find an element that's being moved
9551   // from one vector to the other.
9552   for (unsigned i = 0; i < NumHalfWords; ++i) {
9553     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9554     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9555     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9556     uint32_t TargetOrder = 0x0;
9557 
9558     // If both vector operands for the shuffle are the same vector, the mask
9559     // will contain only elements from the first one and the second one will be
9560     // undef.
9561     if (V2.isUndef()) {
9562       ShiftElts = 0;
9563       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9564       TargetOrder = OriginalOrderLow;
9565       Swap = false;
9566       // Skip if not the correct element or mask of other elements don't equal
9567       // to our expected order.
9568       if (MaskOneElt == VINSERTHSrcElem &&
9569           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9570         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9571         FoundCandidate = true;
9572         break;
9573       }
9574     } else { // If both operands are defined.
9575       // Target order is [8,15] if the current mask is between [0,7].
9576       TargetOrder =
9577           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9578       // Skip if mask of other elements don't equal our expected order.
9579       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9580         // We only need the last 3 bits for the number of shifts.
9581         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9582                          : BigEndianShifts[MaskOneElt & 0x7];
9583         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9584         Swap = MaskOneElt < NumHalfWords;
9585         FoundCandidate = true;
9586         break;
9587       }
9588     }
9589   }
9590 
9591   if (!FoundCandidate)
9592     return SDValue();
9593 
9594   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9595   // optionally with VECSHL if shift is required.
9596   if (Swap)
9597     std::swap(V1, V2);
9598   if (V2.isUndef())
9599     V2 = V1;
9600   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9601   if (ShiftElts) {
9602     // Double ShiftElts because we're left shifting on v16i8 type.
9603     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9604                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9605     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9606     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9607                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9608     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9609   }
9610   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9611   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9612                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9613   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9614 }
9615 
9616 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9617 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9618 /// return the default SDValue.
9619 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9620                                               SelectionDAG &DAG) const {
9621   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9622   // to v16i8. Peek through the bitcasts to get the actual operands.
9623   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9624   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9625 
9626   auto ShuffleMask = SVN->getMask();
9627   SDValue VecShuffle(SVN, 0);
9628   SDLoc DL(SVN);
9629 
9630   // Check that we have a four byte shuffle.
9631   if (!isNByteElemShuffleMask(SVN, 4, 1))
9632     return SDValue();
9633 
9634   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9635   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9636     std::swap(LHS, RHS);
9637     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9638     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9639   }
9640 
9641   // Ensure that the RHS is a vector of constants.
9642   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9643   if (!BVN)
9644     return SDValue();
9645 
9646   // Check if RHS is a splat of 4-bytes (or smaller).
9647   APInt APSplatValue, APSplatUndef;
9648   unsigned SplatBitSize;
9649   bool HasAnyUndefs;
9650   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9651                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9652       SplatBitSize > 32)
9653     return SDValue();
9654 
9655   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9656   // The instruction splats a constant C into two words of the source vector
9657   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9658   // Thus we check that the shuffle mask is the equivalent  of
9659   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9660   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9661   // within each word are consecutive, so we only need to check the first byte.
9662   SDValue Index;
9663   bool IsLE = Subtarget.isLittleEndian();
9664   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9665       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9666        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9667     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9668   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9669            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9670             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9671     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9672   else
9673     return SDValue();
9674 
9675   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9676   // for XXSPLTI32DX.
9677   unsigned SplatVal = APSplatValue.getZExtValue();
9678   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9679     SplatVal |= (SplatVal << SplatBitSize);
9680 
9681   SDValue SplatNode = DAG.getNode(
9682       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9683       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9684   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9685 }
9686 
9687 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9688 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9689 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9690 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9691 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9692   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9693   assert(Op.getValueType() == MVT::v1i128 &&
9694          "Only set v1i128 as custom, other type shouldn't reach here!");
9695   SDLoc dl(Op);
9696   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9697   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9698   unsigned SHLAmt = N1.getConstantOperandVal(0);
9699   if (SHLAmt % 8 == 0) {
9700     SmallVector<int, 16> Mask(16, 0);
9701     std::iota(Mask.begin(), Mask.end(), 0);
9702     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9703     if (SDValue Shuffle =
9704             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9705                                  DAG.getUNDEF(MVT::v16i8), Mask))
9706       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9707   }
9708   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9709   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9710                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9711   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9712                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9713   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9714   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9715 }
9716 
9717 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9718 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9719 /// return the code it can be lowered into.  Worst case, it can always be
9720 /// lowered into a vperm.
9721 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9722                                                SelectionDAG &DAG) const {
9723   SDLoc dl(Op);
9724   SDValue V1 = Op.getOperand(0);
9725   SDValue V2 = Op.getOperand(1);
9726   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9727 
9728   // Any nodes that were combined in the target-independent combiner prior
9729   // to vector legalization will not be sent to the target combine. Try to
9730   // combine it here.
9731   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9732     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9733       return NewShuffle;
9734     Op = NewShuffle;
9735     SVOp = cast<ShuffleVectorSDNode>(Op);
9736     V1 = Op.getOperand(0);
9737     V2 = Op.getOperand(1);
9738   }
9739   EVT VT = Op.getValueType();
9740   bool isLittleEndian = Subtarget.isLittleEndian();
9741 
9742   unsigned ShiftElts, InsertAtByte;
9743   bool Swap = false;
9744 
9745   // If this is a load-and-splat, we can do that with a single instruction
9746   // in some cases. However if the load has multiple uses, we don't want to
9747   // combine it because that will just produce multiple loads.
9748   bool IsPermutedLoad = false;
9749   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9750   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9751       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9752       InputLoad->hasOneUse()) {
9753     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9754     int SplatIdx =
9755       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9756 
9757     // The splat index for permuted loads will be in the left half of the vector
9758     // which is strictly wider than the loaded value by 8 bytes. So we need to
9759     // adjust the splat index to point to the correct address in memory.
9760     if (IsPermutedLoad) {
9761       assert((isLittleEndian || IsFourByte) &&
9762              "Unexpected size for permuted load on big endian target");
9763       SplatIdx += IsFourByte ? 2 : 1;
9764       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9765              "Splat of a value outside of the loaded memory");
9766     }
9767 
9768     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9769     // For 4-byte load-and-splat, we need Power9.
9770     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9771       uint64_t Offset = 0;
9772       if (IsFourByte)
9773         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9774       else
9775         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9776 
9777       // If the width of the load is the same as the width of the splat,
9778       // loading with an offset would load the wrong memory.
9779       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9780         Offset = 0;
9781 
9782       SDValue BasePtr = LD->getBasePtr();
9783       if (Offset != 0)
9784         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9785                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9786       SDValue Ops[] = {
9787         LD->getChain(),    // Chain
9788         BasePtr,           // BasePtr
9789         DAG.getValueType(Op.getValueType()) // VT
9790       };
9791       SDVTList VTL =
9792         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9793       SDValue LdSplt =
9794         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9795                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9796       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9797       if (LdSplt.getValueType() != SVOp->getValueType(0))
9798         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9799       return LdSplt;
9800     }
9801   }
9802   if (Subtarget.hasP9Vector() &&
9803       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9804                            isLittleEndian)) {
9805     if (Swap)
9806       std::swap(V1, V2);
9807     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9808     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9809     if (ShiftElts) {
9810       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9811                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9812       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9813                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9814       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9815     }
9816     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9817                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9818     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9819   }
9820 
9821   if (Subtarget.hasPrefixInstrs()) {
9822     SDValue SplatInsertNode;
9823     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9824       return SplatInsertNode;
9825   }
9826 
9827   if (Subtarget.hasP9Altivec()) {
9828     SDValue NewISDNode;
9829     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9830       return NewISDNode;
9831 
9832     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9833       return NewISDNode;
9834   }
9835 
9836   if (Subtarget.hasVSX() &&
9837       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9838     if (Swap)
9839       std::swap(V1, V2);
9840     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9841     SDValue Conv2 =
9842         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9843 
9844     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9845                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9846     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9847   }
9848 
9849   if (Subtarget.hasVSX() &&
9850     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9851     if (Swap)
9852       std::swap(V1, V2);
9853     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9854     SDValue Conv2 =
9855         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9856 
9857     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9858                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9859     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9860   }
9861 
9862   if (Subtarget.hasP9Vector()) {
9863      if (PPC::isXXBRHShuffleMask(SVOp)) {
9864       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9865       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9866       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9867     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9868       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9869       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9870       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9871     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9872       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9873       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9874       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9875     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9876       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9877       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9878       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9879     }
9880   }
9881 
9882   if (Subtarget.hasVSX()) {
9883     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9884       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9885 
9886       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9887       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9888                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9889       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9890     }
9891 
9892     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9893     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9894       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9895       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9896       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9897     }
9898   }
9899 
9900   // Cases that are handled by instructions that take permute immediates
9901   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9902   // selected by the instruction selector.
9903   if (V2.isUndef()) {
9904     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9905         PPC::isSplatShuffleMask(SVOp, 2) ||
9906         PPC::isSplatShuffleMask(SVOp, 4) ||
9907         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9908         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9909         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9910         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9911         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9912         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9913         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9914         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9915         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9916         (Subtarget.hasP8Altivec() && (
9917          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9918          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9919          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9920       return Op;
9921     }
9922   }
9923 
9924   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9925   // and produce a fixed permutation.  If any of these match, do not lower to
9926   // VPERM.
9927   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9928   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9929       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9930       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9931       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9932       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9933       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9934       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9935       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9936       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9937       (Subtarget.hasP8Altivec() && (
9938        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9939        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9940        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9941     return Op;
9942 
9943   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9944   // perfect shuffle table to emit an optimal matching sequence.
9945   ArrayRef<int> PermMask = SVOp->getMask();
9946 
9947   unsigned PFIndexes[4];
9948   bool isFourElementShuffle = true;
9949   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9950     unsigned EltNo = 8;   // Start out undef.
9951     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9952       if (PermMask[i*4+j] < 0)
9953         continue;   // Undef, ignore it.
9954 
9955       unsigned ByteSource = PermMask[i*4+j];
9956       if ((ByteSource & 3) != j) {
9957         isFourElementShuffle = false;
9958         break;
9959       }
9960 
9961       if (EltNo == 8) {
9962         EltNo = ByteSource/4;
9963       } else if (EltNo != ByteSource/4) {
9964         isFourElementShuffle = false;
9965         break;
9966       }
9967     }
9968     PFIndexes[i] = EltNo;
9969   }
9970 
9971   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9972   // perfect shuffle vector to determine if it is cost effective to do this as
9973   // discrete instructions, or whether we should use a vperm.
9974   // For now, we skip this for little endian until such time as we have a
9975   // little-endian perfect shuffle table.
9976   if (isFourElementShuffle && !isLittleEndian) {
9977     // Compute the index in the perfect shuffle table.
9978     unsigned PFTableIndex =
9979       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9980 
9981     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9982     unsigned Cost  = (PFEntry >> 30);
9983 
9984     // Determining when to avoid vperm is tricky.  Many things affect the cost
9985     // of vperm, particularly how many times the perm mask needs to be computed.
9986     // For example, if the perm mask can be hoisted out of a loop or is already
9987     // used (perhaps because there are multiple permutes with the same shuffle
9988     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9989     // the loop requires an extra register.
9990     //
9991     // As a compromise, we only emit discrete instructions if the shuffle can be
9992     // generated in 3 or fewer operations.  When we have loop information
9993     // available, if this block is within a loop, we should avoid using vperm
9994     // for 3-operation perms and use a constant pool load instead.
9995     if (Cost < 3)
9996       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9997   }
9998 
9999   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10000   // vector that will get spilled to the constant pool.
10001   if (V2.isUndef()) V2 = V1;
10002 
10003   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10004   // that it is in input element units, not in bytes.  Convert now.
10005 
10006   // For little endian, the order of the input vectors is reversed, and
10007   // the permutation mask is complemented with respect to 31.  This is
10008   // necessary to produce proper semantics with the big-endian-biased vperm
10009   // instruction.
10010   EVT EltVT = V1.getValueType().getVectorElementType();
10011   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10012 
10013   SmallVector<SDValue, 16> ResultMask;
10014   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10015     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10016 
10017     for (unsigned j = 0; j != BytesPerElement; ++j)
10018       if (isLittleEndian)
10019         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10020                                              dl, MVT::i32));
10021       else
10022         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10023                                              MVT::i32));
10024   }
10025 
10026   ShufflesHandledWithVPERM++;
10027   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10028   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10029   LLVM_DEBUG(SVOp->dump());
10030   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10031   LLVM_DEBUG(VPermMask.dump());
10032 
10033   if (isLittleEndian)
10034     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10035                        V2, V1, VPermMask);
10036   else
10037     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10038                        V1, V2, VPermMask);
10039 }
10040 
10041 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10042 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10043 /// information about the intrinsic.
10044 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10045                                  bool &isDot, const PPCSubtarget &Subtarget) {
10046   unsigned IntrinsicID =
10047       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10048   CompareOpc = -1;
10049   isDot = false;
10050   switch (IntrinsicID) {
10051   default:
10052     return false;
10053   // Comparison predicates.
10054   case Intrinsic::ppc_altivec_vcmpbfp_p:
10055     CompareOpc = 966;
10056     isDot = true;
10057     break;
10058   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10059     CompareOpc = 198;
10060     isDot = true;
10061     break;
10062   case Intrinsic::ppc_altivec_vcmpequb_p:
10063     CompareOpc = 6;
10064     isDot = true;
10065     break;
10066   case Intrinsic::ppc_altivec_vcmpequh_p:
10067     CompareOpc = 70;
10068     isDot = true;
10069     break;
10070   case Intrinsic::ppc_altivec_vcmpequw_p:
10071     CompareOpc = 134;
10072     isDot = true;
10073     break;
10074   case Intrinsic::ppc_altivec_vcmpequd_p:
10075     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10076       CompareOpc = 199;
10077       isDot = true;
10078     } else
10079       return false;
10080     break;
10081   case Intrinsic::ppc_altivec_vcmpneb_p:
10082   case Intrinsic::ppc_altivec_vcmpneh_p:
10083   case Intrinsic::ppc_altivec_vcmpnew_p:
10084   case Intrinsic::ppc_altivec_vcmpnezb_p:
10085   case Intrinsic::ppc_altivec_vcmpnezh_p:
10086   case Intrinsic::ppc_altivec_vcmpnezw_p:
10087     if (Subtarget.hasP9Altivec()) {
10088       switch (IntrinsicID) {
10089       default:
10090         llvm_unreachable("Unknown comparison intrinsic.");
10091       case Intrinsic::ppc_altivec_vcmpneb_p:
10092         CompareOpc = 7;
10093         break;
10094       case Intrinsic::ppc_altivec_vcmpneh_p:
10095         CompareOpc = 71;
10096         break;
10097       case Intrinsic::ppc_altivec_vcmpnew_p:
10098         CompareOpc = 135;
10099         break;
10100       case Intrinsic::ppc_altivec_vcmpnezb_p:
10101         CompareOpc = 263;
10102         break;
10103       case Intrinsic::ppc_altivec_vcmpnezh_p:
10104         CompareOpc = 327;
10105         break;
10106       case Intrinsic::ppc_altivec_vcmpnezw_p:
10107         CompareOpc = 391;
10108         break;
10109       }
10110       isDot = true;
10111     } else
10112       return false;
10113     break;
10114   case Intrinsic::ppc_altivec_vcmpgefp_p:
10115     CompareOpc = 454;
10116     isDot = true;
10117     break;
10118   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10119     CompareOpc = 710;
10120     isDot = true;
10121     break;
10122   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10123     CompareOpc = 774;
10124     isDot = true;
10125     break;
10126   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10127     CompareOpc = 838;
10128     isDot = true;
10129     break;
10130   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10131     CompareOpc = 902;
10132     isDot = true;
10133     break;
10134   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10135     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10136       CompareOpc = 967;
10137       isDot = true;
10138     } else
10139       return false;
10140     break;
10141   case Intrinsic::ppc_altivec_vcmpgtub_p:
10142     CompareOpc = 518;
10143     isDot = true;
10144     break;
10145   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10146     CompareOpc = 582;
10147     isDot = true;
10148     break;
10149   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10150     CompareOpc = 646;
10151     isDot = true;
10152     break;
10153   case Intrinsic::ppc_altivec_vcmpgtud_p:
10154     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10155       CompareOpc = 711;
10156       isDot = true;
10157     } else
10158       return false;
10159     break;
10160 
10161   case Intrinsic::ppc_altivec_vcmpequq:
10162   case Intrinsic::ppc_altivec_vcmpgtsq:
10163   case Intrinsic::ppc_altivec_vcmpgtuq:
10164     if (!Subtarget.isISA3_1())
10165       return false;
10166     switch (IntrinsicID) {
10167     default:
10168       llvm_unreachable("Unknown comparison intrinsic.");
10169     case Intrinsic::ppc_altivec_vcmpequq:
10170       CompareOpc = 455;
10171       break;
10172     case Intrinsic::ppc_altivec_vcmpgtsq:
10173       CompareOpc = 903;
10174       break;
10175     case Intrinsic::ppc_altivec_vcmpgtuq:
10176       CompareOpc = 647;
10177       break;
10178     }
10179     break;
10180 
10181   // VSX predicate comparisons use the same infrastructure
10182   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10183   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10184   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10185   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10186   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10187   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10188     if (Subtarget.hasVSX()) {
10189       switch (IntrinsicID) {
10190       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10191         CompareOpc = 99;
10192         break;
10193       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10194         CompareOpc = 115;
10195         break;
10196       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10197         CompareOpc = 107;
10198         break;
10199       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10200         CompareOpc = 67;
10201         break;
10202       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10203         CompareOpc = 83;
10204         break;
10205       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10206         CompareOpc = 75;
10207         break;
10208       }
10209       isDot = true;
10210     } else
10211       return false;
10212     break;
10213 
10214   // Normal Comparisons.
10215   case Intrinsic::ppc_altivec_vcmpbfp:
10216     CompareOpc = 966;
10217     break;
10218   case Intrinsic::ppc_altivec_vcmpeqfp:
10219     CompareOpc = 198;
10220     break;
10221   case Intrinsic::ppc_altivec_vcmpequb:
10222     CompareOpc = 6;
10223     break;
10224   case Intrinsic::ppc_altivec_vcmpequh:
10225     CompareOpc = 70;
10226     break;
10227   case Intrinsic::ppc_altivec_vcmpequw:
10228     CompareOpc = 134;
10229     break;
10230   case Intrinsic::ppc_altivec_vcmpequd:
10231     if (Subtarget.hasP8Altivec())
10232       CompareOpc = 199;
10233     else
10234       return false;
10235     break;
10236   case Intrinsic::ppc_altivec_vcmpneb:
10237   case Intrinsic::ppc_altivec_vcmpneh:
10238   case Intrinsic::ppc_altivec_vcmpnew:
10239   case Intrinsic::ppc_altivec_vcmpnezb:
10240   case Intrinsic::ppc_altivec_vcmpnezh:
10241   case Intrinsic::ppc_altivec_vcmpnezw:
10242     if (Subtarget.hasP9Altivec())
10243       switch (IntrinsicID) {
10244       default:
10245         llvm_unreachable("Unknown comparison intrinsic.");
10246       case Intrinsic::ppc_altivec_vcmpneb:
10247         CompareOpc = 7;
10248         break;
10249       case Intrinsic::ppc_altivec_vcmpneh:
10250         CompareOpc = 71;
10251         break;
10252       case Intrinsic::ppc_altivec_vcmpnew:
10253         CompareOpc = 135;
10254         break;
10255       case Intrinsic::ppc_altivec_vcmpnezb:
10256         CompareOpc = 263;
10257         break;
10258       case Intrinsic::ppc_altivec_vcmpnezh:
10259         CompareOpc = 327;
10260         break;
10261       case Intrinsic::ppc_altivec_vcmpnezw:
10262         CompareOpc = 391;
10263         break;
10264       }
10265     else
10266       return false;
10267     break;
10268   case Intrinsic::ppc_altivec_vcmpgefp:
10269     CompareOpc = 454;
10270     break;
10271   case Intrinsic::ppc_altivec_vcmpgtfp:
10272     CompareOpc = 710;
10273     break;
10274   case Intrinsic::ppc_altivec_vcmpgtsb:
10275     CompareOpc = 774;
10276     break;
10277   case Intrinsic::ppc_altivec_vcmpgtsh:
10278     CompareOpc = 838;
10279     break;
10280   case Intrinsic::ppc_altivec_vcmpgtsw:
10281     CompareOpc = 902;
10282     break;
10283   case Intrinsic::ppc_altivec_vcmpgtsd:
10284     if (Subtarget.hasP8Altivec())
10285       CompareOpc = 967;
10286     else
10287       return false;
10288     break;
10289   case Intrinsic::ppc_altivec_vcmpgtub:
10290     CompareOpc = 518;
10291     break;
10292   case Intrinsic::ppc_altivec_vcmpgtuh:
10293     CompareOpc = 582;
10294     break;
10295   case Intrinsic::ppc_altivec_vcmpgtuw:
10296     CompareOpc = 646;
10297     break;
10298   case Intrinsic::ppc_altivec_vcmpgtud:
10299     if (Subtarget.hasP8Altivec())
10300       CompareOpc = 711;
10301     else
10302       return false;
10303     break;
10304   case Intrinsic::ppc_altivec_vcmpequq_p:
10305   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10306   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10307     if (!Subtarget.isISA3_1())
10308       return false;
10309     switch (IntrinsicID) {
10310     default:
10311       llvm_unreachable("Unknown comparison intrinsic.");
10312     case Intrinsic::ppc_altivec_vcmpequq_p:
10313       CompareOpc = 455;
10314       break;
10315     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10316       CompareOpc = 903;
10317       break;
10318     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10319       CompareOpc = 647;
10320       break;
10321     }
10322     isDot = true;
10323     break;
10324   }
10325   return true;
10326 }
10327 
10328 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10329 /// lower, do it, otherwise return null.
10330 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10331                                                    SelectionDAG &DAG) const {
10332   unsigned IntrinsicID =
10333     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10334 
10335   SDLoc dl(Op);
10336 
10337   switch (IntrinsicID) {
10338   case Intrinsic::thread_pointer:
10339     // Reads the thread pointer register, used for __builtin_thread_pointer.
10340     if (Subtarget.isPPC64())
10341       return DAG.getRegister(PPC::X13, MVT::i64);
10342     return DAG.getRegister(PPC::R2, MVT::i32);
10343 
10344   case Intrinsic::ppc_mma_disassemble_acc:
10345   case Intrinsic::ppc_vsx_disassemble_pair: {
10346     int NumVecs = 2;
10347     SDValue WideVec = Op.getOperand(1);
10348     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10349       NumVecs = 4;
10350       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10351     }
10352     SmallVector<SDValue, 4> RetOps;
10353     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10354       SDValue Extract = DAG.getNode(
10355           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10356           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10357                                                      : VecNo,
10358                           dl, getPointerTy(DAG.getDataLayout())));
10359       RetOps.push_back(Extract);
10360     }
10361     return DAG.getMergeValues(RetOps, dl);
10362   }
10363   }
10364 
10365   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10366   // opcode number of the comparison.
10367   int CompareOpc;
10368   bool isDot;
10369   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10370     return SDValue();    // Don't custom lower most intrinsics.
10371 
10372   // If this is a non-dot comparison, make the VCMP node and we are done.
10373   if (!isDot) {
10374     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10375                               Op.getOperand(1), Op.getOperand(2),
10376                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10377     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10378   }
10379 
10380   // Create the PPCISD altivec 'dot' comparison node.
10381   SDValue Ops[] = {
10382     Op.getOperand(2),  // LHS
10383     Op.getOperand(3),  // RHS
10384     DAG.getConstant(CompareOpc, dl, MVT::i32)
10385   };
10386   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10387   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10388 
10389   // Now that we have the comparison, emit a copy from the CR to a GPR.
10390   // This is flagged to the above dot comparison.
10391   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10392                                 DAG.getRegister(PPC::CR6, MVT::i32),
10393                                 CompNode.getValue(1));
10394 
10395   // Unpack the result based on how the target uses it.
10396   unsigned BitNo;   // Bit # of CR6.
10397   bool InvertBit;   // Invert result?
10398   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10399   default:  // Can't happen, don't crash on invalid number though.
10400   case 0:   // Return the value of the EQ bit of CR6.
10401     BitNo = 0; InvertBit = false;
10402     break;
10403   case 1:   // Return the inverted value of the EQ bit of CR6.
10404     BitNo = 0; InvertBit = true;
10405     break;
10406   case 2:   // Return the value of the LT bit of CR6.
10407     BitNo = 2; InvertBit = false;
10408     break;
10409   case 3:   // Return the inverted value of the LT bit of CR6.
10410     BitNo = 2; InvertBit = true;
10411     break;
10412   }
10413 
10414   // Shift the bit into the low position.
10415   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10416                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10417   // Isolate the bit.
10418   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10419                       DAG.getConstant(1, dl, MVT::i32));
10420 
10421   // If we are supposed to, toggle the bit.
10422   if (InvertBit)
10423     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10424                         DAG.getConstant(1, dl, MVT::i32));
10425   return Flags;
10426 }
10427 
10428 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10429                                                SelectionDAG &DAG) const {
10430   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10431   // the beginning of the argument list.
10432   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10433   SDLoc DL(Op);
10434   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10435   case Intrinsic::ppc_cfence: {
10436     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10437     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10438     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10439                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10440                                                   Op.getOperand(ArgStart + 1)),
10441                                       Op.getOperand(0)),
10442                    0);
10443   }
10444   default:
10445     break;
10446   }
10447   return SDValue();
10448 }
10449 
10450 // Lower scalar BSWAP64 to xxbrd.
10451 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10452   SDLoc dl(Op);
10453   if (!Subtarget.isPPC64())
10454     return Op;
10455   // MTVSRDD
10456   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10457                    Op.getOperand(0));
10458   // XXBRD
10459   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10460   // MFVSRD
10461   int VectorIndex = 0;
10462   if (Subtarget.isLittleEndian())
10463     VectorIndex = 1;
10464   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10465                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10466   return Op;
10467 }
10468 
10469 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10470 // compared to a value that is atomically loaded (atomic loads zero-extend).
10471 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10472                                                 SelectionDAG &DAG) const {
10473   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10474          "Expecting an atomic compare-and-swap here.");
10475   SDLoc dl(Op);
10476   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10477   EVT MemVT = AtomicNode->getMemoryVT();
10478   if (MemVT.getSizeInBits() >= 32)
10479     return Op;
10480 
10481   SDValue CmpOp = Op.getOperand(2);
10482   // If this is already correctly zero-extended, leave it alone.
10483   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10484   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10485     return Op;
10486 
10487   // Clear the high bits of the compare operand.
10488   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10489   SDValue NewCmpOp =
10490     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10491                 DAG.getConstant(MaskVal, dl, MVT::i32));
10492 
10493   // Replace the existing compare operand with the properly zero-extended one.
10494   SmallVector<SDValue, 4> Ops;
10495   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10496     Ops.push_back(AtomicNode->getOperand(i));
10497   Ops[2] = NewCmpOp;
10498   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10499   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10500   auto NodeTy =
10501     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10502   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10503 }
10504 
10505 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10506                                                  SelectionDAG &DAG) const {
10507   SDLoc dl(Op);
10508   // Create a stack slot that is 16-byte aligned.
10509   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10510   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10511   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10512   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10513 
10514   // Store the input value into Value#0 of the stack slot.
10515   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10516                                MachinePointerInfo());
10517   // Load it out.
10518   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10519 }
10520 
10521 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10522                                                   SelectionDAG &DAG) const {
10523   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10524          "Should only be called for ISD::INSERT_VECTOR_ELT");
10525 
10526   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10527 
10528   EVT VT = Op.getValueType();
10529   SDLoc dl(Op);
10530   SDValue V1 = Op.getOperand(0);
10531   SDValue V2 = Op.getOperand(1);
10532   SDValue V3 = Op.getOperand(2);
10533 
10534   if (VT == MVT::v2f64 && C)
10535     return Op;
10536 
10537   if (Subtarget.isISA3_1()) {
10538     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10539       return SDValue();
10540     // On P10, we have legal lowering for constant and variable indices for
10541     // integer vectors.
10542     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10543         VT == MVT::v2i64)
10544       return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10545     // For f32 and f64 vectors, we have legal lowering for variable indices.
10546     // For f32 we also have legal lowering when the element is loaded from
10547     // memory.
10548     if (VT == MVT::v4f32 || VT == MVT::v2f64) {
10549       if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2)))
10550         return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10551       return Op;
10552     }
10553   }
10554 
10555   // Before P10, we have legal lowering for constant indices but not for
10556   // variable ones.
10557   if (!C)
10558     return SDValue();
10559 
10560   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10561   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10562     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10563     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10564     unsigned InsertAtElement = C->getZExtValue();
10565     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10566     if (Subtarget.isLittleEndian()) {
10567       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10568     }
10569     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10570                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10571   }
10572   return Op;
10573 }
10574 
10575 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10576                                            SelectionDAG &DAG) const {
10577   SDLoc dl(Op);
10578   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10579   SDValue LoadChain = LN->getChain();
10580   SDValue BasePtr = LN->getBasePtr();
10581   EVT VT = Op.getValueType();
10582 
10583   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10584     return Op;
10585 
10586   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10587   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10588   // 2 or 4 vsx registers.
10589   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10590          "Type unsupported without MMA");
10591   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10592          "Type unsupported without paired vector support");
10593   Align Alignment = LN->getAlign();
10594   SmallVector<SDValue, 4> Loads;
10595   SmallVector<SDValue, 4> LoadChains;
10596   unsigned NumVecs = VT.getSizeInBits() / 128;
10597   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10598     SDValue Load =
10599         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10600                     LN->getPointerInfo().getWithOffset(Idx * 16),
10601                     commonAlignment(Alignment, Idx * 16),
10602                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10603     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10604                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10605     Loads.push_back(Load);
10606     LoadChains.push_back(Load.getValue(1));
10607   }
10608   if (Subtarget.isLittleEndian()) {
10609     std::reverse(Loads.begin(), Loads.end());
10610     std::reverse(LoadChains.begin(), LoadChains.end());
10611   }
10612   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10613   SDValue Value =
10614       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10615                   dl, VT, Loads);
10616   SDValue RetOps[] = {Value, TF};
10617   return DAG.getMergeValues(RetOps, dl);
10618 }
10619 
10620 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10621                                             SelectionDAG &DAG) const {
10622   SDLoc dl(Op);
10623   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10624   SDValue StoreChain = SN->getChain();
10625   SDValue BasePtr = SN->getBasePtr();
10626   SDValue Value = SN->getValue();
10627   EVT StoreVT = Value.getValueType();
10628 
10629   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10630     return Op;
10631 
10632   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10633   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10634   // underlying registers individually.
10635   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10636          "Type unsupported without MMA");
10637   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10638          "Type unsupported without paired vector support");
10639   Align Alignment = SN->getAlign();
10640   SmallVector<SDValue, 4> Stores;
10641   unsigned NumVecs = 2;
10642   if (StoreVT == MVT::v512i1) {
10643     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10644     NumVecs = 4;
10645   }
10646   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10647     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10648     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10649                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10650     SDValue Store =
10651         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10652                      SN->getPointerInfo().getWithOffset(Idx * 16),
10653                      commonAlignment(Alignment, Idx * 16),
10654                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10655     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10656                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10657     Stores.push_back(Store);
10658   }
10659   SDValue TF = DAG.getTokenFactor(dl, Stores);
10660   return TF;
10661 }
10662 
10663 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10664   SDLoc dl(Op);
10665   if (Op.getValueType() == MVT::v4i32) {
10666     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10667 
10668     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10669     // +16 as shift amt.
10670     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10671     SDValue RHSSwap =   // = vrlw RHS, 16
10672       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10673 
10674     // Shrinkify inputs to v8i16.
10675     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10676     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10677     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10678 
10679     // Low parts multiplied together, generating 32-bit results (we ignore the
10680     // top parts).
10681     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10682                                         LHS, RHS, DAG, dl, MVT::v4i32);
10683 
10684     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10685                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10686     // Shift the high parts up 16 bits.
10687     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10688                               Neg16, DAG, dl);
10689     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10690   } else if (Op.getValueType() == MVT::v16i8) {
10691     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10692     bool isLittleEndian = Subtarget.isLittleEndian();
10693 
10694     // Multiply the even 8-bit parts, producing 16-bit sums.
10695     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10696                                            LHS, RHS, DAG, dl, MVT::v8i16);
10697     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10698 
10699     // Multiply the odd 8-bit parts, producing 16-bit sums.
10700     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10701                                           LHS, RHS, DAG, dl, MVT::v8i16);
10702     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10703 
10704     // Merge the results together.  Because vmuleub and vmuloub are
10705     // instructions with a big-endian bias, we must reverse the
10706     // element numbering and reverse the meaning of "odd" and "even"
10707     // when generating little endian code.
10708     int Ops[16];
10709     for (unsigned i = 0; i != 8; ++i) {
10710       if (isLittleEndian) {
10711         Ops[i*2  ] = 2*i;
10712         Ops[i*2+1] = 2*i+16;
10713       } else {
10714         Ops[i*2  ] = 2*i+1;
10715         Ops[i*2+1] = 2*i+1+16;
10716       }
10717     }
10718     if (isLittleEndian)
10719       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10720     else
10721       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10722   } else {
10723     llvm_unreachable("Unknown mul to lower!");
10724   }
10725 }
10726 
10727 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10728   bool IsStrict = Op->isStrictFPOpcode();
10729   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10730       !Subtarget.hasP9Vector())
10731     return SDValue();
10732 
10733   return Op;
10734 }
10735 
10736 // Custom lowering for fpext vf32 to v2f64
10737 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10738 
10739   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10740          "Should only be called for ISD::FP_EXTEND");
10741 
10742   // FIXME: handle extends from half precision float vectors on P9.
10743   // We only want to custom lower an extend from v2f32 to v2f64.
10744   if (Op.getValueType() != MVT::v2f64 ||
10745       Op.getOperand(0).getValueType() != MVT::v2f32)
10746     return SDValue();
10747 
10748   SDLoc dl(Op);
10749   SDValue Op0 = Op.getOperand(0);
10750 
10751   switch (Op0.getOpcode()) {
10752   default:
10753     return SDValue();
10754   case ISD::EXTRACT_SUBVECTOR: {
10755     assert(Op0.getNumOperands() == 2 &&
10756            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10757            "Node should have 2 operands with second one being a constant!");
10758 
10759     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10760       return SDValue();
10761 
10762     // Custom lower is only done for high or low doubleword.
10763     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10764     if (Idx % 2 != 0)
10765       return SDValue();
10766 
10767     // Since input is v4f32, at this point Idx is either 0 or 2.
10768     // Shift to get the doubleword position we want.
10769     int DWord = Idx >> 1;
10770 
10771     // High and low word positions are different on little endian.
10772     if (Subtarget.isLittleEndian())
10773       DWord ^= 0x1;
10774 
10775     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10776                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10777   }
10778   case ISD::FADD:
10779   case ISD::FMUL:
10780   case ISD::FSUB: {
10781     SDValue NewLoad[2];
10782     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10783       // Ensure both input are loads.
10784       SDValue LdOp = Op0.getOperand(i);
10785       if (LdOp.getOpcode() != ISD::LOAD)
10786         return SDValue();
10787       // Generate new load node.
10788       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10789       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10790       NewLoad[i] = DAG.getMemIntrinsicNode(
10791           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10792           LD->getMemoryVT(), LD->getMemOperand());
10793     }
10794     SDValue NewOp =
10795         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10796                     NewLoad[1], Op0.getNode()->getFlags());
10797     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10798                        DAG.getConstant(0, dl, MVT::i32));
10799   }
10800   case ISD::LOAD: {
10801     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10802     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10803     SDValue NewLd = DAG.getMemIntrinsicNode(
10804         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10805         LD->getMemoryVT(), LD->getMemOperand());
10806     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10807                        DAG.getConstant(0, dl, MVT::i32));
10808   }
10809   }
10810   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10811 }
10812 
10813 /// LowerOperation - Provide custom lowering hooks for some operations.
10814 ///
10815 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10816   switch (Op.getOpcode()) {
10817   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10818   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10819   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10820   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10821   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10822   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10823   case ISD::STRICT_FSETCC:
10824   case ISD::STRICT_FSETCCS:
10825   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10826   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10827   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10828 
10829   case ISD::INLINEASM:
10830   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
10831   // Variable argument lowering.
10832   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10833   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10834   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10835 
10836   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10837   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10838   case ISD::GET_DYNAMIC_AREA_OFFSET:
10839     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10840 
10841   // Exception handling lowering.
10842   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10843   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10844   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10845 
10846   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10847   case ISD::STORE:              return LowerSTORE(Op, DAG);
10848   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10849   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10850   case ISD::STRICT_FP_TO_UINT:
10851   case ISD::STRICT_FP_TO_SINT:
10852   case ISD::FP_TO_UINT:
10853   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10854   case ISD::STRICT_UINT_TO_FP:
10855   case ISD::STRICT_SINT_TO_FP:
10856   case ISD::UINT_TO_FP:
10857   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10858   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10859 
10860   // Lower 64-bit shifts.
10861   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10862   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10863   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10864 
10865   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10866   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10867 
10868   // Vector-related lowering.
10869   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10870   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10871   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10872   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10873   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10874   case ISD::MUL:                return LowerMUL(Op, DAG);
10875   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10876   case ISD::STRICT_FP_ROUND:
10877   case ISD::FP_ROUND:
10878     return LowerFP_ROUND(Op, DAG);
10879   case ISD::ROTL:               return LowerROTL(Op, DAG);
10880 
10881   // For counter-based loop handling.
10882   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10883 
10884   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10885 
10886   // Frame & Return address.
10887   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10888   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10889 
10890   case ISD::INTRINSIC_VOID:
10891     return LowerINTRINSIC_VOID(Op, DAG);
10892   case ISD::BSWAP:
10893     return LowerBSWAP(Op, DAG);
10894   case ISD::ATOMIC_CMP_SWAP:
10895     return LowerATOMIC_CMP_SWAP(Op, DAG);
10896   }
10897 }
10898 
10899 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10900                                            SmallVectorImpl<SDValue>&Results,
10901                                            SelectionDAG &DAG) const {
10902   SDLoc dl(N);
10903   switch (N->getOpcode()) {
10904   default:
10905     llvm_unreachable("Do not know how to custom type legalize this operation!");
10906   case ISD::READCYCLECOUNTER: {
10907     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10908     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10909 
10910     Results.push_back(
10911         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10912     Results.push_back(RTB.getValue(2));
10913     break;
10914   }
10915   case ISD::INTRINSIC_W_CHAIN: {
10916     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10917         Intrinsic::loop_decrement)
10918       break;
10919 
10920     assert(N->getValueType(0) == MVT::i1 &&
10921            "Unexpected result type for CTR decrement intrinsic");
10922     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10923                                  N->getValueType(0));
10924     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10925     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10926                                  N->getOperand(1));
10927 
10928     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10929     Results.push_back(NewInt.getValue(1));
10930     break;
10931   }
10932   case ISD::VAARG: {
10933     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10934       return;
10935 
10936     EVT VT = N->getValueType(0);
10937 
10938     if (VT == MVT::i64) {
10939       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10940 
10941       Results.push_back(NewNode);
10942       Results.push_back(NewNode.getValue(1));
10943     }
10944     return;
10945   }
10946   case ISD::STRICT_FP_TO_SINT:
10947   case ISD::STRICT_FP_TO_UINT:
10948   case ISD::FP_TO_SINT:
10949   case ISD::FP_TO_UINT:
10950     // LowerFP_TO_INT() can only handle f32 and f64.
10951     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10952         MVT::ppcf128)
10953       return;
10954     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10955     return;
10956   case ISD::TRUNCATE: {
10957     if (!N->getValueType(0).isVector())
10958       return;
10959     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
10960     if (Lowered)
10961       Results.push_back(Lowered);
10962     return;
10963   }
10964   case ISD::FSHL:
10965   case ISD::FSHR:
10966     // Don't handle funnel shifts here.
10967     return;
10968   case ISD::BITCAST:
10969     // Don't handle bitcast here.
10970     return;
10971   case ISD::FP_EXTEND:
10972     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10973     if (Lowered)
10974       Results.push_back(Lowered);
10975     return;
10976   }
10977 }
10978 
10979 //===----------------------------------------------------------------------===//
10980 //  Other Lowering Code
10981 //===----------------------------------------------------------------------===//
10982 
10983 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
10984   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10985   Function *Func = Intrinsic::getDeclaration(M, Id);
10986   return Builder.CreateCall(Func, {});
10987 }
10988 
10989 // The mappings for emitLeading/TrailingFence is taken from
10990 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10991 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10992                                                  Instruction *Inst,
10993                                                  AtomicOrdering Ord) const {
10994   if (Ord == AtomicOrdering::SequentiallyConsistent)
10995     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10996   if (isReleaseOrStronger(Ord))
10997     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10998   return nullptr;
10999 }
11000 
11001 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11002                                                   Instruction *Inst,
11003                                                   AtomicOrdering Ord) const {
11004   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11005     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11006     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11007     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11008     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11009       return Builder.CreateCall(
11010           Intrinsic::getDeclaration(
11011               Builder.GetInsertBlock()->getParent()->getParent(),
11012               Intrinsic::ppc_cfence, {Inst->getType()}),
11013           {Inst});
11014     // FIXME: Can use isync for rmw operation.
11015     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11016   }
11017   return nullptr;
11018 }
11019 
11020 MachineBasicBlock *
11021 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11022                                     unsigned AtomicSize,
11023                                     unsigned BinOpcode,
11024                                     unsigned CmpOpcode,
11025                                     unsigned CmpPred) const {
11026   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11027   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11028 
11029   auto LoadMnemonic = PPC::LDARX;
11030   auto StoreMnemonic = PPC::STDCX;
11031   switch (AtomicSize) {
11032   default:
11033     llvm_unreachable("Unexpected size of atomic entity");
11034   case 1:
11035     LoadMnemonic = PPC::LBARX;
11036     StoreMnemonic = PPC::STBCX;
11037     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11038     break;
11039   case 2:
11040     LoadMnemonic = PPC::LHARX;
11041     StoreMnemonic = PPC::STHCX;
11042     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11043     break;
11044   case 4:
11045     LoadMnemonic = PPC::LWARX;
11046     StoreMnemonic = PPC::STWCX;
11047     break;
11048   case 8:
11049     LoadMnemonic = PPC::LDARX;
11050     StoreMnemonic = PPC::STDCX;
11051     break;
11052   }
11053 
11054   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11055   MachineFunction *F = BB->getParent();
11056   MachineFunction::iterator It = ++BB->getIterator();
11057 
11058   Register dest = MI.getOperand(0).getReg();
11059   Register ptrA = MI.getOperand(1).getReg();
11060   Register ptrB = MI.getOperand(2).getReg();
11061   Register incr = MI.getOperand(3).getReg();
11062   DebugLoc dl = MI.getDebugLoc();
11063 
11064   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11065   MachineBasicBlock *loop2MBB =
11066     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11067   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11068   F->insert(It, loopMBB);
11069   if (CmpOpcode)
11070     F->insert(It, loop2MBB);
11071   F->insert(It, exitMBB);
11072   exitMBB->splice(exitMBB->begin(), BB,
11073                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11074   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11075 
11076   MachineRegisterInfo &RegInfo = F->getRegInfo();
11077   Register TmpReg = (!BinOpcode) ? incr :
11078     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11079                                            : &PPC::GPRCRegClass);
11080 
11081   //  thisMBB:
11082   //   ...
11083   //   fallthrough --> loopMBB
11084   BB->addSuccessor(loopMBB);
11085 
11086   //  loopMBB:
11087   //   l[wd]arx dest, ptr
11088   //   add r0, dest, incr
11089   //   st[wd]cx. r0, ptr
11090   //   bne- loopMBB
11091   //   fallthrough --> exitMBB
11092 
11093   // For max/min...
11094   //  loopMBB:
11095   //   l[wd]arx dest, ptr
11096   //   cmpl?[wd] incr, dest
11097   //   bgt exitMBB
11098   //  loop2MBB:
11099   //   st[wd]cx. dest, ptr
11100   //   bne- loopMBB
11101   //   fallthrough --> exitMBB
11102 
11103   BB = loopMBB;
11104   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11105     .addReg(ptrA).addReg(ptrB);
11106   if (BinOpcode)
11107     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11108   if (CmpOpcode) {
11109     // Signed comparisons of byte or halfword values must be sign-extended.
11110     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11111       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11112       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11113               ExtReg).addReg(dest);
11114       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11115         .addReg(incr).addReg(ExtReg);
11116     } else
11117       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11118         .addReg(incr).addReg(dest);
11119 
11120     BuildMI(BB, dl, TII->get(PPC::BCC))
11121       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11122     BB->addSuccessor(loop2MBB);
11123     BB->addSuccessor(exitMBB);
11124     BB = loop2MBB;
11125   }
11126   BuildMI(BB, dl, TII->get(StoreMnemonic))
11127     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11128   BuildMI(BB, dl, TII->get(PPC::BCC))
11129     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11130   BB->addSuccessor(loopMBB);
11131   BB->addSuccessor(exitMBB);
11132 
11133   //  exitMBB:
11134   //   ...
11135   BB = exitMBB;
11136   return BB;
11137 }
11138 
11139 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11140   switch(MI.getOpcode()) {
11141   default:
11142     return false;
11143   case PPC::COPY:
11144     return TII->isSignExtended(MI);
11145   case PPC::LHA:
11146   case PPC::LHA8:
11147   case PPC::LHAU:
11148   case PPC::LHAU8:
11149   case PPC::LHAUX:
11150   case PPC::LHAUX8:
11151   case PPC::LHAX:
11152   case PPC::LHAX8:
11153   case PPC::LWA:
11154   case PPC::LWAUX:
11155   case PPC::LWAX:
11156   case PPC::LWAX_32:
11157   case PPC::LWA_32:
11158   case PPC::PLHA:
11159   case PPC::PLHA8:
11160   case PPC::PLHA8pc:
11161   case PPC::PLHApc:
11162   case PPC::PLWA:
11163   case PPC::PLWA8:
11164   case PPC::PLWA8pc:
11165   case PPC::PLWApc:
11166   case PPC::EXTSB:
11167   case PPC::EXTSB8:
11168   case PPC::EXTSB8_32_64:
11169   case PPC::EXTSB8_rec:
11170   case PPC::EXTSB_rec:
11171   case PPC::EXTSH:
11172   case PPC::EXTSH8:
11173   case PPC::EXTSH8_32_64:
11174   case PPC::EXTSH8_rec:
11175   case PPC::EXTSH_rec:
11176   case PPC::EXTSW:
11177   case PPC::EXTSWSLI:
11178   case PPC::EXTSWSLI_32_64:
11179   case PPC::EXTSWSLI_32_64_rec:
11180   case PPC::EXTSWSLI_rec:
11181   case PPC::EXTSW_32:
11182   case PPC::EXTSW_32_64:
11183   case PPC::EXTSW_32_64_rec:
11184   case PPC::EXTSW_rec:
11185   case PPC::SRAW:
11186   case PPC::SRAWI:
11187   case PPC::SRAWI_rec:
11188   case PPC::SRAW_rec:
11189     return true;
11190   }
11191   return false;
11192 }
11193 
11194 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11195     MachineInstr &MI, MachineBasicBlock *BB,
11196     bool is8bit, // operation
11197     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11198   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11199   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11200 
11201   // If this is a signed comparison and the value being compared is not known
11202   // to be sign extended, sign extend it here.
11203   DebugLoc dl = MI.getDebugLoc();
11204   MachineFunction *F = BB->getParent();
11205   MachineRegisterInfo &RegInfo = F->getRegInfo();
11206   Register incr = MI.getOperand(3).getReg();
11207   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11208     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11209 
11210   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11211     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11212     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11213         .addReg(MI.getOperand(3).getReg());
11214     MI.getOperand(3).setReg(ValueReg);
11215   }
11216   // If we support part-word atomic mnemonics, just use them
11217   if (Subtarget.hasPartwordAtomics())
11218     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11219                             CmpPred);
11220 
11221   // In 64 bit mode we have to use 64 bits for addresses, even though the
11222   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11223   // registers without caring whether they're 32 or 64, but here we're
11224   // doing actual arithmetic on the addresses.
11225   bool is64bit = Subtarget.isPPC64();
11226   bool isLittleEndian = Subtarget.isLittleEndian();
11227   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11228 
11229   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11230   MachineFunction::iterator It = ++BB->getIterator();
11231 
11232   Register dest = MI.getOperand(0).getReg();
11233   Register ptrA = MI.getOperand(1).getReg();
11234   Register ptrB = MI.getOperand(2).getReg();
11235 
11236   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11237   MachineBasicBlock *loop2MBB =
11238       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11239   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11240   F->insert(It, loopMBB);
11241   if (CmpOpcode)
11242     F->insert(It, loop2MBB);
11243   F->insert(It, exitMBB);
11244   exitMBB->splice(exitMBB->begin(), BB,
11245                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11246   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11247 
11248   const TargetRegisterClass *RC =
11249       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11250   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11251 
11252   Register PtrReg = RegInfo.createVirtualRegister(RC);
11253   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11254   Register ShiftReg =
11255       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11256   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11257   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11258   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11259   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11260   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11261   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11262   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11263   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11264   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11265   Register Ptr1Reg;
11266   Register TmpReg =
11267       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11268 
11269   //  thisMBB:
11270   //   ...
11271   //   fallthrough --> loopMBB
11272   BB->addSuccessor(loopMBB);
11273 
11274   // The 4-byte load must be aligned, while a char or short may be
11275   // anywhere in the word.  Hence all this nasty bookkeeping code.
11276   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11277   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11278   //   xori shift, shift1, 24 [16]
11279   //   rlwinm ptr, ptr1, 0, 0, 29
11280   //   slw incr2, incr, shift
11281   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11282   //   slw mask, mask2, shift
11283   //  loopMBB:
11284   //   lwarx tmpDest, ptr
11285   //   add tmp, tmpDest, incr2
11286   //   andc tmp2, tmpDest, mask
11287   //   and tmp3, tmp, mask
11288   //   or tmp4, tmp3, tmp2
11289   //   stwcx. tmp4, ptr
11290   //   bne- loopMBB
11291   //   fallthrough --> exitMBB
11292   //   srw SrwDest, tmpDest, shift
11293   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11294   if (ptrA != ZeroReg) {
11295     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11296     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11297         .addReg(ptrA)
11298         .addReg(ptrB);
11299   } else {
11300     Ptr1Reg = ptrB;
11301   }
11302   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11303   // mode.
11304   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11305       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11306       .addImm(3)
11307       .addImm(27)
11308       .addImm(is8bit ? 28 : 27);
11309   if (!isLittleEndian)
11310     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11311         .addReg(Shift1Reg)
11312         .addImm(is8bit ? 24 : 16);
11313   if (is64bit)
11314     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11315         .addReg(Ptr1Reg)
11316         .addImm(0)
11317         .addImm(61);
11318   else
11319     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11320         .addReg(Ptr1Reg)
11321         .addImm(0)
11322         .addImm(0)
11323         .addImm(29);
11324   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11325   if (is8bit)
11326     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11327   else {
11328     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11329     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11330         .addReg(Mask3Reg)
11331         .addImm(65535);
11332   }
11333   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11334       .addReg(Mask2Reg)
11335       .addReg(ShiftReg);
11336 
11337   BB = loopMBB;
11338   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11339       .addReg(ZeroReg)
11340       .addReg(PtrReg);
11341   if (BinOpcode)
11342     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11343         .addReg(Incr2Reg)
11344         .addReg(TmpDestReg);
11345   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11346       .addReg(TmpDestReg)
11347       .addReg(MaskReg);
11348   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11349   if (CmpOpcode) {
11350     // For unsigned comparisons, we can directly compare the shifted values.
11351     // For signed comparisons we shift and sign extend.
11352     Register SReg = RegInfo.createVirtualRegister(GPRC);
11353     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11354         .addReg(TmpDestReg)
11355         .addReg(MaskReg);
11356     unsigned ValueReg = SReg;
11357     unsigned CmpReg = Incr2Reg;
11358     if (CmpOpcode == PPC::CMPW) {
11359       ValueReg = RegInfo.createVirtualRegister(GPRC);
11360       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11361           .addReg(SReg)
11362           .addReg(ShiftReg);
11363       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11364       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11365           .addReg(ValueReg);
11366       ValueReg = ValueSReg;
11367       CmpReg = incr;
11368     }
11369     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11370         .addReg(CmpReg)
11371         .addReg(ValueReg);
11372     BuildMI(BB, dl, TII->get(PPC::BCC))
11373         .addImm(CmpPred)
11374         .addReg(PPC::CR0)
11375         .addMBB(exitMBB);
11376     BB->addSuccessor(loop2MBB);
11377     BB->addSuccessor(exitMBB);
11378     BB = loop2MBB;
11379   }
11380   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11381   BuildMI(BB, dl, TII->get(PPC::STWCX))
11382       .addReg(Tmp4Reg)
11383       .addReg(ZeroReg)
11384       .addReg(PtrReg);
11385   BuildMI(BB, dl, TII->get(PPC::BCC))
11386       .addImm(PPC::PRED_NE)
11387       .addReg(PPC::CR0)
11388       .addMBB(loopMBB);
11389   BB->addSuccessor(loopMBB);
11390   BB->addSuccessor(exitMBB);
11391 
11392   //  exitMBB:
11393   //   ...
11394   BB = exitMBB;
11395   // Since the shift amount is not a constant, we need to clear
11396   // the upper bits with a separate RLWINM.
11397   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11398       .addReg(SrwDestReg)
11399       .addImm(0)
11400       .addImm(is8bit ? 24 : 16)
11401       .addImm(31);
11402   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11403       .addReg(TmpDestReg)
11404       .addReg(ShiftReg);
11405   return BB;
11406 }
11407 
11408 llvm::MachineBasicBlock *
11409 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11410                                     MachineBasicBlock *MBB) const {
11411   DebugLoc DL = MI.getDebugLoc();
11412   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11413   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11414 
11415   MachineFunction *MF = MBB->getParent();
11416   MachineRegisterInfo &MRI = MF->getRegInfo();
11417 
11418   const BasicBlock *BB = MBB->getBasicBlock();
11419   MachineFunction::iterator I = ++MBB->getIterator();
11420 
11421   Register DstReg = MI.getOperand(0).getReg();
11422   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11423   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11424   Register mainDstReg = MRI.createVirtualRegister(RC);
11425   Register restoreDstReg = MRI.createVirtualRegister(RC);
11426 
11427   MVT PVT = getPointerTy(MF->getDataLayout());
11428   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11429          "Invalid Pointer Size!");
11430   // For v = setjmp(buf), we generate
11431   //
11432   // thisMBB:
11433   //  SjLjSetup mainMBB
11434   //  bl mainMBB
11435   //  v_restore = 1
11436   //  b sinkMBB
11437   //
11438   // mainMBB:
11439   //  buf[LabelOffset] = LR
11440   //  v_main = 0
11441   //
11442   // sinkMBB:
11443   //  v = phi(main, restore)
11444   //
11445 
11446   MachineBasicBlock *thisMBB = MBB;
11447   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11448   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11449   MF->insert(I, mainMBB);
11450   MF->insert(I, sinkMBB);
11451 
11452   MachineInstrBuilder MIB;
11453 
11454   // Transfer the remainder of BB and its successor edges to sinkMBB.
11455   sinkMBB->splice(sinkMBB->begin(), MBB,
11456                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11457   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11458 
11459   // Note that the structure of the jmp_buf used here is not compatible
11460   // with that used by libc, and is not designed to be. Specifically, it
11461   // stores only those 'reserved' registers that LLVM does not otherwise
11462   // understand how to spill. Also, by convention, by the time this
11463   // intrinsic is called, Clang has already stored the frame address in the
11464   // first slot of the buffer and stack address in the third. Following the
11465   // X86 target code, we'll store the jump address in the second slot. We also
11466   // need to save the TOC pointer (R2) to handle jumps between shared
11467   // libraries, and that will be stored in the fourth slot. The thread
11468   // identifier (R13) is not affected.
11469 
11470   // thisMBB:
11471   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11472   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11473   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11474 
11475   // Prepare IP either in reg.
11476   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11477   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11478   Register BufReg = MI.getOperand(1).getReg();
11479 
11480   if (Subtarget.is64BitELFABI()) {
11481     setUsesTOCBasePtr(*MBB->getParent());
11482     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11483               .addReg(PPC::X2)
11484               .addImm(TOCOffset)
11485               .addReg(BufReg)
11486               .cloneMemRefs(MI);
11487   }
11488 
11489   // Naked functions never have a base pointer, and so we use r1. For all
11490   // other functions, this decision must be delayed until during PEI.
11491   unsigned BaseReg;
11492   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11493     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11494   else
11495     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11496 
11497   MIB = BuildMI(*thisMBB, MI, DL,
11498                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11499             .addReg(BaseReg)
11500             .addImm(BPOffset)
11501             .addReg(BufReg)
11502             .cloneMemRefs(MI);
11503 
11504   // Setup
11505   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11506   MIB.addRegMask(TRI->getNoPreservedMask());
11507 
11508   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11509 
11510   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11511           .addMBB(mainMBB);
11512   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11513 
11514   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11515   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11516 
11517   // mainMBB:
11518   //  mainDstReg = 0
11519   MIB =
11520       BuildMI(mainMBB, DL,
11521               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11522 
11523   // Store IP
11524   if (Subtarget.isPPC64()) {
11525     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11526             .addReg(LabelReg)
11527             .addImm(LabelOffset)
11528             .addReg(BufReg);
11529   } else {
11530     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11531             .addReg(LabelReg)
11532             .addImm(LabelOffset)
11533             .addReg(BufReg);
11534   }
11535   MIB.cloneMemRefs(MI);
11536 
11537   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11538   mainMBB->addSuccessor(sinkMBB);
11539 
11540   // sinkMBB:
11541   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11542           TII->get(PPC::PHI), DstReg)
11543     .addReg(mainDstReg).addMBB(mainMBB)
11544     .addReg(restoreDstReg).addMBB(thisMBB);
11545 
11546   MI.eraseFromParent();
11547   return sinkMBB;
11548 }
11549 
11550 MachineBasicBlock *
11551 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11552                                      MachineBasicBlock *MBB) const {
11553   DebugLoc DL = MI.getDebugLoc();
11554   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11555 
11556   MachineFunction *MF = MBB->getParent();
11557   MachineRegisterInfo &MRI = MF->getRegInfo();
11558 
11559   MVT PVT = getPointerTy(MF->getDataLayout());
11560   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11561          "Invalid Pointer Size!");
11562 
11563   const TargetRegisterClass *RC =
11564     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11565   Register Tmp = MRI.createVirtualRegister(RC);
11566   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11567   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11568   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11569   unsigned BP =
11570       (PVT == MVT::i64)
11571           ? PPC::X30
11572           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11573                                                               : PPC::R30);
11574 
11575   MachineInstrBuilder MIB;
11576 
11577   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11578   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11579   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11580   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11581 
11582   Register BufReg = MI.getOperand(0).getReg();
11583 
11584   // Reload FP (the jumped-to function may not have had a
11585   // frame pointer, and if so, then its r31 will be restored
11586   // as necessary).
11587   if (PVT == MVT::i64) {
11588     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11589             .addImm(0)
11590             .addReg(BufReg);
11591   } else {
11592     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11593             .addImm(0)
11594             .addReg(BufReg);
11595   }
11596   MIB.cloneMemRefs(MI);
11597 
11598   // Reload IP
11599   if (PVT == MVT::i64) {
11600     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11601             .addImm(LabelOffset)
11602             .addReg(BufReg);
11603   } else {
11604     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11605             .addImm(LabelOffset)
11606             .addReg(BufReg);
11607   }
11608   MIB.cloneMemRefs(MI);
11609 
11610   // Reload SP
11611   if (PVT == MVT::i64) {
11612     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11613             .addImm(SPOffset)
11614             .addReg(BufReg);
11615   } else {
11616     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11617             .addImm(SPOffset)
11618             .addReg(BufReg);
11619   }
11620   MIB.cloneMemRefs(MI);
11621 
11622   // Reload BP
11623   if (PVT == MVT::i64) {
11624     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11625             .addImm(BPOffset)
11626             .addReg(BufReg);
11627   } else {
11628     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11629             .addImm(BPOffset)
11630             .addReg(BufReg);
11631   }
11632   MIB.cloneMemRefs(MI);
11633 
11634   // Reload TOC
11635   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11636     setUsesTOCBasePtr(*MBB->getParent());
11637     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11638               .addImm(TOCOffset)
11639               .addReg(BufReg)
11640               .cloneMemRefs(MI);
11641   }
11642 
11643   // Jump
11644   BuildMI(*MBB, MI, DL,
11645           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11646   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11647 
11648   MI.eraseFromParent();
11649   return MBB;
11650 }
11651 
11652 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11653   // If the function specifically requests inline stack probes, emit them.
11654   if (MF.getFunction().hasFnAttribute("probe-stack"))
11655     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11656            "inline-asm";
11657   return false;
11658 }
11659 
11660 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11661   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11662   unsigned StackAlign = TFI->getStackAlignment();
11663   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11664          "Unexpected stack alignment");
11665   // The default stack probe size is 4096 if the function has no
11666   // stack-probe-size attribute.
11667   unsigned StackProbeSize = 4096;
11668   const Function &Fn = MF.getFunction();
11669   if (Fn.hasFnAttribute("stack-probe-size"))
11670     Fn.getFnAttribute("stack-probe-size")
11671         .getValueAsString()
11672         .getAsInteger(0, StackProbeSize);
11673   // Round down to the stack alignment.
11674   StackProbeSize &= ~(StackAlign - 1);
11675   return StackProbeSize ? StackProbeSize : StackAlign;
11676 }
11677 
11678 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11679 // into three phases. In the first phase, it uses pseudo instruction
11680 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11681 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11682 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11683 // MaxCallFrameSize so that it can calculate correct data area pointer.
11684 MachineBasicBlock *
11685 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11686                                     MachineBasicBlock *MBB) const {
11687   const bool isPPC64 = Subtarget.isPPC64();
11688   MachineFunction *MF = MBB->getParent();
11689   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11690   DebugLoc DL = MI.getDebugLoc();
11691   const unsigned ProbeSize = getStackProbeSize(*MF);
11692   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11693   MachineRegisterInfo &MRI = MF->getRegInfo();
11694   // The CFG of probing stack looks as
11695   //         +-----+
11696   //         | MBB |
11697   //         +--+--+
11698   //            |
11699   //       +----v----+
11700   //  +--->+ TestMBB +---+
11701   //  |    +----+----+   |
11702   //  |         |        |
11703   //  |   +-----v----+   |
11704   //  +---+ BlockMBB |   |
11705   //      +----------+   |
11706   //                     |
11707   //       +---------+   |
11708   //       | TailMBB +<--+
11709   //       +---------+
11710   // In MBB, calculate previous frame pointer and final stack pointer.
11711   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11712   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11713   // TailMBB is spliced via \p MI.
11714   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11715   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11716   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11717 
11718   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11719   MF->insert(MBBIter, TestMBB);
11720   MF->insert(MBBIter, BlockMBB);
11721   MF->insert(MBBIter, TailMBB);
11722 
11723   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11724   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11725 
11726   Register DstReg = MI.getOperand(0).getReg();
11727   Register NegSizeReg = MI.getOperand(1).getReg();
11728   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11729   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11730   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11731   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11732 
11733   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11734   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11735   // NegSize.
11736   unsigned ProbeOpc;
11737   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11738     ProbeOpc =
11739         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11740   else
11741     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11742     // and NegSizeReg will be allocated in the same phyreg to avoid
11743     // redundant copy when NegSizeReg has only one use which is current MI and
11744     // will be replaced by PREPARE_PROBED_ALLOCA then.
11745     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11746                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11747   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11748       .addDef(ActualNegSizeReg)
11749       .addReg(NegSizeReg)
11750       .add(MI.getOperand(2))
11751       .add(MI.getOperand(3));
11752 
11753   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11754   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11755           FinalStackPtr)
11756       .addReg(SPReg)
11757       .addReg(ActualNegSizeReg);
11758 
11759   // Materialize a scratch register for update.
11760   int64_t NegProbeSize = -(int64_t)ProbeSize;
11761   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11762   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11763   if (!isInt<16>(NegProbeSize)) {
11764     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11765     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11766         .addImm(NegProbeSize >> 16);
11767     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11768             ScratchReg)
11769         .addReg(TempReg)
11770         .addImm(NegProbeSize & 0xFFFF);
11771   } else
11772     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11773         .addImm(NegProbeSize);
11774 
11775   {
11776     // Probing leading residual part.
11777     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11778     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11779         .addReg(ActualNegSizeReg)
11780         .addReg(ScratchReg);
11781     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11782     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11783         .addReg(Div)
11784         .addReg(ScratchReg);
11785     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11786     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11787         .addReg(Mul)
11788         .addReg(ActualNegSizeReg);
11789     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11790         .addReg(FramePointer)
11791         .addReg(SPReg)
11792         .addReg(NegMod);
11793   }
11794 
11795   {
11796     // Remaining part should be multiple of ProbeSize.
11797     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11798     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11799         .addReg(SPReg)
11800         .addReg(FinalStackPtr);
11801     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11802         .addImm(PPC::PRED_EQ)
11803         .addReg(CmpResult)
11804         .addMBB(TailMBB);
11805     TestMBB->addSuccessor(BlockMBB);
11806     TestMBB->addSuccessor(TailMBB);
11807   }
11808 
11809   {
11810     // Touch the block.
11811     // |P...|P...|P...
11812     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11813         .addReg(FramePointer)
11814         .addReg(SPReg)
11815         .addReg(ScratchReg);
11816     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11817     BlockMBB->addSuccessor(TestMBB);
11818   }
11819 
11820   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11821   // DYNAREAOFFSET pseudo instruction to get the future result.
11822   Register MaxCallFrameSizeReg =
11823       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11824   BuildMI(TailMBB, DL,
11825           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11826           MaxCallFrameSizeReg)
11827       .add(MI.getOperand(2))
11828       .add(MI.getOperand(3));
11829   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11830       .addReg(SPReg)
11831       .addReg(MaxCallFrameSizeReg);
11832 
11833   // Splice instructions after MI to TailMBB.
11834   TailMBB->splice(TailMBB->end(), MBB,
11835                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11836   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11837   MBB->addSuccessor(TestMBB);
11838 
11839   // Delete the pseudo instruction.
11840   MI.eraseFromParent();
11841 
11842   ++NumDynamicAllocaProbed;
11843   return TailMBB;
11844 }
11845 
11846 MachineBasicBlock *
11847 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11848                                                MachineBasicBlock *BB) const {
11849   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11850       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11851     if (Subtarget.is64BitELFABI() &&
11852         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11853         !Subtarget.isUsingPCRelativeCalls()) {
11854       // Call lowering should have added an r2 operand to indicate a dependence
11855       // on the TOC base pointer value. It can't however, because there is no
11856       // way to mark the dependence as implicit there, and so the stackmap code
11857       // will confuse it with a regular operand. Instead, add the dependence
11858       // here.
11859       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11860     }
11861 
11862     return emitPatchPoint(MI, BB);
11863   }
11864 
11865   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11866       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11867     return emitEHSjLjSetJmp(MI, BB);
11868   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11869              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11870     return emitEHSjLjLongJmp(MI, BB);
11871   }
11872 
11873   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11874 
11875   // To "insert" these instructions we actually have to insert their
11876   // control-flow patterns.
11877   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11878   MachineFunction::iterator It = ++BB->getIterator();
11879 
11880   MachineFunction *F = BB->getParent();
11881 
11882   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11883       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11884       MI.getOpcode() == PPC::SELECT_I8) {
11885     SmallVector<MachineOperand, 2> Cond;
11886     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11887         MI.getOpcode() == PPC::SELECT_CC_I8)
11888       Cond.push_back(MI.getOperand(4));
11889     else
11890       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11891     Cond.push_back(MI.getOperand(1));
11892 
11893     DebugLoc dl = MI.getDebugLoc();
11894     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11895                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11896   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11897              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11898              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11899              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11900              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11901              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11902              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11903              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11904              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11905              MI.getOpcode() == PPC::SELECT_F4 ||
11906              MI.getOpcode() == PPC::SELECT_F8 ||
11907              MI.getOpcode() == PPC::SELECT_F16 ||
11908              MI.getOpcode() == PPC::SELECT_SPE ||
11909              MI.getOpcode() == PPC::SELECT_SPE4 ||
11910              MI.getOpcode() == PPC::SELECT_VRRC ||
11911              MI.getOpcode() == PPC::SELECT_VSFRC ||
11912              MI.getOpcode() == PPC::SELECT_VSSRC ||
11913              MI.getOpcode() == PPC::SELECT_VSRC) {
11914     // The incoming instruction knows the destination vreg to set, the
11915     // condition code register to branch on, the true/false values to
11916     // select between, and a branch opcode to use.
11917 
11918     //  thisMBB:
11919     //  ...
11920     //   TrueVal = ...
11921     //   cmpTY ccX, r1, r2
11922     //   bCC copy1MBB
11923     //   fallthrough --> copy0MBB
11924     MachineBasicBlock *thisMBB = BB;
11925     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11926     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11927     DebugLoc dl = MI.getDebugLoc();
11928     F->insert(It, copy0MBB);
11929     F->insert(It, sinkMBB);
11930 
11931     // Transfer the remainder of BB and its successor edges to sinkMBB.
11932     sinkMBB->splice(sinkMBB->begin(), BB,
11933                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11934     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11935 
11936     // Next, add the true and fallthrough blocks as its successors.
11937     BB->addSuccessor(copy0MBB);
11938     BB->addSuccessor(sinkMBB);
11939 
11940     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11941         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11942         MI.getOpcode() == PPC::SELECT_F16 ||
11943         MI.getOpcode() == PPC::SELECT_SPE4 ||
11944         MI.getOpcode() == PPC::SELECT_SPE ||
11945         MI.getOpcode() == PPC::SELECT_VRRC ||
11946         MI.getOpcode() == PPC::SELECT_VSFRC ||
11947         MI.getOpcode() == PPC::SELECT_VSSRC ||
11948         MI.getOpcode() == PPC::SELECT_VSRC) {
11949       BuildMI(BB, dl, TII->get(PPC::BC))
11950           .addReg(MI.getOperand(1).getReg())
11951           .addMBB(sinkMBB);
11952     } else {
11953       unsigned SelectPred = MI.getOperand(4).getImm();
11954       BuildMI(BB, dl, TII->get(PPC::BCC))
11955           .addImm(SelectPred)
11956           .addReg(MI.getOperand(1).getReg())
11957           .addMBB(sinkMBB);
11958     }
11959 
11960     //  copy0MBB:
11961     //   %FalseValue = ...
11962     //   # fallthrough to sinkMBB
11963     BB = copy0MBB;
11964 
11965     // Update machine-CFG edges
11966     BB->addSuccessor(sinkMBB);
11967 
11968     //  sinkMBB:
11969     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11970     //  ...
11971     BB = sinkMBB;
11972     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11973         .addReg(MI.getOperand(3).getReg())
11974         .addMBB(copy0MBB)
11975         .addReg(MI.getOperand(2).getReg())
11976         .addMBB(thisMBB);
11977   } else if (MI.getOpcode() == PPC::ReadTB) {
11978     // To read the 64-bit time-base register on a 32-bit target, we read the
11979     // two halves. Should the counter have wrapped while it was being read, we
11980     // need to try again.
11981     // ...
11982     // readLoop:
11983     // mfspr Rx,TBU # load from TBU
11984     // mfspr Ry,TB  # load from TB
11985     // mfspr Rz,TBU # load from TBU
11986     // cmpw crX,Rx,Rz # check if 'old'='new'
11987     // bne readLoop   # branch if they're not equal
11988     // ...
11989 
11990     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11991     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11992     DebugLoc dl = MI.getDebugLoc();
11993     F->insert(It, readMBB);
11994     F->insert(It, sinkMBB);
11995 
11996     // Transfer the remainder of BB and its successor edges to sinkMBB.
11997     sinkMBB->splice(sinkMBB->begin(), BB,
11998                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11999     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12000 
12001     BB->addSuccessor(readMBB);
12002     BB = readMBB;
12003 
12004     MachineRegisterInfo &RegInfo = F->getRegInfo();
12005     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12006     Register LoReg = MI.getOperand(0).getReg();
12007     Register HiReg = MI.getOperand(1).getReg();
12008 
12009     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12010     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12011     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12012 
12013     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12014 
12015     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12016         .addReg(HiReg)
12017         .addReg(ReadAgainReg);
12018     BuildMI(BB, dl, TII->get(PPC::BCC))
12019         .addImm(PPC::PRED_NE)
12020         .addReg(CmpReg)
12021         .addMBB(readMBB);
12022 
12023     BB->addSuccessor(readMBB);
12024     BB->addSuccessor(sinkMBB);
12025   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12026     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12027   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12028     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12029   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12030     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12031   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12032     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12033 
12034   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12035     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12036   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12037     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12038   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12039     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12040   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12041     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12042 
12043   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12044     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12045   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12046     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12047   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12048     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12049   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12050     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12051 
12052   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12053     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12054   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12055     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12056   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12057     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12058   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12059     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12060 
12061   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12062     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12063   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12064     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12065   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12066     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12067   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12068     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12069 
12070   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12071     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12072   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12073     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12074   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12075     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12076   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12077     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12078 
12079   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12080     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12081   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12082     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12083   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12084     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12085   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12086     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12087 
12088   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12089     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12090   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12091     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12092   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12093     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12094   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12095     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12096 
12097   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12098     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12099   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12100     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12101   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12102     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12103   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12104     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12105 
12106   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12107     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12108   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12109     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12110   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12111     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12112   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12113     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12114 
12115   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12116     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12117   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12118     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12119   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12120     BB = EmitAtomicBinary(MI, BB, 4, 0);
12121   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12122     BB = EmitAtomicBinary(MI, BB, 8, 0);
12123   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12124            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12125            (Subtarget.hasPartwordAtomics() &&
12126             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12127            (Subtarget.hasPartwordAtomics() &&
12128             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12129     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12130 
12131     auto LoadMnemonic = PPC::LDARX;
12132     auto StoreMnemonic = PPC::STDCX;
12133     switch (MI.getOpcode()) {
12134     default:
12135       llvm_unreachable("Compare and swap of unknown size");
12136     case PPC::ATOMIC_CMP_SWAP_I8:
12137       LoadMnemonic = PPC::LBARX;
12138       StoreMnemonic = PPC::STBCX;
12139       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12140       break;
12141     case PPC::ATOMIC_CMP_SWAP_I16:
12142       LoadMnemonic = PPC::LHARX;
12143       StoreMnemonic = PPC::STHCX;
12144       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12145       break;
12146     case PPC::ATOMIC_CMP_SWAP_I32:
12147       LoadMnemonic = PPC::LWARX;
12148       StoreMnemonic = PPC::STWCX;
12149       break;
12150     case PPC::ATOMIC_CMP_SWAP_I64:
12151       LoadMnemonic = PPC::LDARX;
12152       StoreMnemonic = PPC::STDCX;
12153       break;
12154     }
12155     Register dest = MI.getOperand(0).getReg();
12156     Register ptrA = MI.getOperand(1).getReg();
12157     Register ptrB = MI.getOperand(2).getReg();
12158     Register oldval = MI.getOperand(3).getReg();
12159     Register newval = MI.getOperand(4).getReg();
12160     DebugLoc dl = MI.getDebugLoc();
12161 
12162     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12163     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12164     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12165     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12166     F->insert(It, loop1MBB);
12167     F->insert(It, loop2MBB);
12168     F->insert(It, midMBB);
12169     F->insert(It, exitMBB);
12170     exitMBB->splice(exitMBB->begin(), BB,
12171                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12172     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12173 
12174     //  thisMBB:
12175     //   ...
12176     //   fallthrough --> loopMBB
12177     BB->addSuccessor(loop1MBB);
12178 
12179     // loop1MBB:
12180     //   l[bhwd]arx dest, ptr
12181     //   cmp[wd] dest, oldval
12182     //   bne- midMBB
12183     // loop2MBB:
12184     //   st[bhwd]cx. newval, ptr
12185     //   bne- loopMBB
12186     //   b exitBB
12187     // midMBB:
12188     //   st[bhwd]cx. dest, ptr
12189     // exitBB:
12190     BB = loop1MBB;
12191     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12192     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12193         .addReg(oldval)
12194         .addReg(dest);
12195     BuildMI(BB, dl, TII->get(PPC::BCC))
12196         .addImm(PPC::PRED_NE)
12197         .addReg(PPC::CR0)
12198         .addMBB(midMBB);
12199     BB->addSuccessor(loop2MBB);
12200     BB->addSuccessor(midMBB);
12201 
12202     BB = loop2MBB;
12203     BuildMI(BB, dl, TII->get(StoreMnemonic))
12204         .addReg(newval)
12205         .addReg(ptrA)
12206         .addReg(ptrB);
12207     BuildMI(BB, dl, TII->get(PPC::BCC))
12208         .addImm(PPC::PRED_NE)
12209         .addReg(PPC::CR0)
12210         .addMBB(loop1MBB);
12211     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12212     BB->addSuccessor(loop1MBB);
12213     BB->addSuccessor(exitMBB);
12214 
12215     BB = midMBB;
12216     BuildMI(BB, dl, TII->get(StoreMnemonic))
12217         .addReg(dest)
12218         .addReg(ptrA)
12219         .addReg(ptrB);
12220     BB->addSuccessor(exitMBB);
12221 
12222     //  exitMBB:
12223     //   ...
12224     BB = exitMBB;
12225   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12226              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12227     // We must use 64-bit registers for addresses when targeting 64-bit,
12228     // since we're actually doing arithmetic on them.  Other registers
12229     // can be 32-bit.
12230     bool is64bit = Subtarget.isPPC64();
12231     bool isLittleEndian = Subtarget.isLittleEndian();
12232     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12233 
12234     Register dest = MI.getOperand(0).getReg();
12235     Register ptrA = MI.getOperand(1).getReg();
12236     Register ptrB = MI.getOperand(2).getReg();
12237     Register oldval = MI.getOperand(3).getReg();
12238     Register newval = MI.getOperand(4).getReg();
12239     DebugLoc dl = MI.getDebugLoc();
12240 
12241     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12242     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12243     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12244     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12245     F->insert(It, loop1MBB);
12246     F->insert(It, loop2MBB);
12247     F->insert(It, midMBB);
12248     F->insert(It, exitMBB);
12249     exitMBB->splice(exitMBB->begin(), BB,
12250                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12251     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12252 
12253     MachineRegisterInfo &RegInfo = F->getRegInfo();
12254     const TargetRegisterClass *RC =
12255         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12256     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12257 
12258     Register PtrReg = RegInfo.createVirtualRegister(RC);
12259     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12260     Register ShiftReg =
12261         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12262     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12263     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12264     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12265     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12266     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12267     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12268     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12269     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12270     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12271     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12272     Register Ptr1Reg;
12273     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12274     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12275     //  thisMBB:
12276     //   ...
12277     //   fallthrough --> loopMBB
12278     BB->addSuccessor(loop1MBB);
12279 
12280     // The 4-byte load must be aligned, while a char or short may be
12281     // anywhere in the word.  Hence all this nasty bookkeeping code.
12282     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12283     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12284     //   xori shift, shift1, 24 [16]
12285     //   rlwinm ptr, ptr1, 0, 0, 29
12286     //   slw newval2, newval, shift
12287     //   slw oldval2, oldval,shift
12288     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12289     //   slw mask, mask2, shift
12290     //   and newval3, newval2, mask
12291     //   and oldval3, oldval2, mask
12292     // loop1MBB:
12293     //   lwarx tmpDest, ptr
12294     //   and tmp, tmpDest, mask
12295     //   cmpw tmp, oldval3
12296     //   bne- midMBB
12297     // loop2MBB:
12298     //   andc tmp2, tmpDest, mask
12299     //   or tmp4, tmp2, newval3
12300     //   stwcx. tmp4, ptr
12301     //   bne- loop1MBB
12302     //   b exitBB
12303     // midMBB:
12304     //   stwcx. tmpDest, ptr
12305     // exitBB:
12306     //   srw dest, tmpDest, shift
12307     if (ptrA != ZeroReg) {
12308       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12309       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12310           .addReg(ptrA)
12311           .addReg(ptrB);
12312     } else {
12313       Ptr1Reg = ptrB;
12314     }
12315 
12316     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12317     // mode.
12318     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12319         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12320         .addImm(3)
12321         .addImm(27)
12322         .addImm(is8bit ? 28 : 27);
12323     if (!isLittleEndian)
12324       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12325           .addReg(Shift1Reg)
12326           .addImm(is8bit ? 24 : 16);
12327     if (is64bit)
12328       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12329           .addReg(Ptr1Reg)
12330           .addImm(0)
12331           .addImm(61);
12332     else
12333       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12334           .addReg(Ptr1Reg)
12335           .addImm(0)
12336           .addImm(0)
12337           .addImm(29);
12338     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12339         .addReg(newval)
12340         .addReg(ShiftReg);
12341     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12342         .addReg(oldval)
12343         .addReg(ShiftReg);
12344     if (is8bit)
12345       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12346     else {
12347       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12348       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12349           .addReg(Mask3Reg)
12350           .addImm(65535);
12351     }
12352     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12353         .addReg(Mask2Reg)
12354         .addReg(ShiftReg);
12355     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12356         .addReg(NewVal2Reg)
12357         .addReg(MaskReg);
12358     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12359         .addReg(OldVal2Reg)
12360         .addReg(MaskReg);
12361 
12362     BB = loop1MBB;
12363     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12364         .addReg(ZeroReg)
12365         .addReg(PtrReg);
12366     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12367         .addReg(TmpDestReg)
12368         .addReg(MaskReg);
12369     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12370         .addReg(TmpReg)
12371         .addReg(OldVal3Reg);
12372     BuildMI(BB, dl, TII->get(PPC::BCC))
12373         .addImm(PPC::PRED_NE)
12374         .addReg(PPC::CR0)
12375         .addMBB(midMBB);
12376     BB->addSuccessor(loop2MBB);
12377     BB->addSuccessor(midMBB);
12378 
12379     BB = loop2MBB;
12380     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12381         .addReg(TmpDestReg)
12382         .addReg(MaskReg);
12383     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12384         .addReg(Tmp2Reg)
12385         .addReg(NewVal3Reg);
12386     BuildMI(BB, dl, TII->get(PPC::STWCX))
12387         .addReg(Tmp4Reg)
12388         .addReg(ZeroReg)
12389         .addReg(PtrReg);
12390     BuildMI(BB, dl, TII->get(PPC::BCC))
12391         .addImm(PPC::PRED_NE)
12392         .addReg(PPC::CR0)
12393         .addMBB(loop1MBB);
12394     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12395     BB->addSuccessor(loop1MBB);
12396     BB->addSuccessor(exitMBB);
12397 
12398     BB = midMBB;
12399     BuildMI(BB, dl, TII->get(PPC::STWCX))
12400         .addReg(TmpDestReg)
12401         .addReg(ZeroReg)
12402         .addReg(PtrReg);
12403     BB->addSuccessor(exitMBB);
12404 
12405     //  exitMBB:
12406     //   ...
12407     BB = exitMBB;
12408     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12409         .addReg(TmpReg)
12410         .addReg(ShiftReg);
12411   } else if (MI.getOpcode() == PPC::FADDrtz) {
12412     // This pseudo performs an FADD with rounding mode temporarily forced
12413     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12414     // is not modeled at the SelectionDAG level.
12415     Register Dest = MI.getOperand(0).getReg();
12416     Register Src1 = MI.getOperand(1).getReg();
12417     Register Src2 = MI.getOperand(2).getReg();
12418     DebugLoc dl = MI.getDebugLoc();
12419 
12420     MachineRegisterInfo &RegInfo = F->getRegInfo();
12421     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12422 
12423     // Save FPSCR value.
12424     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12425 
12426     // Set rounding mode to round-to-zero.
12427     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12428         .addImm(31)
12429         .addReg(PPC::RM, RegState::ImplicitDefine);
12430 
12431     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12432         .addImm(30)
12433         .addReg(PPC::RM, RegState::ImplicitDefine);
12434 
12435     // Perform addition.
12436     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12437                    .addReg(Src1)
12438                    .addReg(Src2);
12439     if (MI.getFlag(MachineInstr::NoFPExcept))
12440       MIB.setMIFlag(MachineInstr::NoFPExcept);
12441 
12442     // Restore FPSCR value.
12443     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12444   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12445              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12446              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12447              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12448     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12449                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12450                           ? PPC::ANDI8_rec
12451                           : PPC::ANDI_rec;
12452     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12453                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12454 
12455     MachineRegisterInfo &RegInfo = F->getRegInfo();
12456     Register Dest = RegInfo.createVirtualRegister(
12457         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12458 
12459     DebugLoc Dl = MI.getDebugLoc();
12460     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12461         .addReg(MI.getOperand(1).getReg())
12462         .addImm(1);
12463     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12464             MI.getOperand(0).getReg())
12465         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12466   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12467     DebugLoc Dl = MI.getDebugLoc();
12468     MachineRegisterInfo &RegInfo = F->getRegInfo();
12469     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12470     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12471     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12472             MI.getOperand(0).getReg())
12473         .addReg(CRReg);
12474   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12475     DebugLoc Dl = MI.getDebugLoc();
12476     unsigned Imm = MI.getOperand(1).getImm();
12477     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12478     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12479             MI.getOperand(0).getReg())
12480         .addReg(PPC::CR0EQ);
12481   } else if (MI.getOpcode() == PPC::SETRNDi) {
12482     DebugLoc dl = MI.getDebugLoc();
12483     Register OldFPSCRReg = MI.getOperand(0).getReg();
12484 
12485     // Save FPSCR value.
12486     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12487 
12488     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12489     // the following settings:
12490     //   00 Round to nearest
12491     //   01 Round to 0
12492     //   10 Round to +inf
12493     //   11 Round to -inf
12494 
12495     // When the operand is immediate, using the two least significant bits of
12496     // the immediate to set the bits 62:63 of FPSCR.
12497     unsigned Mode = MI.getOperand(1).getImm();
12498     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12499         .addImm(31)
12500         .addReg(PPC::RM, RegState::ImplicitDefine);
12501 
12502     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12503         .addImm(30)
12504         .addReg(PPC::RM, RegState::ImplicitDefine);
12505   } else if (MI.getOpcode() == PPC::SETRND) {
12506     DebugLoc dl = MI.getDebugLoc();
12507 
12508     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12509     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12510     // If the target doesn't have DirectMove, we should use stack to do the
12511     // conversion, because the target doesn't have the instructions like mtvsrd
12512     // or mfvsrd to do this conversion directly.
12513     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12514       if (Subtarget.hasDirectMove()) {
12515         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12516           .addReg(SrcReg);
12517       } else {
12518         // Use stack to do the register copy.
12519         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12520         MachineRegisterInfo &RegInfo = F->getRegInfo();
12521         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12522         if (RC == &PPC::F8RCRegClass) {
12523           // Copy register from F8RCRegClass to G8RCRegclass.
12524           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12525                  "Unsupported RegClass.");
12526 
12527           StoreOp = PPC::STFD;
12528           LoadOp = PPC::LD;
12529         } else {
12530           // Copy register from G8RCRegClass to F8RCRegclass.
12531           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12532                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12533                  "Unsupported RegClass.");
12534         }
12535 
12536         MachineFrameInfo &MFI = F->getFrameInfo();
12537         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12538 
12539         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12540             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12541             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12542             MFI.getObjectAlign(FrameIdx));
12543 
12544         // Store the SrcReg into the stack.
12545         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12546           .addReg(SrcReg)
12547           .addImm(0)
12548           .addFrameIndex(FrameIdx)
12549           .addMemOperand(MMOStore);
12550 
12551         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12552             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12553             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12554             MFI.getObjectAlign(FrameIdx));
12555 
12556         // Load from the stack where SrcReg is stored, and save to DestReg,
12557         // so we have done the RegClass conversion from RegClass::SrcReg to
12558         // RegClass::DestReg.
12559         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12560           .addImm(0)
12561           .addFrameIndex(FrameIdx)
12562           .addMemOperand(MMOLoad);
12563       }
12564     };
12565 
12566     Register OldFPSCRReg = MI.getOperand(0).getReg();
12567 
12568     // Save FPSCR value.
12569     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12570 
12571     // When the operand is gprc register, use two least significant bits of the
12572     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12573     //
12574     // copy OldFPSCRTmpReg, OldFPSCRReg
12575     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12576     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12577     // copy NewFPSCRReg, NewFPSCRTmpReg
12578     // mtfsf 255, NewFPSCRReg
12579     MachineOperand SrcOp = MI.getOperand(1);
12580     MachineRegisterInfo &RegInfo = F->getRegInfo();
12581     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12582 
12583     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12584 
12585     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12586     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12587 
12588     // The first operand of INSERT_SUBREG should be a register which has
12589     // subregisters, we only care about its RegClass, so we should use an
12590     // IMPLICIT_DEF register.
12591     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12592     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12593       .addReg(ImDefReg)
12594       .add(SrcOp)
12595       .addImm(1);
12596 
12597     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12598     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12599       .addReg(OldFPSCRTmpReg)
12600       .addReg(ExtSrcReg)
12601       .addImm(0)
12602       .addImm(62);
12603 
12604     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12605     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12606 
12607     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12608     // bits of FPSCR.
12609     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12610       .addImm(255)
12611       .addReg(NewFPSCRReg)
12612       .addImm(0)
12613       .addImm(0);
12614   } else if (MI.getOpcode() == PPC::SETFLM) {
12615     DebugLoc Dl = MI.getDebugLoc();
12616 
12617     // Result of setflm is previous FPSCR content, so we need to save it first.
12618     Register OldFPSCRReg = MI.getOperand(0).getReg();
12619     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12620 
12621     // Put bits in 32:63 to FPSCR.
12622     Register NewFPSCRReg = MI.getOperand(1).getReg();
12623     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12624         .addImm(255)
12625         .addReg(NewFPSCRReg)
12626         .addImm(0)
12627         .addImm(0);
12628   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12629              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12630     return emitProbedAlloca(MI, BB);
12631   } else {
12632     llvm_unreachable("Unexpected instr type to insert");
12633   }
12634 
12635   MI.eraseFromParent(); // The pseudo instruction is gone now.
12636   return BB;
12637 }
12638 
12639 //===----------------------------------------------------------------------===//
12640 // Target Optimization Hooks
12641 //===----------------------------------------------------------------------===//
12642 
12643 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12644   // For the estimates, convergence is quadratic, so we essentially double the
12645   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12646   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12647   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12648   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12649   if (VT.getScalarType() == MVT::f64)
12650     RefinementSteps++;
12651   return RefinementSteps;
12652 }
12653 
12654 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12655                                             const DenormalMode &Mode) const {
12656   // We only have VSX Vector Test for software Square Root.
12657   EVT VT = Op.getValueType();
12658   if (!isTypeLegal(MVT::i1) ||
12659       (VT != MVT::f64 &&
12660        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12661     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12662 
12663   SDLoc DL(Op);
12664   // The output register of FTSQRT is CR field.
12665   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12666   // ftsqrt BF,FRB
12667   // Let e_b be the unbiased exponent of the double-precision
12668   // floating-point operand in register FRB.
12669   // fe_flag is set to 1 if either of the following conditions occurs.
12670   //   - The double-precision floating-point operand in register FRB is a zero,
12671   //     a NaN, or an infinity, or a negative value.
12672   //   - e_b is less than or equal to -970.
12673   // Otherwise fe_flag is set to 0.
12674   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12675   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12676   // exponent is less than -970)
12677   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12678   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12679                                     FTSQRT, SRIdxVal),
12680                  0);
12681 }
12682 
12683 SDValue
12684 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12685                                                SelectionDAG &DAG) const {
12686   // We only have VSX Vector Square Root.
12687   EVT VT = Op.getValueType();
12688   if (VT != MVT::f64 &&
12689       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12690     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12691 
12692   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12693 }
12694 
12695 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12696                                            int Enabled, int &RefinementSteps,
12697                                            bool &UseOneConstNR,
12698                                            bool Reciprocal) const {
12699   EVT VT = Operand.getValueType();
12700   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12701       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12702       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12703       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12704     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12705       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12706 
12707     // The Newton-Raphson computation with a single constant does not provide
12708     // enough accuracy on some CPUs.
12709     UseOneConstNR = !Subtarget.needsTwoConstNR();
12710     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12711   }
12712   return SDValue();
12713 }
12714 
12715 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12716                                             int Enabled,
12717                                             int &RefinementSteps) const {
12718   EVT VT = Operand.getValueType();
12719   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12720       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12721       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12722       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12723     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12724       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12725     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12726   }
12727   return SDValue();
12728 }
12729 
12730 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12731   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12732   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12733   // enabled for division), this functionality is redundant with the default
12734   // combiner logic (once the division -> reciprocal/multiply transformation
12735   // has taken place). As a result, this matters more for older cores than for
12736   // newer ones.
12737 
12738   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12739   // reciprocal if there are two or more FDIVs (for embedded cores with only
12740   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12741   switch (Subtarget.getCPUDirective()) {
12742   default:
12743     return 3;
12744   case PPC::DIR_440:
12745   case PPC::DIR_A2:
12746   case PPC::DIR_E500:
12747   case PPC::DIR_E500mc:
12748   case PPC::DIR_E5500:
12749     return 2;
12750   }
12751 }
12752 
12753 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12754 // collapsed, and so we need to look through chains of them.
12755 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12756                                      int64_t& Offset, SelectionDAG &DAG) {
12757   if (DAG.isBaseWithConstantOffset(Loc)) {
12758     Base = Loc.getOperand(0);
12759     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12760 
12761     // The base might itself be a base plus an offset, and if so, accumulate
12762     // that as well.
12763     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12764   }
12765 }
12766 
12767 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12768                             unsigned Bytes, int Dist,
12769                             SelectionDAG &DAG) {
12770   if (VT.getSizeInBits() / 8 != Bytes)
12771     return false;
12772 
12773   SDValue BaseLoc = Base->getBasePtr();
12774   if (Loc.getOpcode() == ISD::FrameIndex) {
12775     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12776       return false;
12777     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12778     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12779     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12780     int FS  = MFI.getObjectSize(FI);
12781     int BFS = MFI.getObjectSize(BFI);
12782     if (FS != BFS || FS != (int)Bytes) return false;
12783     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12784   }
12785 
12786   SDValue Base1 = Loc, Base2 = BaseLoc;
12787   int64_t Offset1 = 0, Offset2 = 0;
12788   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12789   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12790   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12791     return true;
12792 
12793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12794   const GlobalValue *GV1 = nullptr;
12795   const GlobalValue *GV2 = nullptr;
12796   Offset1 = 0;
12797   Offset2 = 0;
12798   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12799   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12800   if (isGA1 && isGA2 && GV1 == GV2)
12801     return Offset1 == (Offset2 + Dist*Bytes);
12802   return false;
12803 }
12804 
12805 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12806 // not enforce equality of the chain operands.
12807 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12808                             unsigned Bytes, int Dist,
12809                             SelectionDAG &DAG) {
12810   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12811     EVT VT = LS->getMemoryVT();
12812     SDValue Loc = LS->getBasePtr();
12813     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12814   }
12815 
12816   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12817     EVT VT;
12818     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12819     default: return false;
12820     case Intrinsic::ppc_altivec_lvx:
12821     case Intrinsic::ppc_altivec_lvxl:
12822     case Intrinsic::ppc_vsx_lxvw4x:
12823     case Intrinsic::ppc_vsx_lxvw4x_be:
12824       VT = MVT::v4i32;
12825       break;
12826     case Intrinsic::ppc_vsx_lxvd2x:
12827     case Intrinsic::ppc_vsx_lxvd2x_be:
12828       VT = MVT::v2f64;
12829       break;
12830     case Intrinsic::ppc_altivec_lvebx:
12831       VT = MVT::i8;
12832       break;
12833     case Intrinsic::ppc_altivec_lvehx:
12834       VT = MVT::i16;
12835       break;
12836     case Intrinsic::ppc_altivec_lvewx:
12837       VT = MVT::i32;
12838       break;
12839     }
12840 
12841     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12842   }
12843 
12844   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12845     EVT VT;
12846     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12847     default: return false;
12848     case Intrinsic::ppc_altivec_stvx:
12849     case Intrinsic::ppc_altivec_stvxl:
12850     case Intrinsic::ppc_vsx_stxvw4x:
12851       VT = MVT::v4i32;
12852       break;
12853     case Intrinsic::ppc_vsx_stxvd2x:
12854       VT = MVT::v2f64;
12855       break;
12856     case Intrinsic::ppc_vsx_stxvw4x_be:
12857       VT = MVT::v4i32;
12858       break;
12859     case Intrinsic::ppc_vsx_stxvd2x_be:
12860       VT = MVT::v2f64;
12861       break;
12862     case Intrinsic::ppc_altivec_stvebx:
12863       VT = MVT::i8;
12864       break;
12865     case Intrinsic::ppc_altivec_stvehx:
12866       VT = MVT::i16;
12867       break;
12868     case Intrinsic::ppc_altivec_stvewx:
12869       VT = MVT::i32;
12870       break;
12871     }
12872 
12873     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12874   }
12875 
12876   return false;
12877 }
12878 
12879 // Return true is there is a nearyby consecutive load to the one provided
12880 // (regardless of alignment). We search up and down the chain, looking though
12881 // token factors and other loads (but nothing else). As a result, a true result
12882 // indicates that it is safe to create a new consecutive load adjacent to the
12883 // load provided.
12884 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12885   SDValue Chain = LD->getChain();
12886   EVT VT = LD->getMemoryVT();
12887 
12888   SmallSet<SDNode *, 16> LoadRoots;
12889   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12890   SmallSet<SDNode *, 16> Visited;
12891 
12892   // First, search up the chain, branching to follow all token-factor operands.
12893   // If we find a consecutive load, then we're done, otherwise, record all
12894   // nodes just above the top-level loads and token factors.
12895   while (!Queue.empty()) {
12896     SDNode *ChainNext = Queue.pop_back_val();
12897     if (!Visited.insert(ChainNext).second)
12898       continue;
12899 
12900     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12901       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12902         return true;
12903 
12904       if (!Visited.count(ChainLD->getChain().getNode()))
12905         Queue.push_back(ChainLD->getChain().getNode());
12906     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12907       for (const SDUse &O : ChainNext->ops())
12908         if (!Visited.count(O.getNode()))
12909           Queue.push_back(O.getNode());
12910     } else
12911       LoadRoots.insert(ChainNext);
12912   }
12913 
12914   // Second, search down the chain, starting from the top-level nodes recorded
12915   // in the first phase. These top-level nodes are the nodes just above all
12916   // loads and token factors. Starting with their uses, recursively look though
12917   // all loads (just the chain uses) and token factors to find a consecutive
12918   // load.
12919   Visited.clear();
12920   Queue.clear();
12921 
12922   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12923        IE = LoadRoots.end(); I != IE; ++I) {
12924     Queue.push_back(*I);
12925 
12926     while (!Queue.empty()) {
12927       SDNode *LoadRoot = Queue.pop_back_val();
12928       if (!Visited.insert(LoadRoot).second)
12929         continue;
12930 
12931       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12932         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12933           return true;
12934 
12935       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12936            UE = LoadRoot->use_end(); UI != UE; ++UI)
12937         if (((isa<MemSDNode>(*UI) &&
12938             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12939             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12940           Queue.push_back(*UI);
12941     }
12942   }
12943 
12944   return false;
12945 }
12946 
12947 /// This function is called when we have proved that a SETCC node can be replaced
12948 /// by subtraction (and other supporting instructions) so that the result of
12949 /// comparison is kept in a GPR instead of CR. This function is purely for
12950 /// codegen purposes and has some flags to guide the codegen process.
12951 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12952                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12953   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12954 
12955   // Zero extend the operands to the largest legal integer. Originally, they
12956   // must be of a strictly smaller size.
12957   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12958                          DAG.getConstant(Size, DL, MVT::i32));
12959   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12960                          DAG.getConstant(Size, DL, MVT::i32));
12961 
12962   // Swap if needed. Depends on the condition code.
12963   if (Swap)
12964     std::swap(Op0, Op1);
12965 
12966   // Subtract extended integers.
12967   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12968 
12969   // Move the sign bit to the least significant position and zero out the rest.
12970   // Now the least significant bit carries the result of original comparison.
12971   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12972                              DAG.getConstant(Size - 1, DL, MVT::i32));
12973   auto Final = Shifted;
12974 
12975   // Complement the result if needed. Based on the condition code.
12976   if (Complement)
12977     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12978                         DAG.getConstant(1, DL, MVT::i64));
12979 
12980   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12981 }
12982 
12983 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12984                                                   DAGCombinerInfo &DCI) const {
12985   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12986 
12987   SelectionDAG &DAG = DCI.DAG;
12988   SDLoc DL(N);
12989 
12990   // Size of integers being compared has a critical role in the following
12991   // analysis, so we prefer to do this when all types are legal.
12992   if (!DCI.isAfterLegalizeDAG())
12993     return SDValue();
12994 
12995   // If all users of SETCC extend its value to a legal integer type
12996   // then we replace SETCC with a subtraction
12997   for (SDNode::use_iterator UI = N->use_begin(),
12998        UE = N->use_end(); UI != UE; ++UI) {
12999     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13000       return SDValue();
13001   }
13002 
13003   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13004   auto OpSize = N->getOperand(0).getValueSizeInBits();
13005 
13006   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13007 
13008   if (OpSize < Size) {
13009     switch (CC) {
13010     default: break;
13011     case ISD::SETULT:
13012       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13013     case ISD::SETULE:
13014       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13015     case ISD::SETUGT:
13016       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13017     case ISD::SETUGE:
13018       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13019     }
13020   }
13021 
13022   return SDValue();
13023 }
13024 
13025 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13026                                                   DAGCombinerInfo &DCI) const {
13027   SelectionDAG &DAG = DCI.DAG;
13028   SDLoc dl(N);
13029 
13030   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13031   // If we're tracking CR bits, we need to be careful that we don't have:
13032   //   trunc(binary-ops(zext(x), zext(y)))
13033   // or
13034   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13035   // such that we're unnecessarily moving things into GPRs when it would be
13036   // better to keep them in CR bits.
13037 
13038   // Note that trunc here can be an actual i1 trunc, or can be the effective
13039   // truncation that comes from a setcc or select_cc.
13040   if (N->getOpcode() == ISD::TRUNCATE &&
13041       N->getValueType(0) != MVT::i1)
13042     return SDValue();
13043 
13044   if (N->getOperand(0).getValueType() != MVT::i32 &&
13045       N->getOperand(0).getValueType() != MVT::i64)
13046     return SDValue();
13047 
13048   if (N->getOpcode() == ISD::SETCC ||
13049       N->getOpcode() == ISD::SELECT_CC) {
13050     // If we're looking at a comparison, then we need to make sure that the
13051     // high bits (all except for the first) don't matter the result.
13052     ISD::CondCode CC =
13053       cast<CondCodeSDNode>(N->getOperand(
13054         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13055     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13056 
13057     if (ISD::isSignedIntSetCC(CC)) {
13058       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13059           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13060         return SDValue();
13061     } else if (ISD::isUnsignedIntSetCC(CC)) {
13062       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13063                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13064           !DAG.MaskedValueIsZero(N->getOperand(1),
13065                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13066         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13067                                              : SDValue());
13068     } else {
13069       // This is neither a signed nor an unsigned comparison, just make sure
13070       // that the high bits are equal.
13071       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13072       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13073 
13074       // We don't really care about what is known about the first bit (if
13075       // anything), so pretend that it is known zero for both to ensure they can
13076       // be compared as constants.
13077       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13078       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13079 
13080       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13081           Op1Known.getConstant() != Op2Known.getConstant())
13082         return SDValue();
13083     }
13084   }
13085 
13086   // We now know that the higher-order bits are irrelevant, we just need to
13087   // make sure that all of the intermediate operations are bit operations, and
13088   // all inputs are extensions.
13089   if (N->getOperand(0).getOpcode() != ISD::AND &&
13090       N->getOperand(0).getOpcode() != ISD::OR  &&
13091       N->getOperand(0).getOpcode() != ISD::XOR &&
13092       N->getOperand(0).getOpcode() != ISD::SELECT &&
13093       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13094       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13095       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13096       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13097       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13098     return SDValue();
13099 
13100   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13101       N->getOperand(1).getOpcode() != ISD::AND &&
13102       N->getOperand(1).getOpcode() != ISD::OR  &&
13103       N->getOperand(1).getOpcode() != ISD::XOR &&
13104       N->getOperand(1).getOpcode() != ISD::SELECT &&
13105       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13106       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13107       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13108       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13109       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13110     return SDValue();
13111 
13112   SmallVector<SDValue, 4> Inputs;
13113   SmallVector<SDValue, 8> BinOps, PromOps;
13114   SmallPtrSet<SDNode *, 16> Visited;
13115 
13116   for (unsigned i = 0; i < 2; ++i) {
13117     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13118           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13119           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13120           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13121         isa<ConstantSDNode>(N->getOperand(i)))
13122       Inputs.push_back(N->getOperand(i));
13123     else
13124       BinOps.push_back(N->getOperand(i));
13125 
13126     if (N->getOpcode() == ISD::TRUNCATE)
13127       break;
13128   }
13129 
13130   // Visit all inputs, collect all binary operations (and, or, xor and
13131   // select) that are all fed by extensions.
13132   while (!BinOps.empty()) {
13133     SDValue BinOp = BinOps.pop_back_val();
13134 
13135     if (!Visited.insert(BinOp.getNode()).second)
13136       continue;
13137 
13138     PromOps.push_back(BinOp);
13139 
13140     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13141       // The condition of the select is not promoted.
13142       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13143         continue;
13144       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13145         continue;
13146 
13147       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13148             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13149             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13150            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13151           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13152         Inputs.push_back(BinOp.getOperand(i));
13153       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13154                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13155                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13156                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13157                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13158                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13159                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13160                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13161                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13162         BinOps.push_back(BinOp.getOperand(i));
13163       } else {
13164         // We have an input that is not an extension or another binary
13165         // operation; we'll abort this transformation.
13166         return SDValue();
13167       }
13168     }
13169   }
13170 
13171   // Make sure that this is a self-contained cluster of operations (which
13172   // is not quite the same thing as saying that everything has only one
13173   // use).
13174   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13175     if (isa<ConstantSDNode>(Inputs[i]))
13176       continue;
13177 
13178     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13179                               UE = Inputs[i].getNode()->use_end();
13180          UI != UE; ++UI) {
13181       SDNode *User = *UI;
13182       if (User != N && !Visited.count(User))
13183         return SDValue();
13184 
13185       // Make sure that we're not going to promote the non-output-value
13186       // operand(s) or SELECT or SELECT_CC.
13187       // FIXME: Although we could sometimes handle this, and it does occur in
13188       // practice that one of the condition inputs to the select is also one of
13189       // the outputs, we currently can't deal with this.
13190       if (User->getOpcode() == ISD::SELECT) {
13191         if (User->getOperand(0) == Inputs[i])
13192           return SDValue();
13193       } else if (User->getOpcode() == ISD::SELECT_CC) {
13194         if (User->getOperand(0) == Inputs[i] ||
13195             User->getOperand(1) == Inputs[i])
13196           return SDValue();
13197       }
13198     }
13199   }
13200 
13201   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13202     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13203                               UE = PromOps[i].getNode()->use_end();
13204          UI != UE; ++UI) {
13205       SDNode *User = *UI;
13206       if (User != N && !Visited.count(User))
13207         return SDValue();
13208 
13209       // Make sure that we're not going to promote the non-output-value
13210       // operand(s) or SELECT or SELECT_CC.
13211       // FIXME: Although we could sometimes handle this, and it does occur in
13212       // practice that one of the condition inputs to the select is also one of
13213       // the outputs, we currently can't deal with this.
13214       if (User->getOpcode() == ISD::SELECT) {
13215         if (User->getOperand(0) == PromOps[i])
13216           return SDValue();
13217       } else if (User->getOpcode() == ISD::SELECT_CC) {
13218         if (User->getOperand(0) == PromOps[i] ||
13219             User->getOperand(1) == PromOps[i])
13220           return SDValue();
13221       }
13222     }
13223   }
13224 
13225   // Replace all inputs with the extension operand.
13226   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13227     // Constants may have users outside the cluster of to-be-promoted nodes,
13228     // and so we need to replace those as we do the promotions.
13229     if (isa<ConstantSDNode>(Inputs[i]))
13230       continue;
13231     else
13232       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13233   }
13234 
13235   std::list<HandleSDNode> PromOpHandles;
13236   for (auto &PromOp : PromOps)
13237     PromOpHandles.emplace_back(PromOp);
13238 
13239   // Replace all operations (these are all the same, but have a different
13240   // (i1) return type). DAG.getNode will validate that the types of
13241   // a binary operator match, so go through the list in reverse so that
13242   // we've likely promoted both operands first. Any intermediate truncations or
13243   // extensions disappear.
13244   while (!PromOpHandles.empty()) {
13245     SDValue PromOp = PromOpHandles.back().getValue();
13246     PromOpHandles.pop_back();
13247 
13248     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13249         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13250         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13251         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13252       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13253           PromOp.getOperand(0).getValueType() != MVT::i1) {
13254         // The operand is not yet ready (see comment below).
13255         PromOpHandles.emplace_front(PromOp);
13256         continue;
13257       }
13258 
13259       SDValue RepValue = PromOp.getOperand(0);
13260       if (isa<ConstantSDNode>(RepValue))
13261         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13262 
13263       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13264       continue;
13265     }
13266 
13267     unsigned C;
13268     switch (PromOp.getOpcode()) {
13269     default:             C = 0; break;
13270     case ISD::SELECT:    C = 1; break;
13271     case ISD::SELECT_CC: C = 2; break;
13272     }
13273 
13274     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13275          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13276         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13277          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13278       // The to-be-promoted operands of this node have not yet been
13279       // promoted (this should be rare because we're going through the
13280       // list backward, but if one of the operands has several users in
13281       // this cluster of to-be-promoted nodes, it is possible).
13282       PromOpHandles.emplace_front(PromOp);
13283       continue;
13284     }
13285 
13286     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13287                                 PromOp.getNode()->op_end());
13288 
13289     // If there are any constant inputs, make sure they're replaced now.
13290     for (unsigned i = 0; i < 2; ++i)
13291       if (isa<ConstantSDNode>(Ops[C+i]))
13292         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13293 
13294     DAG.ReplaceAllUsesOfValueWith(PromOp,
13295       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13296   }
13297 
13298   // Now we're left with the initial truncation itself.
13299   if (N->getOpcode() == ISD::TRUNCATE)
13300     return N->getOperand(0);
13301 
13302   // Otherwise, this is a comparison. The operands to be compared have just
13303   // changed type (to i1), but everything else is the same.
13304   return SDValue(N, 0);
13305 }
13306 
13307 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13308                                                   DAGCombinerInfo &DCI) const {
13309   SelectionDAG &DAG = DCI.DAG;
13310   SDLoc dl(N);
13311 
13312   // If we're tracking CR bits, we need to be careful that we don't have:
13313   //   zext(binary-ops(trunc(x), trunc(y)))
13314   // or
13315   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13316   // such that we're unnecessarily moving things into CR bits that can more
13317   // efficiently stay in GPRs. Note that if we're not certain that the high
13318   // bits are set as required by the final extension, we still may need to do
13319   // some masking to get the proper behavior.
13320 
13321   // This same functionality is important on PPC64 when dealing with
13322   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13323   // the return values of functions. Because it is so similar, it is handled
13324   // here as well.
13325 
13326   if (N->getValueType(0) != MVT::i32 &&
13327       N->getValueType(0) != MVT::i64)
13328     return SDValue();
13329 
13330   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13331         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13332     return SDValue();
13333 
13334   if (N->getOperand(0).getOpcode() != ISD::AND &&
13335       N->getOperand(0).getOpcode() != ISD::OR  &&
13336       N->getOperand(0).getOpcode() != ISD::XOR &&
13337       N->getOperand(0).getOpcode() != ISD::SELECT &&
13338       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13339     return SDValue();
13340 
13341   SmallVector<SDValue, 4> Inputs;
13342   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13343   SmallPtrSet<SDNode *, 16> Visited;
13344 
13345   // Visit all inputs, collect all binary operations (and, or, xor and
13346   // select) that are all fed by truncations.
13347   while (!BinOps.empty()) {
13348     SDValue BinOp = BinOps.pop_back_val();
13349 
13350     if (!Visited.insert(BinOp.getNode()).second)
13351       continue;
13352 
13353     PromOps.push_back(BinOp);
13354 
13355     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13356       // The condition of the select is not promoted.
13357       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13358         continue;
13359       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13360         continue;
13361 
13362       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13363           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13364         Inputs.push_back(BinOp.getOperand(i));
13365       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13366                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13367                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13368                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13369                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13370         BinOps.push_back(BinOp.getOperand(i));
13371       } else {
13372         // We have an input that is not a truncation or another binary
13373         // operation; we'll abort this transformation.
13374         return SDValue();
13375       }
13376     }
13377   }
13378 
13379   // The operands of a select that must be truncated when the select is
13380   // promoted because the operand is actually part of the to-be-promoted set.
13381   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13382 
13383   // Make sure that this is a self-contained cluster of operations (which
13384   // is not quite the same thing as saying that everything has only one
13385   // use).
13386   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13387     if (isa<ConstantSDNode>(Inputs[i]))
13388       continue;
13389 
13390     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13391                               UE = Inputs[i].getNode()->use_end();
13392          UI != UE; ++UI) {
13393       SDNode *User = *UI;
13394       if (User != N && !Visited.count(User))
13395         return SDValue();
13396 
13397       // If we're going to promote the non-output-value operand(s) or SELECT or
13398       // SELECT_CC, record them for truncation.
13399       if (User->getOpcode() == ISD::SELECT) {
13400         if (User->getOperand(0) == Inputs[i])
13401           SelectTruncOp[0].insert(std::make_pair(User,
13402                                     User->getOperand(0).getValueType()));
13403       } else if (User->getOpcode() == ISD::SELECT_CC) {
13404         if (User->getOperand(0) == Inputs[i])
13405           SelectTruncOp[0].insert(std::make_pair(User,
13406                                     User->getOperand(0).getValueType()));
13407         if (User->getOperand(1) == Inputs[i])
13408           SelectTruncOp[1].insert(std::make_pair(User,
13409                                     User->getOperand(1).getValueType()));
13410       }
13411     }
13412   }
13413 
13414   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13415     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13416                               UE = PromOps[i].getNode()->use_end();
13417          UI != UE; ++UI) {
13418       SDNode *User = *UI;
13419       if (User != N && !Visited.count(User))
13420         return SDValue();
13421 
13422       // If we're going to promote the non-output-value operand(s) or SELECT or
13423       // SELECT_CC, record them for truncation.
13424       if (User->getOpcode() == ISD::SELECT) {
13425         if (User->getOperand(0) == PromOps[i])
13426           SelectTruncOp[0].insert(std::make_pair(User,
13427                                     User->getOperand(0).getValueType()));
13428       } else if (User->getOpcode() == ISD::SELECT_CC) {
13429         if (User->getOperand(0) == PromOps[i])
13430           SelectTruncOp[0].insert(std::make_pair(User,
13431                                     User->getOperand(0).getValueType()));
13432         if (User->getOperand(1) == PromOps[i])
13433           SelectTruncOp[1].insert(std::make_pair(User,
13434                                     User->getOperand(1).getValueType()));
13435       }
13436     }
13437   }
13438 
13439   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13440   bool ReallyNeedsExt = false;
13441   if (N->getOpcode() != ISD::ANY_EXTEND) {
13442     // If all of the inputs are not already sign/zero extended, then
13443     // we'll still need to do that at the end.
13444     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13445       if (isa<ConstantSDNode>(Inputs[i]))
13446         continue;
13447 
13448       unsigned OpBits =
13449         Inputs[i].getOperand(0).getValueSizeInBits();
13450       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13451 
13452       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13453            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13454                                   APInt::getHighBitsSet(OpBits,
13455                                                         OpBits-PromBits))) ||
13456           (N->getOpcode() == ISD::SIGN_EXTEND &&
13457            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13458              (OpBits-(PromBits-1)))) {
13459         ReallyNeedsExt = true;
13460         break;
13461       }
13462     }
13463   }
13464 
13465   // Replace all inputs, either with the truncation operand, or a
13466   // truncation or extension to the final output type.
13467   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13468     // Constant inputs need to be replaced with the to-be-promoted nodes that
13469     // use them because they might have users outside of the cluster of
13470     // promoted nodes.
13471     if (isa<ConstantSDNode>(Inputs[i]))
13472       continue;
13473 
13474     SDValue InSrc = Inputs[i].getOperand(0);
13475     if (Inputs[i].getValueType() == N->getValueType(0))
13476       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13477     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13478       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13479         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13480     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13481       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13482         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13483     else
13484       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13485         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13486   }
13487 
13488   std::list<HandleSDNode> PromOpHandles;
13489   for (auto &PromOp : PromOps)
13490     PromOpHandles.emplace_back(PromOp);
13491 
13492   // Replace all operations (these are all the same, but have a different
13493   // (promoted) return type). DAG.getNode will validate that the types of
13494   // a binary operator match, so go through the list in reverse so that
13495   // we've likely promoted both operands first.
13496   while (!PromOpHandles.empty()) {
13497     SDValue PromOp = PromOpHandles.back().getValue();
13498     PromOpHandles.pop_back();
13499 
13500     unsigned C;
13501     switch (PromOp.getOpcode()) {
13502     default:             C = 0; break;
13503     case ISD::SELECT:    C = 1; break;
13504     case ISD::SELECT_CC: C = 2; break;
13505     }
13506 
13507     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13508          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13509         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13510          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13511       // The to-be-promoted operands of this node have not yet been
13512       // promoted (this should be rare because we're going through the
13513       // list backward, but if one of the operands has several users in
13514       // this cluster of to-be-promoted nodes, it is possible).
13515       PromOpHandles.emplace_front(PromOp);
13516       continue;
13517     }
13518 
13519     // For SELECT and SELECT_CC nodes, we do a similar check for any
13520     // to-be-promoted comparison inputs.
13521     if (PromOp.getOpcode() == ISD::SELECT ||
13522         PromOp.getOpcode() == ISD::SELECT_CC) {
13523       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13524            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13525           (SelectTruncOp[1].count(PromOp.getNode()) &&
13526            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13527         PromOpHandles.emplace_front(PromOp);
13528         continue;
13529       }
13530     }
13531 
13532     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13533                                 PromOp.getNode()->op_end());
13534 
13535     // If this node has constant inputs, then they'll need to be promoted here.
13536     for (unsigned i = 0; i < 2; ++i) {
13537       if (!isa<ConstantSDNode>(Ops[C+i]))
13538         continue;
13539       if (Ops[C+i].getValueType() == N->getValueType(0))
13540         continue;
13541 
13542       if (N->getOpcode() == ISD::SIGN_EXTEND)
13543         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13544       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13545         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13546       else
13547         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13548     }
13549 
13550     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13551     // truncate them again to the original value type.
13552     if (PromOp.getOpcode() == ISD::SELECT ||
13553         PromOp.getOpcode() == ISD::SELECT_CC) {
13554       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13555       if (SI0 != SelectTruncOp[0].end())
13556         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13557       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13558       if (SI1 != SelectTruncOp[1].end())
13559         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13560     }
13561 
13562     DAG.ReplaceAllUsesOfValueWith(PromOp,
13563       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13564   }
13565 
13566   // Now we're left with the initial extension itself.
13567   if (!ReallyNeedsExt)
13568     return N->getOperand(0);
13569 
13570   // To zero extend, just mask off everything except for the first bit (in the
13571   // i1 case).
13572   if (N->getOpcode() == ISD::ZERO_EXTEND)
13573     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13574                        DAG.getConstant(APInt::getLowBitsSet(
13575                                          N->getValueSizeInBits(0), PromBits),
13576                                        dl, N->getValueType(0)));
13577 
13578   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13579          "Invalid extension type");
13580   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13581   SDValue ShiftCst =
13582       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13583   return DAG.getNode(
13584       ISD::SRA, dl, N->getValueType(0),
13585       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13586       ShiftCst);
13587 }
13588 
13589 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13590                                         DAGCombinerInfo &DCI) const {
13591   assert(N->getOpcode() == ISD::SETCC &&
13592          "Should be called with a SETCC node");
13593 
13594   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13595   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13596     SDValue LHS = N->getOperand(0);
13597     SDValue RHS = N->getOperand(1);
13598 
13599     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13600     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13601         LHS.hasOneUse())
13602       std::swap(LHS, RHS);
13603 
13604     // x == 0-y --> x+y == 0
13605     // x != 0-y --> x+y != 0
13606     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13607         RHS.hasOneUse()) {
13608       SDLoc DL(N);
13609       SelectionDAG &DAG = DCI.DAG;
13610       EVT VT = N->getValueType(0);
13611       EVT OpVT = LHS.getValueType();
13612       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13613       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13614     }
13615   }
13616 
13617   return DAGCombineTruncBoolExt(N, DCI);
13618 }
13619 
13620 // Is this an extending load from an f32 to an f64?
13621 static bool isFPExtLoad(SDValue Op) {
13622   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13623     return LD->getExtensionType() == ISD::EXTLOAD &&
13624       Op.getValueType() == MVT::f64;
13625   return false;
13626 }
13627 
13628 /// Reduces the number of fp-to-int conversion when building a vector.
13629 ///
13630 /// If this vector is built out of floating to integer conversions,
13631 /// transform it to a vector built out of floating point values followed by a
13632 /// single floating to integer conversion of the vector.
13633 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13634 /// becomes (fptosi (build_vector ($A, $B, ...)))
13635 SDValue PPCTargetLowering::
13636 combineElementTruncationToVectorTruncation(SDNode *N,
13637                                            DAGCombinerInfo &DCI) const {
13638   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13639          "Should be called with a BUILD_VECTOR node");
13640 
13641   SelectionDAG &DAG = DCI.DAG;
13642   SDLoc dl(N);
13643 
13644   SDValue FirstInput = N->getOperand(0);
13645   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13646          "The input operand must be an fp-to-int conversion.");
13647 
13648   // This combine happens after legalization so the fp_to_[su]i nodes are
13649   // already converted to PPCSISD nodes.
13650   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13651   if (FirstConversion == PPCISD::FCTIDZ ||
13652       FirstConversion == PPCISD::FCTIDUZ ||
13653       FirstConversion == PPCISD::FCTIWZ ||
13654       FirstConversion == PPCISD::FCTIWUZ) {
13655     bool IsSplat = true;
13656     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13657       FirstConversion == PPCISD::FCTIWUZ;
13658     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13659     SmallVector<SDValue, 4> Ops;
13660     EVT TargetVT = N->getValueType(0);
13661     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13662       SDValue NextOp = N->getOperand(i);
13663       if (NextOp.getOpcode() != PPCISD::MFVSR)
13664         return SDValue();
13665       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13666       if (NextConversion != FirstConversion)
13667         return SDValue();
13668       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13669       // This is not valid if the input was originally double precision. It is
13670       // also not profitable to do unless this is an extending load in which
13671       // case doing this combine will allow us to combine consecutive loads.
13672       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13673         return SDValue();
13674       if (N->getOperand(i) != FirstInput)
13675         IsSplat = false;
13676     }
13677 
13678     // If this is a splat, we leave it as-is since there will be only a single
13679     // fp-to-int conversion followed by a splat of the integer. This is better
13680     // for 32-bit and smaller ints and neutral for 64-bit ints.
13681     if (IsSplat)
13682       return SDValue();
13683 
13684     // Now that we know we have the right type of node, get its operands
13685     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13686       SDValue In = N->getOperand(i).getOperand(0);
13687       if (Is32Bit) {
13688         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13689         // here, we know that all inputs are extending loads so this is safe).
13690         if (In.isUndef())
13691           Ops.push_back(DAG.getUNDEF(SrcVT));
13692         else {
13693           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13694                                       MVT::f32, In.getOperand(0),
13695                                       DAG.getIntPtrConstant(1, dl));
13696           Ops.push_back(Trunc);
13697         }
13698       } else
13699         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13700     }
13701 
13702     unsigned Opcode;
13703     if (FirstConversion == PPCISD::FCTIDZ ||
13704         FirstConversion == PPCISD::FCTIWZ)
13705       Opcode = ISD::FP_TO_SINT;
13706     else
13707       Opcode = ISD::FP_TO_UINT;
13708 
13709     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13710     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13711     return DAG.getNode(Opcode, dl, TargetVT, BV);
13712   }
13713   return SDValue();
13714 }
13715 
13716 /// Reduce the number of loads when building a vector.
13717 ///
13718 /// Building a vector out of multiple loads can be converted to a load
13719 /// of the vector type if the loads are consecutive. If the loads are
13720 /// consecutive but in descending order, a shuffle is added at the end
13721 /// to reorder the vector.
13722 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13723   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13724          "Should be called with a BUILD_VECTOR node");
13725 
13726   SDLoc dl(N);
13727 
13728   // Return early for non byte-sized type, as they can't be consecutive.
13729   if (!N->getValueType(0).getVectorElementType().isByteSized())
13730     return SDValue();
13731 
13732   bool InputsAreConsecutiveLoads = true;
13733   bool InputsAreReverseConsecutive = true;
13734   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13735   SDValue FirstInput = N->getOperand(0);
13736   bool IsRoundOfExtLoad = false;
13737 
13738   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13739       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13740     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13741     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13742   }
13743   // Not a build vector of (possibly fp_rounded) loads.
13744   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13745       N->getNumOperands() == 1)
13746     return SDValue();
13747 
13748   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13749     // If any inputs are fp_round(extload), they all must be.
13750     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13751       return SDValue();
13752 
13753     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13754       N->getOperand(i);
13755     if (NextInput.getOpcode() != ISD::LOAD)
13756       return SDValue();
13757 
13758     SDValue PreviousInput =
13759       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13760     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13761     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13762 
13763     // If any inputs are fp_round(extload), they all must be.
13764     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13765       return SDValue();
13766 
13767     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13768       InputsAreConsecutiveLoads = false;
13769     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13770       InputsAreReverseConsecutive = false;
13771 
13772     // Exit early if the loads are neither consecutive nor reverse consecutive.
13773     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13774       return SDValue();
13775   }
13776 
13777   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13778          "The loads cannot be both consecutive and reverse consecutive.");
13779 
13780   SDValue FirstLoadOp =
13781     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13782   SDValue LastLoadOp =
13783     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13784                        N->getOperand(N->getNumOperands()-1);
13785 
13786   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13787   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13788   if (InputsAreConsecutiveLoads) {
13789     assert(LD1 && "Input needs to be a LoadSDNode.");
13790     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13791                        LD1->getBasePtr(), LD1->getPointerInfo(),
13792                        LD1->getAlignment());
13793   }
13794   if (InputsAreReverseConsecutive) {
13795     assert(LDL && "Input needs to be a LoadSDNode.");
13796     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13797                                LDL->getBasePtr(), LDL->getPointerInfo(),
13798                                LDL->getAlignment());
13799     SmallVector<int, 16> Ops;
13800     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13801       Ops.push_back(i);
13802 
13803     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13804                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13805   }
13806   return SDValue();
13807 }
13808 
13809 // This function adds the required vector_shuffle needed to get
13810 // the elements of the vector extract in the correct position
13811 // as specified by the CorrectElems encoding.
13812 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13813                                       SDValue Input, uint64_t Elems,
13814                                       uint64_t CorrectElems) {
13815   SDLoc dl(N);
13816 
13817   unsigned NumElems = Input.getValueType().getVectorNumElements();
13818   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13819 
13820   // Knowing the element indices being extracted from the original
13821   // vector and the order in which they're being inserted, just put
13822   // them at element indices required for the instruction.
13823   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13824     if (DAG.getDataLayout().isLittleEndian())
13825       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13826     else
13827       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13828     CorrectElems = CorrectElems >> 8;
13829     Elems = Elems >> 8;
13830   }
13831 
13832   SDValue Shuffle =
13833       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13834                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13835 
13836   EVT VT = N->getValueType(0);
13837   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13838 
13839   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13840                                Input.getValueType().getVectorElementType(),
13841                                VT.getVectorNumElements());
13842   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13843                      DAG.getValueType(ExtVT));
13844 }
13845 
13846 // Look for build vector patterns where input operands come from sign
13847 // extended vector_extract elements of specific indices. If the correct indices
13848 // aren't used, add a vector shuffle to fix up the indices and create
13849 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13850 // during instruction selection.
13851 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13852   // This array encodes the indices that the vector sign extend instructions
13853   // extract from when extending from one type to another for both BE and LE.
13854   // The right nibble of each byte corresponds to the LE incides.
13855   // and the left nibble of each byte corresponds to the BE incides.
13856   // For example: 0x3074B8FC  byte->word
13857   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13858   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13859   // For example: 0x000070F8  byte->double word
13860   // For LE: the allowed indices are: 0x0,0x8
13861   // For BE: the allowed indices are: 0x7,0xF
13862   uint64_t TargetElems[] = {
13863       0x3074B8FC, // b->w
13864       0x000070F8, // b->d
13865       0x10325476, // h->w
13866       0x00003074, // h->d
13867       0x00001032, // w->d
13868   };
13869 
13870   uint64_t Elems = 0;
13871   int Index;
13872   SDValue Input;
13873 
13874   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13875     if (!Op)
13876       return false;
13877     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13878         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13879       return false;
13880 
13881     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13882     // of the right width.
13883     SDValue Extract = Op.getOperand(0);
13884     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13885       Extract = Extract.getOperand(0);
13886     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13887       return false;
13888 
13889     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13890     if (!ExtOp)
13891       return false;
13892 
13893     Index = ExtOp->getZExtValue();
13894     if (Input && Input != Extract.getOperand(0))
13895       return false;
13896 
13897     if (!Input)
13898       Input = Extract.getOperand(0);
13899 
13900     Elems = Elems << 8;
13901     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13902     Elems |= Index;
13903 
13904     return true;
13905   };
13906 
13907   // If the build vector operands aren't sign extended vector extracts,
13908   // of the same input vector, then return.
13909   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13910     if (!isSExtOfVecExtract(N->getOperand(i))) {
13911       return SDValue();
13912     }
13913   }
13914 
13915   // If the vector extract indicies are not correct, add the appropriate
13916   // vector_shuffle.
13917   int TgtElemArrayIdx;
13918   int InputSize = Input.getValueType().getScalarSizeInBits();
13919   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13920   if (InputSize + OutputSize == 40)
13921     TgtElemArrayIdx = 0;
13922   else if (InputSize + OutputSize == 72)
13923     TgtElemArrayIdx = 1;
13924   else if (InputSize + OutputSize == 48)
13925     TgtElemArrayIdx = 2;
13926   else if (InputSize + OutputSize == 80)
13927     TgtElemArrayIdx = 3;
13928   else if (InputSize + OutputSize == 96)
13929     TgtElemArrayIdx = 4;
13930   else
13931     return SDValue();
13932 
13933   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13934   CorrectElems = DAG.getDataLayout().isLittleEndian()
13935                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13936                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13937   if (Elems != CorrectElems) {
13938     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13939   }
13940 
13941   // Regular lowering will catch cases where a shuffle is not needed.
13942   return SDValue();
13943 }
13944 
13945 // Look for the pattern of a load from a narrow width to i128, feeding
13946 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13947 // (LXVRZX). This node represents a zero extending load that will be matched
13948 // to the Load VSX Vector Rightmost instructions.
13949 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13950   SDLoc DL(N);
13951 
13952   // This combine is only eligible for a BUILD_VECTOR of v1i128.
13953   if (N->getValueType(0) != MVT::v1i128)
13954     return SDValue();
13955 
13956   SDValue Operand = N->getOperand(0);
13957   // Proceed with the transformation if the operand to the BUILD_VECTOR
13958   // is a load instruction.
13959   if (Operand.getOpcode() != ISD::LOAD)
13960     return SDValue();
13961 
13962   auto *LD = cast<LoadSDNode>(Operand);
13963   EVT MemoryType = LD->getMemoryVT();
13964 
13965   // This transformation is only valid if the we are loading either a byte,
13966   // halfword, word, or doubleword.
13967   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
13968                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
13969 
13970   // Ensure that the load from the narrow width is being zero extended to i128.
13971   if (!ValidLDType ||
13972       (LD->getExtensionType() != ISD::ZEXTLOAD &&
13973        LD->getExtensionType() != ISD::EXTLOAD))
13974     return SDValue();
13975 
13976   SDValue LoadOps[] = {
13977       LD->getChain(), LD->getBasePtr(),
13978       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
13979 
13980   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
13981                                  DAG.getVTList(MVT::v1i128, MVT::Other),
13982                                  LoadOps, MemoryType, LD->getMemOperand());
13983 }
13984 
13985 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13986                                                  DAGCombinerInfo &DCI) const {
13987   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13988          "Should be called with a BUILD_VECTOR node");
13989 
13990   SelectionDAG &DAG = DCI.DAG;
13991   SDLoc dl(N);
13992 
13993   if (!Subtarget.hasVSX())
13994     return SDValue();
13995 
13996   // The target independent DAG combiner will leave a build_vector of
13997   // float-to-int conversions intact. We can generate MUCH better code for
13998   // a float-to-int conversion of a vector of floats.
13999   SDValue FirstInput = N->getOperand(0);
14000   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14001     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14002     if (Reduced)
14003       return Reduced;
14004   }
14005 
14006   // If we're building a vector out of consecutive loads, just load that
14007   // vector type.
14008   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14009   if (Reduced)
14010     return Reduced;
14011 
14012   // If we're building a vector out of extended elements from another vector
14013   // we have P9 vector integer extend instructions. The code assumes legal
14014   // input types (i.e. it can't handle things like v4i16) so do not run before
14015   // legalization.
14016   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14017     Reduced = combineBVOfVecSExt(N, DAG);
14018     if (Reduced)
14019       return Reduced;
14020   }
14021 
14022   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14023   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14024   // is a load from <valid narrow width> to i128.
14025   if (Subtarget.isISA3_1()) {
14026     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14027     if (BVOfZLoad)
14028       return BVOfZLoad;
14029   }
14030 
14031   if (N->getValueType(0) != MVT::v2f64)
14032     return SDValue();
14033 
14034   // Looking for:
14035   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14036   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14037       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14038     return SDValue();
14039   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14040       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14041     return SDValue();
14042   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14043     return SDValue();
14044 
14045   SDValue Ext1 = FirstInput.getOperand(0);
14046   SDValue Ext2 = N->getOperand(1).getOperand(0);
14047   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14048      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14049     return SDValue();
14050 
14051   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14052   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14053   if (!Ext1Op || !Ext2Op)
14054     return SDValue();
14055   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14056       Ext1.getOperand(0) != Ext2.getOperand(0))
14057     return SDValue();
14058 
14059   int FirstElem = Ext1Op->getZExtValue();
14060   int SecondElem = Ext2Op->getZExtValue();
14061   int SubvecIdx;
14062   if (FirstElem == 0 && SecondElem == 1)
14063     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14064   else if (FirstElem == 2 && SecondElem == 3)
14065     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14066   else
14067     return SDValue();
14068 
14069   SDValue SrcVec = Ext1.getOperand(0);
14070   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14071     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14072   return DAG.getNode(NodeType, dl, MVT::v2f64,
14073                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14074 }
14075 
14076 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14077                                               DAGCombinerInfo &DCI) const {
14078   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14079           N->getOpcode() == ISD::UINT_TO_FP) &&
14080          "Need an int -> FP conversion node here");
14081 
14082   if (useSoftFloat() || !Subtarget.has64BitSupport())
14083     return SDValue();
14084 
14085   SelectionDAG &DAG = DCI.DAG;
14086   SDLoc dl(N);
14087   SDValue Op(N, 0);
14088 
14089   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14090   // from the hardware.
14091   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14092     return SDValue();
14093   if (!Op.getOperand(0).getValueType().isSimple())
14094     return SDValue();
14095   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14096       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14097     return SDValue();
14098 
14099   SDValue FirstOperand(Op.getOperand(0));
14100   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14101     (FirstOperand.getValueType() == MVT::i8 ||
14102      FirstOperand.getValueType() == MVT::i16);
14103   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14104     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14105     bool DstDouble = Op.getValueType() == MVT::f64;
14106     unsigned ConvOp = Signed ?
14107       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14108       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14109     SDValue WidthConst =
14110       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14111                             dl, false);
14112     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14113     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14114     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14115                                          DAG.getVTList(MVT::f64, MVT::Other),
14116                                          Ops, MVT::i8, LDN->getMemOperand());
14117 
14118     // For signed conversion, we need to sign-extend the value in the VSR
14119     if (Signed) {
14120       SDValue ExtOps[] = { Ld, WidthConst };
14121       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14122       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14123     } else
14124       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14125   }
14126 
14127 
14128   // For i32 intermediate values, unfortunately, the conversion functions
14129   // leave the upper 32 bits of the value are undefined. Within the set of
14130   // scalar instructions, we have no method for zero- or sign-extending the
14131   // value. Thus, we cannot handle i32 intermediate values here.
14132   if (Op.getOperand(0).getValueType() == MVT::i32)
14133     return SDValue();
14134 
14135   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14136          "UINT_TO_FP is supported only with FPCVT");
14137 
14138   // If we have FCFIDS, then use it when converting to single-precision.
14139   // Otherwise, convert to double-precision and then round.
14140   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14141                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14142                                                             : PPCISD::FCFIDS)
14143                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14144                                                             : PPCISD::FCFID);
14145   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14146                   ? MVT::f32
14147                   : MVT::f64;
14148 
14149   // If we're converting from a float, to an int, and back to a float again,
14150   // then we don't need the store/load pair at all.
14151   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14152        Subtarget.hasFPCVT()) ||
14153       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14154     SDValue Src = Op.getOperand(0).getOperand(0);
14155     if (Src.getValueType() == MVT::f32) {
14156       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14157       DCI.AddToWorklist(Src.getNode());
14158     } else if (Src.getValueType() != MVT::f64) {
14159       // Make sure that we don't pick up a ppc_fp128 source value.
14160       return SDValue();
14161     }
14162 
14163     unsigned FCTOp =
14164       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14165                                                         PPCISD::FCTIDUZ;
14166 
14167     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14168     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14169 
14170     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14171       FP = DAG.getNode(ISD::FP_ROUND, dl,
14172                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14173       DCI.AddToWorklist(FP.getNode());
14174     }
14175 
14176     return FP;
14177   }
14178 
14179   return SDValue();
14180 }
14181 
14182 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14183 // builtins) into loads with swaps.
14184 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14185                                               DAGCombinerInfo &DCI) const {
14186   SelectionDAG &DAG = DCI.DAG;
14187   SDLoc dl(N);
14188   SDValue Chain;
14189   SDValue Base;
14190   MachineMemOperand *MMO;
14191 
14192   switch (N->getOpcode()) {
14193   default:
14194     llvm_unreachable("Unexpected opcode for little endian VSX load");
14195   case ISD::LOAD: {
14196     LoadSDNode *LD = cast<LoadSDNode>(N);
14197     Chain = LD->getChain();
14198     Base = LD->getBasePtr();
14199     MMO = LD->getMemOperand();
14200     // If the MMO suggests this isn't a load of a full vector, leave
14201     // things alone.  For a built-in, we have to make the change for
14202     // correctness, so if there is a size problem that will be a bug.
14203     if (MMO->getSize() < 16)
14204       return SDValue();
14205     break;
14206   }
14207   case ISD::INTRINSIC_W_CHAIN: {
14208     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14209     Chain = Intrin->getChain();
14210     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14211     // us what we want. Get operand 2 instead.
14212     Base = Intrin->getOperand(2);
14213     MMO = Intrin->getMemOperand();
14214     break;
14215   }
14216   }
14217 
14218   MVT VecTy = N->getValueType(0).getSimpleVT();
14219 
14220   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14221   // aligned and the type is a vector with elements up to 4 bytes
14222   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14223       VecTy.getScalarSizeInBits() <= 32) {
14224     return SDValue();
14225   }
14226 
14227   SDValue LoadOps[] = { Chain, Base };
14228   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14229                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14230                                          LoadOps, MVT::v2f64, MMO);
14231 
14232   DCI.AddToWorklist(Load.getNode());
14233   Chain = Load.getValue(1);
14234   SDValue Swap = DAG.getNode(
14235       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14236   DCI.AddToWorklist(Swap.getNode());
14237 
14238   // Add a bitcast if the resulting load type doesn't match v2f64.
14239   if (VecTy != MVT::v2f64) {
14240     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14241     DCI.AddToWorklist(N.getNode());
14242     // Package {bitcast value, swap's chain} to match Load's shape.
14243     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14244                        N, Swap.getValue(1));
14245   }
14246 
14247   return Swap;
14248 }
14249 
14250 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14251 // builtins) into stores with swaps.
14252 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14253                                                DAGCombinerInfo &DCI) const {
14254   SelectionDAG &DAG = DCI.DAG;
14255   SDLoc dl(N);
14256   SDValue Chain;
14257   SDValue Base;
14258   unsigned SrcOpnd;
14259   MachineMemOperand *MMO;
14260 
14261   switch (N->getOpcode()) {
14262   default:
14263     llvm_unreachable("Unexpected opcode for little endian VSX store");
14264   case ISD::STORE: {
14265     StoreSDNode *ST = cast<StoreSDNode>(N);
14266     Chain = ST->getChain();
14267     Base = ST->getBasePtr();
14268     MMO = ST->getMemOperand();
14269     SrcOpnd = 1;
14270     // If the MMO suggests this isn't a store of a full vector, leave
14271     // things alone.  For a built-in, we have to make the change for
14272     // correctness, so if there is a size problem that will be a bug.
14273     if (MMO->getSize() < 16)
14274       return SDValue();
14275     break;
14276   }
14277   case ISD::INTRINSIC_VOID: {
14278     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14279     Chain = Intrin->getChain();
14280     // Intrin->getBasePtr() oddly does not get what we want.
14281     Base = Intrin->getOperand(3);
14282     MMO = Intrin->getMemOperand();
14283     SrcOpnd = 2;
14284     break;
14285   }
14286   }
14287 
14288   SDValue Src = N->getOperand(SrcOpnd);
14289   MVT VecTy = Src.getValueType().getSimpleVT();
14290 
14291   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14292   // aligned and the type is a vector with elements up to 4 bytes
14293   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14294       VecTy.getScalarSizeInBits() <= 32) {
14295     return SDValue();
14296   }
14297 
14298   // All stores are done as v2f64 and possible bit cast.
14299   if (VecTy != MVT::v2f64) {
14300     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14301     DCI.AddToWorklist(Src.getNode());
14302   }
14303 
14304   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14305                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14306   DCI.AddToWorklist(Swap.getNode());
14307   Chain = Swap.getValue(1);
14308   SDValue StoreOps[] = { Chain, Swap, Base };
14309   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14310                                           DAG.getVTList(MVT::Other),
14311                                           StoreOps, VecTy, MMO);
14312   DCI.AddToWorklist(Store.getNode());
14313   return Store;
14314 }
14315 
14316 // Handle DAG combine for STORE (FP_TO_INT F).
14317 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14318                                                DAGCombinerInfo &DCI) const {
14319 
14320   SelectionDAG &DAG = DCI.DAG;
14321   SDLoc dl(N);
14322   unsigned Opcode = N->getOperand(1).getOpcode();
14323 
14324   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14325          && "Not a FP_TO_INT Instruction!");
14326 
14327   SDValue Val = N->getOperand(1).getOperand(0);
14328   EVT Op1VT = N->getOperand(1).getValueType();
14329   EVT ResVT = Val.getValueType();
14330 
14331   if (!isTypeLegal(ResVT))
14332     return SDValue();
14333 
14334   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14335   bool ValidTypeForStoreFltAsInt =
14336         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14337          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14338 
14339   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14340     return SDValue();
14341 
14342   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14343       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14344     return SDValue();
14345 
14346   // Extend f32 values to f64
14347   if (ResVT.getScalarSizeInBits() == 32) {
14348     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14349     DCI.AddToWorklist(Val.getNode());
14350   }
14351 
14352   // Set signed or unsigned conversion opcode.
14353   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14354                           PPCISD::FP_TO_SINT_IN_VSR :
14355                           PPCISD::FP_TO_UINT_IN_VSR;
14356 
14357   Val = DAG.getNode(ConvOpcode,
14358                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14359   DCI.AddToWorklist(Val.getNode());
14360 
14361   // Set number of bytes being converted.
14362   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14363   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14364                     DAG.getIntPtrConstant(ByteSize, dl, false),
14365                     DAG.getValueType(Op1VT) };
14366 
14367   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14368           DAG.getVTList(MVT::Other), Ops,
14369           cast<StoreSDNode>(N)->getMemoryVT(),
14370           cast<StoreSDNode>(N)->getMemOperand());
14371 
14372   DCI.AddToWorklist(Val.getNode());
14373   return Val;
14374 }
14375 
14376 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14377   // Check that the source of the element keeps flipping
14378   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14379   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14380   for (int i = 1, e = Mask.size(); i < e; i++) {
14381     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14382       return false;
14383     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14384       return false;
14385     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14386   }
14387   return true;
14388 }
14389 
14390 static bool isSplatBV(SDValue Op) {
14391   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14392     return false;
14393   SDValue FirstOp;
14394 
14395   // Find first non-undef input.
14396   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14397     FirstOp = Op.getOperand(i);
14398     if (!FirstOp.isUndef())
14399       break;
14400   }
14401 
14402   // All inputs are undef or the same as the first non-undef input.
14403   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14404     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14405       return false;
14406   return true;
14407 }
14408 
14409 static SDValue isScalarToVec(SDValue Op) {
14410   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14411     return Op;
14412   if (Op.getOpcode() != ISD::BITCAST)
14413     return SDValue();
14414   Op = Op.getOperand(0);
14415   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14416     return Op;
14417   return SDValue();
14418 }
14419 
14420 // Fix up the shuffle mask to account for the fact that the result of
14421 // scalar_to_vector is not in lane zero. This just takes all values in
14422 // the ranges specified by the min/max indices and adds the number of
14423 // elements required to ensure each element comes from the respective
14424 // position in the valid lane.
14425 // On little endian, that's just the corresponding element in the other
14426 // half of the vector. On big endian, it is in the same half but right
14427 // justified rather than left justified in that half.
14428 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14429                                             int LHSMaxIdx, int RHSMinIdx,
14430                                             int RHSMaxIdx, int HalfVec,
14431                                             unsigned ValidLaneWidth,
14432                                             const PPCSubtarget &Subtarget) {
14433   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14434     int Idx = ShuffV[i];
14435     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14436       ShuffV[i] +=
14437           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14438   }
14439 }
14440 
14441 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14442 // the original is:
14443 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14444 // In such a case, just change the shuffle mask to extract the element
14445 // from the permuted index.
14446 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14447                                const PPCSubtarget &Subtarget) {
14448   SDLoc dl(OrigSToV);
14449   EVT VT = OrigSToV.getValueType();
14450   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14451          "Expecting a SCALAR_TO_VECTOR here");
14452   SDValue Input = OrigSToV.getOperand(0);
14453 
14454   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14455     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14456     SDValue OrigVector = Input.getOperand(0);
14457 
14458     // Can't handle non-const element indices or different vector types
14459     // for the input to the extract and the output of the scalar_to_vector.
14460     if (Idx && VT == OrigVector.getValueType()) {
14461       unsigned NumElts = VT.getVectorNumElements();
14462       assert(
14463           NumElts > 1 &&
14464           "Cannot produce a permuted scalar_to_vector for one element vector");
14465       SmallVector<int, 16> NewMask(NumElts, -1);
14466       unsigned ResultInElt = NumElts / 2;
14467       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14468       NewMask[ResultInElt] = Idx->getZExtValue();
14469       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14470     }
14471   }
14472   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14473                      OrigSToV.getOperand(0));
14474 }
14475 
14476 // On little endian subtargets, combine shuffles such as:
14477 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14478 // into:
14479 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14480 // because the latter can be matched to a single instruction merge.
14481 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14482 // to put the value into element zero. Adjust the shuffle mask so that the
14483 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14484 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14485 // nodes with elements smaller than doubleword because all the ways
14486 // of getting scalar data into a vector register put the value in the
14487 // rightmost element of the left half of the vector.
14488 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14489                                                 SelectionDAG &DAG) const {
14490   SDValue LHS = SVN->getOperand(0);
14491   SDValue RHS = SVN->getOperand(1);
14492   auto Mask = SVN->getMask();
14493   int NumElts = LHS.getValueType().getVectorNumElements();
14494   SDValue Res(SVN, 0);
14495   SDLoc dl(SVN);
14496   bool IsLittleEndian = Subtarget.isLittleEndian();
14497 
14498   // On big endian targets this is only useful for subtargets with direct moves.
14499   // On little endian targets it would be useful for all subtargets with VSX.
14500   // However adding special handling for LE subtargets without direct moves
14501   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14502   // which includes direct moves.
14503   if (!Subtarget.hasDirectMove())
14504     return Res;
14505 
14506   // If this is not a shuffle of a shuffle and the first element comes from
14507   // the second vector, canonicalize to the commuted form. This will make it
14508   // more likely to match one of the single instruction patterns.
14509   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14510       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14511     std::swap(LHS, RHS);
14512     Res = DAG.getCommutedVectorShuffle(*SVN);
14513     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14514   }
14515 
14516   // Adjust the shuffle mask if either input vector comes from a
14517   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14518   // form (to prevent the need for a swap).
14519   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14520   SDValue SToVLHS = isScalarToVec(LHS);
14521   SDValue SToVRHS = isScalarToVec(RHS);
14522   if (SToVLHS || SToVRHS) {
14523     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14524                             : SToVRHS.getValueType().getVectorNumElements();
14525     int NumEltsOut = ShuffV.size();
14526     // The width of the "valid lane" (i.e. the lane that contains the value that
14527     // is vectorized) needs to be expressed in terms of the number of elements
14528     // of the shuffle. It is thereby the ratio of the values before and after
14529     // any bitcast.
14530     unsigned ValidLaneWidth =
14531         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14532                       LHS.getValueType().getScalarSizeInBits()
14533                 : SToVRHS.getValueType().getScalarSizeInBits() /
14534                       RHS.getValueType().getScalarSizeInBits();
14535 
14536     // Initially assume that neither input is permuted. These will be adjusted
14537     // accordingly if either input is.
14538     int LHSMaxIdx = -1;
14539     int RHSMinIdx = -1;
14540     int RHSMaxIdx = -1;
14541     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14542 
14543     // Get the permuted scalar to vector nodes for the source(s) that come from
14544     // ISD::SCALAR_TO_VECTOR.
14545     // On big endian systems, this only makes sense for element sizes smaller
14546     // than 64 bits since for 64-bit elements, all instructions already put
14547     // the value into element zero. Since scalar size of LHS and RHS may differ
14548     // after isScalarToVec, this should be checked using their own sizes.
14549     if (SToVLHS) {
14550       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14551         return Res;
14552       // Set up the values for the shuffle vector fixup.
14553       LHSMaxIdx = NumEltsOut / NumEltsIn;
14554       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14555       if (SToVLHS.getValueType() != LHS.getValueType())
14556         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14557       LHS = SToVLHS;
14558     }
14559     if (SToVRHS) {
14560       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14561         return Res;
14562       RHSMinIdx = NumEltsOut;
14563       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14564       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14565       if (SToVRHS.getValueType() != RHS.getValueType())
14566         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14567       RHS = SToVRHS;
14568     }
14569 
14570     // Fix up the shuffle mask to reflect where the desired element actually is.
14571     // The minimum and maximum indices that correspond to element zero for both
14572     // the LHS and RHS are computed and will control which shuffle mask entries
14573     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14574     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14575     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14576                                     HalfVec, ValidLaneWidth, Subtarget);
14577     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14578 
14579     // We may have simplified away the shuffle. We won't be able to do anything
14580     // further with it here.
14581     if (!isa<ShuffleVectorSDNode>(Res))
14582       return Res;
14583     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14584   }
14585 
14586   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14587   // The common case after we commuted the shuffle is that the RHS is a splat
14588   // and we have elements coming in from the splat at indices that are not
14589   // conducive to using a merge.
14590   // Example:
14591   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14592   if (!isSplatBV(TheSplat))
14593     return Res;
14594 
14595   // We are looking for a mask such that all even elements are from
14596   // one vector and all odd elements from the other.
14597   if (!isAlternatingShuffMask(Mask, NumElts))
14598     return Res;
14599 
14600   // Adjust the mask so we are pulling in the same index from the splat
14601   // as the index from the interesting vector in consecutive elements.
14602   if (IsLittleEndian) {
14603     // Example (even elements from first vector):
14604     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14605     if (Mask[0] < NumElts)
14606       for (int i = 1, e = Mask.size(); i < e; i += 2)
14607         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14608     // Example (odd elements from first vector):
14609     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14610     else
14611       for (int i = 0, e = Mask.size(); i < e; i += 2)
14612         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14613   } else {
14614     // Example (even elements from first vector):
14615     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14616     if (Mask[0] < NumElts)
14617       for (int i = 0, e = Mask.size(); i < e; i += 2)
14618         ShuffV[i] = ShuffV[i + 1] - NumElts;
14619     // Example (odd elements from first vector):
14620     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14621     else
14622       for (int i = 1, e = Mask.size(); i < e; i += 2)
14623         ShuffV[i] = ShuffV[i - 1] - NumElts;
14624   }
14625 
14626   // If the RHS has undefs, we need to remove them since we may have created
14627   // a shuffle that adds those instead of the splat value.
14628   SDValue SplatVal =
14629       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14630   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14631 
14632   if (IsLittleEndian)
14633     RHS = TheSplat;
14634   else
14635     LHS = TheSplat;
14636   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14637 }
14638 
14639 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14640                                                 LSBaseSDNode *LSBase,
14641                                                 DAGCombinerInfo &DCI) const {
14642   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14643         "Not a reverse memop pattern!");
14644 
14645   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14646     auto Mask = SVN->getMask();
14647     int i = 0;
14648     auto I = Mask.rbegin();
14649     auto E = Mask.rend();
14650 
14651     for (; I != E; ++I) {
14652       if (*I != i)
14653         return false;
14654       i++;
14655     }
14656     return true;
14657   };
14658 
14659   SelectionDAG &DAG = DCI.DAG;
14660   EVT VT = SVN->getValueType(0);
14661 
14662   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14663     return SDValue();
14664 
14665   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14666   // See comment in PPCVSXSwapRemoval.cpp.
14667   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14668   if (!Subtarget.hasP9Vector())
14669     return SDValue();
14670 
14671   if(!IsElementReverse(SVN))
14672     return SDValue();
14673 
14674   if (LSBase->getOpcode() == ISD::LOAD) {
14675     // If the load return value 0 has more than one user except the
14676     // shufflevector instruction, it is not profitable to replace the
14677     // shufflevector with a reverse load.
14678     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
14679          UI != UE; ++UI)
14680       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
14681         return SDValue();
14682 
14683     SDLoc dl(LSBase);
14684     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14685     return DAG.getMemIntrinsicNode(
14686         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14687         LSBase->getMemoryVT(), LSBase->getMemOperand());
14688   }
14689 
14690   if (LSBase->getOpcode() == ISD::STORE) {
14691     // If there are other uses of the shuffle, the swap cannot be avoided.
14692     // Forcing the use of an X-Form (since swapped stores only have
14693     // X-Forms) without removing the swap is unprofitable.
14694     if (!SVN->hasOneUse())
14695       return SDValue();
14696 
14697     SDLoc dl(LSBase);
14698     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14699                           LSBase->getBasePtr()};
14700     return DAG.getMemIntrinsicNode(
14701         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14702         LSBase->getMemoryVT(), LSBase->getMemOperand());
14703   }
14704 
14705   llvm_unreachable("Expected a load or store node here");
14706 }
14707 
14708 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14709                                              DAGCombinerInfo &DCI) const {
14710   SelectionDAG &DAG = DCI.DAG;
14711   SDLoc dl(N);
14712   switch (N->getOpcode()) {
14713   default: break;
14714   case ISD::ADD:
14715     return combineADD(N, DCI);
14716   case ISD::SHL:
14717     return combineSHL(N, DCI);
14718   case ISD::SRA:
14719     return combineSRA(N, DCI);
14720   case ISD::SRL:
14721     return combineSRL(N, DCI);
14722   case ISD::MUL:
14723     return combineMUL(N, DCI);
14724   case ISD::FMA:
14725   case PPCISD::FNMSUB:
14726     return combineFMALike(N, DCI);
14727   case PPCISD::SHL:
14728     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14729         return N->getOperand(0);
14730     break;
14731   case PPCISD::SRL:
14732     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14733         return N->getOperand(0);
14734     break;
14735   case PPCISD::SRA:
14736     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14737       if (C->isNullValue() ||   //  0 >>s V -> 0.
14738           C->isAllOnesValue())    // -1 >>s V -> -1.
14739         return N->getOperand(0);
14740     }
14741     break;
14742   case ISD::SIGN_EXTEND:
14743   case ISD::ZERO_EXTEND:
14744   case ISD::ANY_EXTEND:
14745     return DAGCombineExtBoolTrunc(N, DCI);
14746   case ISD::TRUNCATE:
14747     return combineTRUNCATE(N, DCI);
14748   case ISD::SETCC:
14749     if (SDValue CSCC = combineSetCC(N, DCI))
14750       return CSCC;
14751     LLVM_FALLTHROUGH;
14752   case ISD::SELECT_CC:
14753     return DAGCombineTruncBoolExt(N, DCI);
14754   case ISD::SINT_TO_FP:
14755   case ISD::UINT_TO_FP:
14756     return combineFPToIntToFP(N, DCI);
14757   case ISD::VECTOR_SHUFFLE:
14758     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14759       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14760       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14761     }
14762     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14763   case ISD::STORE: {
14764 
14765     EVT Op1VT = N->getOperand(1).getValueType();
14766     unsigned Opcode = N->getOperand(1).getOpcode();
14767 
14768     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14769       SDValue Val= combineStoreFPToInt(N, DCI);
14770       if (Val)
14771         return Val;
14772     }
14773 
14774     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14775       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14776       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14777       if (Val)
14778         return Val;
14779     }
14780 
14781     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14782     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14783         N->getOperand(1).getNode()->hasOneUse() &&
14784         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14785          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14786 
14787       // STBRX can only handle simple types and it makes no sense to store less
14788       // two bytes in byte-reversed order.
14789       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14790       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14791         break;
14792 
14793       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14794       // Do an any-extend to 32-bits if this is a half-word input.
14795       if (BSwapOp.getValueType() == MVT::i16)
14796         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14797 
14798       // If the type of BSWAP operand is wider than stored memory width
14799       // it need to be shifted to the right side before STBRX.
14800       if (Op1VT.bitsGT(mVT)) {
14801         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14802         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14803                               DAG.getConstant(Shift, dl, MVT::i32));
14804         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14805         if (Op1VT == MVT::i64)
14806           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14807       }
14808 
14809       SDValue Ops[] = {
14810         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14811       };
14812       return
14813         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14814                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14815                                 cast<StoreSDNode>(N)->getMemOperand());
14816     }
14817 
14818     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14819     // So it can increase the chance of CSE constant construction.
14820     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14821         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14822       // Need to sign-extended to 64-bits to handle negative values.
14823       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14824       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14825                                     MemVT.getSizeInBits());
14826       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14827 
14828       // DAG.getTruncStore() can't be used here because it doesn't accept
14829       // the general (base + offset) addressing mode.
14830       // So we use UpdateNodeOperands and setTruncatingStore instead.
14831       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14832                              N->getOperand(3));
14833       cast<StoreSDNode>(N)->setTruncatingStore(true);
14834       return SDValue(N, 0);
14835     }
14836 
14837     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14838     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14839     if (Op1VT.isSimple()) {
14840       MVT StoreVT = Op1VT.getSimpleVT();
14841       if (Subtarget.needsSwapsForVSXMemOps() &&
14842           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14843            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14844         return expandVSXStoreForLE(N, DCI);
14845     }
14846     break;
14847   }
14848   case ISD::LOAD: {
14849     LoadSDNode *LD = cast<LoadSDNode>(N);
14850     EVT VT = LD->getValueType(0);
14851 
14852     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14853     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14854     if (VT.isSimple()) {
14855       MVT LoadVT = VT.getSimpleVT();
14856       if (Subtarget.needsSwapsForVSXMemOps() &&
14857           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14858            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14859         return expandVSXLoadForLE(N, DCI);
14860     }
14861 
14862     // We sometimes end up with a 64-bit integer load, from which we extract
14863     // two single-precision floating-point numbers. This happens with
14864     // std::complex<float>, and other similar structures, because of the way we
14865     // canonicalize structure copies. However, if we lack direct moves,
14866     // then the final bitcasts from the extracted integer values to the
14867     // floating-point numbers turn into store/load pairs. Even with direct moves,
14868     // just loading the two floating-point numbers is likely better.
14869     auto ReplaceTwoFloatLoad = [&]() {
14870       if (VT != MVT::i64)
14871         return false;
14872 
14873       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14874           LD->isVolatile())
14875         return false;
14876 
14877       //  We're looking for a sequence like this:
14878       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14879       //      t16: i64 = srl t13, Constant:i32<32>
14880       //    t17: i32 = truncate t16
14881       //  t18: f32 = bitcast t17
14882       //    t19: i32 = truncate t13
14883       //  t20: f32 = bitcast t19
14884 
14885       if (!LD->hasNUsesOfValue(2, 0))
14886         return false;
14887 
14888       auto UI = LD->use_begin();
14889       while (UI.getUse().getResNo() != 0) ++UI;
14890       SDNode *Trunc = *UI++;
14891       while (UI.getUse().getResNo() != 0) ++UI;
14892       SDNode *RightShift = *UI;
14893       if (Trunc->getOpcode() != ISD::TRUNCATE)
14894         std::swap(Trunc, RightShift);
14895 
14896       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14897           Trunc->getValueType(0) != MVT::i32 ||
14898           !Trunc->hasOneUse())
14899         return false;
14900       if (RightShift->getOpcode() != ISD::SRL ||
14901           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14902           RightShift->getConstantOperandVal(1) != 32 ||
14903           !RightShift->hasOneUse())
14904         return false;
14905 
14906       SDNode *Trunc2 = *RightShift->use_begin();
14907       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14908           Trunc2->getValueType(0) != MVT::i32 ||
14909           !Trunc2->hasOneUse())
14910         return false;
14911 
14912       SDNode *Bitcast = *Trunc->use_begin();
14913       SDNode *Bitcast2 = *Trunc2->use_begin();
14914 
14915       if (Bitcast->getOpcode() != ISD::BITCAST ||
14916           Bitcast->getValueType(0) != MVT::f32)
14917         return false;
14918       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14919           Bitcast2->getValueType(0) != MVT::f32)
14920         return false;
14921 
14922       if (Subtarget.isLittleEndian())
14923         std::swap(Bitcast, Bitcast2);
14924 
14925       // Bitcast has the second float (in memory-layout order) and Bitcast2
14926       // has the first one.
14927 
14928       SDValue BasePtr = LD->getBasePtr();
14929       if (LD->isIndexed()) {
14930         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14931                "Non-pre-inc AM on PPC?");
14932         BasePtr =
14933           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14934                       LD->getOffset());
14935       }
14936 
14937       auto MMOFlags =
14938           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14939       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14940                                       LD->getPointerInfo(), LD->getAlignment(),
14941                                       MMOFlags, LD->getAAInfo());
14942       SDValue AddPtr =
14943         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14944                     BasePtr, DAG.getIntPtrConstant(4, dl));
14945       SDValue FloatLoad2 = DAG.getLoad(
14946           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14947           LD->getPointerInfo().getWithOffset(4),
14948           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14949 
14950       if (LD->isIndexed()) {
14951         // Note that DAGCombine should re-form any pre-increment load(s) from
14952         // what is produced here if that makes sense.
14953         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14954       }
14955 
14956       DCI.CombineTo(Bitcast2, FloatLoad);
14957       DCI.CombineTo(Bitcast, FloatLoad2);
14958 
14959       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14960                                     SDValue(FloatLoad2.getNode(), 1));
14961       return true;
14962     };
14963 
14964     if (ReplaceTwoFloatLoad())
14965       return SDValue(N, 0);
14966 
14967     EVT MemVT = LD->getMemoryVT();
14968     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14969     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14970     if (LD->isUnindexed() && VT.isVector() &&
14971         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14972           // P8 and later hardware should just use LOAD.
14973           !Subtarget.hasP8Vector() &&
14974           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14975            VT == MVT::v4f32))) &&
14976         LD->getAlign() < ABIAlignment) {
14977       // This is a type-legal unaligned Altivec load.
14978       SDValue Chain = LD->getChain();
14979       SDValue Ptr = LD->getBasePtr();
14980       bool isLittleEndian = Subtarget.isLittleEndian();
14981 
14982       // This implements the loading of unaligned vectors as described in
14983       // the venerable Apple Velocity Engine overview. Specifically:
14984       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14985       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14986       //
14987       // The general idea is to expand a sequence of one or more unaligned
14988       // loads into an alignment-based permutation-control instruction (lvsl
14989       // or lvsr), a series of regular vector loads (which always truncate
14990       // their input address to an aligned address), and a series of
14991       // permutations.  The results of these permutations are the requested
14992       // loaded values.  The trick is that the last "extra" load is not taken
14993       // from the address you might suspect (sizeof(vector) bytes after the
14994       // last requested load), but rather sizeof(vector) - 1 bytes after the
14995       // last requested vector. The point of this is to avoid a page fault if
14996       // the base address happened to be aligned. This works because if the
14997       // base address is aligned, then adding less than a full vector length
14998       // will cause the last vector in the sequence to be (re)loaded.
14999       // Otherwise, the next vector will be fetched as you might suspect was
15000       // necessary.
15001 
15002       // We might be able to reuse the permutation generation from
15003       // a different base address offset from this one by an aligned amount.
15004       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15005       // optimization later.
15006       Intrinsic::ID Intr, IntrLD, IntrPerm;
15007       MVT PermCntlTy, PermTy, LDTy;
15008       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15009                             : Intrinsic::ppc_altivec_lvsl;
15010       IntrLD = Intrinsic::ppc_altivec_lvx;
15011       IntrPerm = Intrinsic::ppc_altivec_vperm;
15012       PermCntlTy = MVT::v16i8;
15013       PermTy = MVT::v4i32;
15014       LDTy = MVT::v4i32;
15015 
15016       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15017 
15018       // Create the new MMO for the new base load. It is like the original MMO,
15019       // but represents an area in memory almost twice the vector size centered
15020       // on the original address. If the address is unaligned, we might start
15021       // reading up to (sizeof(vector)-1) bytes below the address of the
15022       // original unaligned load.
15023       MachineFunction &MF = DAG.getMachineFunction();
15024       MachineMemOperand *BaseMMO =
15025         MF.getMachineMemOperand(LD->getMemOperand(),
15026                                 -(long)MemVT.getStoreSize()+1,
15027                                 2*MemVT.getStoreSize()-1);
15028 
15029       // Create the new base load.
15030       SDValue LDXIntID =
15031           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15032       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15033       SDValue BaseLoad =
15034         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15035                                 DAG.getVTList(PermTy, MVT::Other),
15036                                 BaseLoadOps, LDTy, BaseMMO);
15037 
15038       // Note that the value of IncOffset (which is provided to the next
15039       // load's pointer info offset value, and thus used to calculate the
15040       // alignment), and the value of IncValue (which is actually used to
15041       // increment the pointer value) are different! This is because we
15042       // require the next load to appear to be aligned, even though it
15043       // is actually offset from the base pointer by a lesser amount.
15044       int IncOffset = VT.getSizeInBits() / 8;
15045       int IncValue = IncOffset;
15046 
15047       // Walk (both up and down) the chain looking for another load at the real
15048       // (aligned) offset (the alignment of the other load does not matter in
15049       // this case). If found, then do not use the offset reduction trick, as
15050       // that will prevent the loads from being later combined (as they would
15051       // otherwise be duplicates).
15052       if (!findConsecutiveLoad(LD, DAG))
15053         --IncValue;
15054 
15055       SDValue Increment =
15056           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15057       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15058 
15059       MachineMemOperand *ExtraMMO =
15060         MF.getMachineMemOperand(LD->getMemOperand(),
15061                                 1, 2*MemVT.getStoreSize()-1);
15062       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15063       SDValue ExtraLoad =
15064         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15065                                 DAG.getVTList(PermTy, MVT::Other),
15066                                 ExtraLoadOps, LDTy, ExtraMMO);
15067 
15068       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15069         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15070 
15071       // Because vperm has a big-endian bias, we must reverse the order
15072       // of the input vectors and complement the permute control vector
15073       // when generating little endian code.  We have already handled the
15074       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15075       // and ExtraLoad here.
15076       SDValue Perm;
15077       if (isLittleEndian)
15078         Perm = BuildIntrinsicOp(IntrPerm,
15079                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15080       else
15081         Perm = BuildIntrinsicOp(IntrPerm,
15082                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15083 
15084       if (VT != PermTy)
15085         Perm = Subtarget.hasAltivec()
15086                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15087                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15088                                  DAG.getTargetConstant(1, dl, MVT::i64));
15089                                // second argument is 1 because this rounding
15090                                // is always exact.
15091 
15092       // The output of the permutation is our loaded result, the TokenFactor is
15093       // our new chain.
15094       DCI.CombineTo(N, Perm, TF);
15095       return SDValue(N, 0);
15096     }
15097     }
15098     break;
15099     case ISD::INTRINSIC_WO_CHAIN: {
15100       bool isLittleEndian = Subtarget.isLittleEndian();
15101       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15102       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15103                                            : Intrinsic::ppc_altivec_lvsl);
15104       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15105         SDValue Add = N->getOperand(1);
15106 
15107         int Bits = 4 /* 16 byte alignment */;
15108 
15109         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15110                                   APInt::getAllOnesValue(Bits /* alignment */)
15111                                       .zext(Add.getScalarValueSizeInBits()))) {
15112           SDNode *BasePtr = Add->getOperand(0).getNode();
15113           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15114                                     UE = BasePtr->use_end();
15115                UI != UE; ++UI) {
15116             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15117                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15118                     IID) {
15119               // We've found another LVSL/LVSR, and this address is an aligned
15120               // multiple of that one. The results will be the same, so use the
15121               // one we've just found instead.
15122 
15123               return SDValue(*UI, 0);
15124             }
15125           }
15126         }
15127 
15128         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15129           SDNode *BasePtr = Add->getOperand(0).getNode();
15130           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15131                UE = BasePtr->use_end(); UI != UE; ++UI) {
15132             if (UI->getOpcode() == ISD::ADD &&
15133                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15134                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15135                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15136                 (1ULL << Bits) == 0) {
15137               SDNode *OtherAdd = *UI;
15138               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15139                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15140                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15141                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15142                   return SDValue(*VI, 0);
15143                 }
15144               }
15145             }
15146           }
15147         }
15148       }
15149 
15150       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15151       // Expose the vabsduw/h/b opportunity for down stream
15152       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15153           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15154            IID == Intrinsic::ppc_altivec_vmaxsh ||
15155            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15156         SDValue V1 = N->getOperand(1);
15157         SDValue V2 = N->getOperand(2);
15158         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15159              V1.getSimpleValueType() == MVT::v8i16 ||
15160              V1.getSimpleValueType() == MVT::v16i8) &&
15161             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15162           // (0-a, a)
15163           if (V1.getOpcode() == ISD::SUB &&
15164               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15165               V1.getOperand(1) == V2) {
15166             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15167           }
15168           // (a, 0-a)
15169           if (V2.getOpcode() == ISD::SUB &&
15170               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15171               V2.getOperand(1) == V1) {
15172             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15173           }
15174           // (x-y, y-x)
15175           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15176               V1.getOperand(0) == V2.getOperand(1) &&
15177               V1.getOperand(1) == V2.getOperand(0)) {
15178             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15179           }
15180         }
15181       }
15182     }
15183 
15184     break;
15185   case ISD::INTRINSIC_W_CHAIN:
15186     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15187     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15188     if (Subtarget.needsSwapsForVSXMemOps()) {
15189       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15190       default:
15191         break;
15192       case Intrinsic::ppc_vsx_lxvw4x:
15193       case Intrinsic::ppc_vsx_lxvd2x:
15194         return expandVSXLoadForLE(N, DCI);
15195       }
15196     }
15197     break;
15198   case ISD::INTRINSIC_VOID:
15199     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15200     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15201     if (Subtarget.needsSwapsForVSXMemOps()) {
15202       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15203       default:
15204         break;
15205       case Intrinsic::ppc_vsx_stxvw4x:
15206       case Intrinsic::ppc_vsx_stxvd2x:
15207         return expandVSXStoreForLE(N, DCI);
15208       }
15209     }
15210     break;
15211   case ISD::BSWAP: {
15212     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15213     // For subtargets without LDBRX, we can still do better than the default
15214     // expansion even for 64-bit BSWAP (LOAD).
15215     bool Is64BitBswapOn64BitTgt =
15216         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15217     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15218                                N->getOperand(0).hasOneUse();
15219     if (IsSingleUseNormalLd &&
15220         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15221          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15222       SDValue Load = N->getOperand(0);
15223       LoadSDNode *LD = cast<LoadSDNode>(Load);
15224       // Create the byte-swapping load.
15225       SDValue Ops[] = {
15226         LD->getChain(),    // Chain
15227         LD->getBasePtr(),  // Ptr
15228         DAG.getValueType(N->getValueType(0)) // VT
15229       };
15230       SDValue BSLoad =
15231         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15232                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15233                                               MVT::i64 : MVT::i32, MVT::Other),
15234                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15235 
15236       // If this is an i16 load, insert the truncate.
15237       SDValue ResVal = BSLoad;
15238       if (N->getValueType(0) == MVT::i16)
15239         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15240 
15241       // First, combine the bswap away.  This makes the value produced by the
15242       // load dead.
15243       DCI.CombineTo(N, ResVal);
15244 
15245       // Next, combine the load away, we give it a bogus result value but a real
15246       // chain result.  The result value is dead because the bswap is dead.
15247       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15248 
15249       // Return N so it doesn't get rechecked!
15250       return SDValue(N, 0);
15251     }
15252     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15253     // before legalization so that the BUILD_PAIR is handled correctly.
15254     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15255         !IsSingleUseNormalLd)
15256       return SDValue();
15257     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15258 
15259     // Can't split volatile or atomic loads.
15260     if (!LD->isSimple())
15261       return SDValue();
15262     SDValue BasePtr = LD->getBasePtr();
15263     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15264                              LD->getPointerInfo(), LD->getAlignment());
15265     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15266     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15267                           DAG.getIntPtrConstant(4, dl));
15268     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15269         LD->getMemOperand(), 4, 4);
15270     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15271     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15272     SDValue Res;
15273     if (Subtarget.isLittleEndian())
15274       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15275     else
15276       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15277     SDValue TF =
15278         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15279                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15280     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15281     return Res;
15282   }
15283   case PPCISD::VCMP:
15284     // If a VCMP_rec node already exists with exactly the same operands as this
15285     // node, use its result instead of this node (VCMP_rec computes both a CR6
15286     // and a normal output).
15287     //
15288     if (!N->getOperand(0).hasOneUse() &&
15289         !N->getOperand(1).hasOneUse() &&
15290         !N->getOperand(2).hasOneUse()) {
15291 
15292       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15293       SDNode *VCMPrecNode = nullptr;
15294 
15295       SDNode *LHSN = N->getOperand(0).getNode();
15296       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15297            UI != E; ++UI)
15298         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15299             UI->getOperand(1) == N->getOperand(1) &&
15300             UI->getOperand(2) == N->getOperand(2) &&
15301             UI->getOperand(0) == N->getOperand(0)) {
15302           VCMPrecNode = *UI;
15303           break;
15304         }
15305 
15306       // If there is no VCMP_rec node, or if the flag value has a single use,
15307       // don't transform this.
15308       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15309         break;
15310 
15311       // Look at the (necessarily single) use of the flag value.  If it has a
15312       // chain, this transformation is more complex.  Note that multiple things
15313       // could use the value result, which we should ignore.
15314       SDNode *FlagUser = nullptr;
15315       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15316            FlagUser == nullptr; ++UI) {
15317         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15318         SDNode *User = *UI;
15319         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15320           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15321             FlagUser = User;
15322             break;
15323           }
15324         }
15325       }
15326 
15327       // If the user is a MFOCRF instruction, we know this is safe.
15328       // Otherwise we give up for right now.
15329       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15330         return SDValue(VCMPrecNode, 0);
15331     }
15332     break;
15333   case ISD::BRCOND: {
15334     SDValue Cond = N->getOperand(1);
15335     SDValue Target = N->getOperand(2);
15336 
15337     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15338         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15339           Intrinsic::loop_decrement) {
15340 
15341       // We now need to make the intrinsic dead (it cannot be instruction
15342       // selected).
15343       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15344       assert(Cond.getNode()->hasOneUse() &&
15345              "Counter decrement has more than one use");
15346 
15347       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15348                          N->getOperand(0), Target);
15349     }
15350   }
15351   break;
15352   case ISD::BR_CC: {
15353     // If this is a branch on an altivec predicate comparison, lower this so
15354     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15355     // lowering is done pre-legalize, because the legalizer lowers the predicate
15356     // compare down to code that is difficult to reassemble.
15357     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15358     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15359 
15360     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15361     // value. If so, pass-through the AND to get to the intrinsic.
15362     if (LHS.getOpcode() == ISD::AND &&
15363         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15364         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15365           Intrinsic::loop_decrement &&
15366         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15367         !isNullConstant(LHS.getOperand(1)))
15368       LHS = LHS.getOperand(0);
15369 
15370     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15371         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15372           Intrinsic::loop_decrement &&
15373         isa<ConstantSDNode>(RHS)) {
15374       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15375              "Counter decrement comparison is not EQ or NE");
15376 
15377       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15378       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15379                     (CC == ISD::SETNE && !Val);
15380 
15381       // We now need to make the intrinsic dead (it cannot be instruction
15382       // selected).
15383       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15384       assert(LHS.getNode()->hasOneUse() &&
15385              "Counter decrement has more than one use");
15386 
15387       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15388                          N->getOperand(0), N->getOperand(4));
15389     }
15390 
15391     int CompareOpc;
15392     bool isDot;
15393 
15394     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15395         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15396         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15397       assert(isDot && "Can't compare against a vector result!");
15398 
15399       // If this is a comparison against something other than 0/1, then we know
15400       // that the condition is never/always true.
15401       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15402       if (Val != 0 && Val != 1) {
15403         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15404           return N->getOperand(0);
15405         // Always !=, turn it into an unconditional branch.
15406         return DAG.getNode(ISD::BR, dl, MVT::Other,
15407                            N->getOperand(0), N->getOperand(4));
15408       }
15409 
15410       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15411 
15412       // Create the PPCISD altivec 'dot' comparison node.
15413       SDValue Ops[] = {
15414         LHS.getOperand(2),  // LHS of compare
15415         LHS.getOperand(3),  // RHS of compare
15416         DAG.getConstant(CompareOpc, dl, MVT::i32)
15417       };
15418       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15419       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15420 
15421       // Unpack the result based on how the target uses it.
15422       PPC::Predicate CompOpc;
15423       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15424       default:  // Can't happen, don't crash on invalid number though.
15425       case 0:   // Branch on the value of the EQ bit of CR6.
15426         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15427         break;
15428       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15429         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15430         break;
15431       case 2:   // Branch on the value of the LT bit of CR6.
15432         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15433         break;
15434       case 3:   // Branch on the inverted value of the LT bit of CR6.
15435         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15436         break;
15437       }
15438 
15439       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15440                          DAG.getConstant(CompOpc, dl, MVT::i32),
15441                          DAG.getRegister(PPC::CR6, MVT::i32),
15442                          N->getOperand(4), CompNode.getValue(1));
15443     }
15444     break;
15445   }
15446   case ISD::BUILD_VECTOR:
15447     return DAGCombineBuildVector(N, DCI);
15448   case ISD::ABS:
15449     return combineABS(N, DCI);
15450   case ISD::VSELECT:
15451     return combineVSelect(N, DCI);
15452   }
15453 
15454   return SDValue();
15455 }
15456 
15457 SDValue
15458 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15459                                  SelectionDAG &DAG,
15460                                  SmallVectorImpl<SDNode *> &Created) const {
15461   // fold (sdiv X, pow2)
15462   EVT VT = N->getValueType(0);
15463   if (VT == MVT::i64 && !Subtarget.isPPC64())
15464     return SDValue();
15465   if ((VT != MVT::i32 && VT != MVT::i64) ||
15466       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15467     return SDValue();
15468 
15469   SDLoc DL(N);
15470   SDValue N0 = N->getOperand(0);
15471 
15472   bool IsNegPow2 = (-Divisor).isPowerOf2();
15473   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15474   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15475 
15476   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15477   Created.push_back(Op.getNode());
15478 
15479   if (IsNegPow2) {
15480     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15481     Created.push_back(Op.getNode());
15482   }
15483 
15484   return Op;
15485 }
15486 
15487 //===----------------------------------------------------------------------===//
15488 // Inline Assembly Support
15489 //===----------------------------------------------------------------------===//
15490 
15491 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15492                                                       KnownBits &Known,
15493                                                       const APInt &DemandedElts,
15494                                                       const SelectionDAG &DAG,
15495                                                       unsigned Depth) const {
15496   Known.resetAll();
15497   switch (Op.getOpcode()) {
15498   default: break;
15499   case PPCISD::LBRX: {
15500     // lhbrx is known to have the top bits cleared out.
15501     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15502       Known.Zero = 0xFFFF0000;
15503     break;
15504   }
15505   case ISD::INTRINSIC_WO_CHAIN: {
15506     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15507     default: break;
15508     case Intrinsic::ppc_altivec_vcmpbfp_p:
15509     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15510     case Intrinsic::ppc_altivec_vcmpequb_p:
15511     case Intrinsic::ppc_altivec_vcmpequh_p:
15512     case Intrinsic::ppc_altivec_vcmpequw_p:
15513     case Intrinsic::ppc_altivec_vcmpequd_p:
15514     case Intrinsic::ppc_altivec_vcmpequq_p:
15515     case Intrinsic::ppc_altivec_vcmpgefp_p:
15516     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15517     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15518     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15519     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15520     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15521     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15522     case Intrinsic::ppc_altivec_vcmpgtub_p:
15523     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15524     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15525     case Intrinsic::ppc_altivec_vcmpgtud_p:
15526     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15527       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15528       break;
15529     }
15530   }
15531   }
15532 }
15533 
15534 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15535   switch (Subtarget.getCPUDirective()) {
15536   default: break;
15537   case PPC::DIR_970:
15538   case PPC::DIR_PWR4:
15539   case PPC::DIR_PWR5:
15540   case PPC::DIR_PWR5X:
15541   case PPC::DIR_PWR6:
15542   case PPC::DIR_PWR6X:
15543   case PPC::DIR_PWR7:
15544   case PPC::DIR_PWR8:
15545   case PPC::DIR_PWR9:
15546   case PPC::DIR_PWR10:
15547   case PPC::DIR_PWR_FUTURE: {
15548     if (!ML)
15549       break;
15550 
15551     if (!DisableInnermostLoopAlign32) {
15552       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15553       // so that we can decrease cache misses and branch-prediction misses.
15554       // Actual alignment of the loop will depend on the hotness check and other
15555       // logic in alignBlocks.
15556       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15557         return Align(32);
15558     }
15559 
15560     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15561 
15562     // For small loops (between 5 and 8 instructions), align to a 32-byte
15563     // boundary so that the entire loop fits in one instruction-cache line.
15564     uint64_t LoopSize = 0;
15565     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15566       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15567         LoopSize += TII->getInstSizeInBytes(*J);
15568         if (LoopSize > 32)
15569           break;
15570       }
15571 
15572     if (LoopSize > 16 && LoopSize <= 32)
15573       return Align(32);
15574 
15575     break;
15576   }
15577   }
15578 
15579   return TargetLowering::getPrefLoopAlignment(ML);
15580 }
15581 
15582 /// getConstraintType - Given a constraint, return the type of
15583 /// constraint it is for this target.
15584 PPCTargetLowering::ConstraintType
15585 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15586   if (Constraint.size() == 1) {
15587     switch (Constraint[0]) {
15588     default: break;
15589     case 'b':
15590     case 'r':
15591     case 'f':
15592     case 'd':
15593     case 'v':
15594     case 'y':
15595       return C_RegisterClass;
15596     case 'Z':
15597       // FIXME: While Z does indicate a memory constraint, it specifically
15598       // indicates an r+r address (used in conjunction with the 'y' modifier
15599       // in the replacement string). Currently, we're forcing the base
15600       // register to be r0 in the asm printer (which is interpreted as zero)
15601       // and forming the complete address in the second register. This is
15602       // suboptimal.
15603       return C_Memory;
15604     }
15605   } else if (Constraint == "wc") { // individual CR bits.
15606     return C_RegisterClass;
15607   } else if (Constraint == "wa" || Constraint == "wd" ||
15608              Constraint == "wf" || Constraint == "ws" ||
15609              Constraint == "wi" || Constraint == "ww") {
15610     return C_RegisterClass; // VSX registers.
15611   }
15612   return TargetLowering::getConstraintType(Constraint);
15613 }
15614 
15615 /// Examine constraint type and operand type and determine a weight value.
15616 /// This object must already have been set up with the operand type
15617 /// and the current alternative constraint selected.
15618 TargetLowering::ConstraintWeight
15619 PPCTargetLowering::getSingleConstraintMatchWeight(
15620     AsmOperandInfo &info, const char *constraint) const {
15621   ConstraintWeight weight = CW_Invalid;
15622   Value *CallOperandVal = info.CallOperandVal;
15623     // If we don't have a value, we can't do a match,
15624     // but allow it at the lowest weight.
15625   if (!CallOperandVal)
15626     return CW_Default;
15627   Type *type = CallOperandVal->getType();
15628 
15629   // Look at the constraint type.
15630   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15631     return CW_Register; // an individual CR bit.
15632   else if ((StringRef(constraint) == "wa" ||
15633             StringRef(constraint) == "wd" ||
15634             StringRef(constraint) == "wf") &&
15635            type->isVectorTy())
15636     return CW_Register;
15637   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15638     return CW_Register; // just hold 64-bit integers data.
15639   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15640     return CW_Register;
15641   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15642     return CW_Register;
15643 
15644   switch (*constraint) {
15645   default:
15646     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15647     break;
15648   case 'b':
15649     if (type->isIntegerTy())
15650       weight = CW_Register;
15651     break;
15652   case 'f':
15653     if (type->isFloatTy())
15654       weight = CW_Register;
15655     break;
15656   case 'd':
15657     if (type->isDoubleTy())
15658       weight = CW_Register;
15659     break;
15660   case 'v':
15661     if (type->isVectorTy())
15662       weight = CW_Register;
15663     break;
15664   case 'y':
15665     weight = CW_Register;
15666     break;
15667   case 'Z':
15668     weight = CW_Memory;
15669     break;
15670   }
15671   return weight;
15672 }
15673 
15674 std::pair<unsigned, const TargetRegisterClass *>
15675 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15676                                                 StringRef Constraint,
15677                                                 MVT VT) const {
15678   if (Constraint.size() == 1) {
15679     // GCC RS6000 Constraint Letters
15680     switch (Constraint[0]) {
15681     case 'b':   // R1-R31
15682       if (VT == MVT::i64 && Subtarget.isPPC64())
15683         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15684       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15685     case 'r':   // R0-R31
15686       if (VT == MVT::i64 && Subtarget.isPPC64())
15687         return std::make_pair(0U, &PPC::G8RCRegClass);
15688       return std::make_pair(0U, &PPC::GPRCRegClass);
15689     // 'd' and 'f' constraints are both defined to be "the floating point
15690     // registers", where one is for 32-bit and the other for 64-bit. We don't
15691     // really care overly much here so just give them all the same reg classes.
15692     case 'd':
15693     case 'f':
15694       if (Subtarget.hasSPE()) {
15695         if (VT == MVT::f32 || VT == MVT::i32)
15696           return std::make_pair(0U, &PPC::GPRCRegClass);
15697         if (VT == MVT::f64 || VT == MVT::i64)
15698           return std::make_pair(0U, &PPC::SPERCRegClass);
15699       } else {
15700         if (VT == MVT::f32 || VT == MVT::i32)
15701           return std::make_pair(0U, &PPC::F4RCRegClass);
15702         if (VT == MVT::f64 || VT == MVT::i64)
15703           return std::make_pair(0U, &PPC::F8RCRegClass);
15704       }
15705       break;
15706     case 'v':
15707       if (Subtarget.hasAltivec())
15708         return std::make_pair(0U, &PPC::VRRCRegClass);
15709       break;
15710     case 'y':   // crrc
15711       return std::make_pair(0U, &PPC::CRRCRegClass);
15712     }
15713   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15714     // An individual CR bit.
15715     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15716   } else if ((Constraint == "wa" || Constraint == "wd" ||
15717              Constraint == "wf" || Constraint == "wi") &&
15718              Subtarget.hasVSX()) {
15719     // A VSX register for either a scalar (FP) or vector. There is no
15720     // support for single precision scalars on subtargets prior to Power8.
15721     if (VT.isVector())
15722       return std::make_pair(0U, &PPC::VSRCRegClass);
15723     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15724       return std::make_pair(0U, &PPC::VSSRCRegClass);
15725     return std::make_pair(0U, &PPC::VSFRCRegClass);
15726   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15727     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15728       return std::make_pair(0U, &PPC::VSSRCRegClass);
15729     else
15730       return std::make_pair(0U, &PPC::VSFRCRegClass);
15731   } else if (Constraint == "lr") {
15732     if (VT == MVT::i64)
15733       return std::make_pair(0U, &PPC::LR8RCRegClass);
15734     else
15735       return std::make_pair(0U, &PPC::LRRCRegClass);
15736   }
15737 
15738   // Handle special cases of physical registers that are not properly handled
15739   // by the base class.
15740   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
15741     // If we name a VSX register, we can't defer to the base class because it
15742     // will not recognize the correct register (their names will be VSL{0-31}
15743     // and V{0-31} so they won't match). So we match them here.
15744     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15745       int VSNum = atoi(Constraint.data() + 3);
15746       assert(VSNum >= 0 && VSNum <= 63 &&
15747              "Attempted to access a vsr out of range");
15748       if (VSNum < 32)
15749         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15750       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15751     }
15752 
15753     // For float registers, we can't defer to the base class as it will match
15754     // the SPILLTOVSRRC class.
15755     if (Constraint.size() > 3 && Constraint[1] == 'f') {
15756       int RegNum = atoi(Constraint.data() + 2);
15757       if (RegNum > 31 || RegNum < 0)
15758         report_fatal_error("Invalid floating point register number");
15759       if (VT == MVT::f32 || VT == MVT::i32)
15760         return Subtarget.hasSPE()
15761                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
15762                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
15763       if (VT == MVT::f64 || VT == MVT::i64)
15764         return Subtarget.hasSPE()
15765                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
15766                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
15767     }
15768   }
15769 
15770   std::pair<unsigned, const TargetRegisterClass *> R =
15771       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15772 
15773   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15774   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15775   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15776   // register.
15777   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15778   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15779   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15780       PPC::GPRCRegClass.contains(R.first))
15781     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15782                             PPC::sub_32, &PPC::G8RCRegClass),
15783                           &PPC::G8RCRegClass);
15784 
15785   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15786   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
15787     R.first = PPC::CR0;
15788     R.second = &PPC::CRRCRegClass;
15789   }
15790   // FIXME: This warning should ideally be emitted in the front end.
15791   const auto &TM = getTargetMachine();
15792   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
15793     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
15794          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
15795         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
15796       errs() << "warning: vector registers 20 to 32 are reserved in the "
15797                 "default AIX AltiVec ABI and cannot be used\n";
15798   }
15799 
15800   return R;
15801 }
15802 
15803 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15804 /// vector.  If it is invalid, don't add anything to Ops.
15805 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15806                                                      std::string &Constraint,
15807                                                      std::vector<SDValue>&Ops,
15808                                                      SelectionDAG &DAG) const {
15809   SDValue Result;
15810 
15811   // Only support length 1 constraints.
15812   if (Constraint.length() > 1) return;
15813 
15814   char Letter = Constraint[0];
15815   switch (Letter) {
15816   default: break;
15817   case 'I':
15818   case 'J':
15819   case 'K':
15820   case 'L':
15821   case 'M':
15822   case 'N':
15823   case 'O':
15824   case 'P': {
15825     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15826     if (!CST) return; // Must be an immediate to match.
15827     SDLoc dl(Op);
15828     int64_t Value = CST->getSExtValue();
15829     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15830                          // numbers are printed as such.
15831     switch (Letter) {
15832     default: llvm_unreachable("Unknown constraint letter!");
15833     case 'I':  // "I" is a signed 16-bit constant.
15834       if (isInt<16>(Value))
15835         Result = DAG.getTargetConstant(Value, dl, TCVT);
15836       break;
15837     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15838       if (isShiftedUInt<16, 16>(Value))
15839         Result = DAG.getTargetConstant(Value, dl, TCVT);
15840       break;
15841     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15842       if (isShiftedInt<16, 16>(Value))
15843         Result = DAG.getTargetConstant(Value, dl, TCVT);
15844       break;
15845     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15846       if (isUInt<16>(Value))
15847         Result = DAG.getTargetConstant(Value, dl, TCVT);
15848       break;
15849     case 'M':  // "M" is a constant that is greater than 31.
15850       if (Value > 31)
15851         Result = DAG.getTargetConstant(Value, dl, TCVT);
15852       break;
15853     case 'N':  // "N" is a positive constant that is an exact power of two.
15854       if (Value > 0 && isPowerOf2_64(Value))
15855         Result = DAG.getTargetConstant(Value, dl, TCVT);
15856       break;
15857     case 'O':  // "O" is the constant zero.
15858       if (Value == 0)
15859         Result = DAG.getTargetConstant(Value, dl, TCVT);
15860       break;
15861     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15862       if (isInt<16>(-Value))
15863         Result = DAG.getTargetConstant(Value, dl, TCVT);
15864       break;
15865     }
15866     break;
15867   }
15868   }
15869 
15870   if (Result.getNode()) {
15871     Ops.push_back(Result);
15872     return;
15873   }
15874 
15875   // Handle standard constraint letters.
15876   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15877 }
15878 
15879 // isLegalAddressingMode - Return true if the addressing mode represented
15880 // by AM is legal for this target, for a load/store of the specified type.
15881 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15882                                               const AddrMode &AM, Type *Ty,
15883                                               unsigned AS,
15884                                               Instruction *I) const {
15885   // Vector type r+i form is supported since power9 as DQ form. We don't check
15886   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15887   // imm form is preferred and the offset can be adjusted to use imm form later
15888   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15889   // max offset to check legal addressing mode, we should be a little aggressive
15890   // to contain other offsets for that LSRUse.
15891   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15892     return false;
15893 
15894   // PPC allows a sign-extended 16-bit immediate field.
15895   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15896     return false;
15897 
15898   // No global is ever allowed as a base.
15899   if (AM.BaseGV)
15900     return false;
15901 
15902   // PPC only support r+r,
15903   switch (AM.Scale) {
15904   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15905     break;
15906   case 1:
15907     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15908       return false;
15909     // Otherwise we have r+r or r+i.
15910     break;
15911   case 2:
15912     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15913       return false;
15914     // Allow 2*r as r+r.
15915     break;
15916   default:
15917     // No other scales are supported.
15918     return false;
15919   }
15920 
15921   return true;
15922 }
15923 
15924 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15925                                            SelectionDAG &DAG) const {
15926   MachineFunction &MF = DAG.getMachineFunction();
15927   MachineFrameInfo &MFI = MF.getFrameInfo();
15928   MFI.setReturnAddressIsTaken(true);
15929 
15930   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15931     return SDValue();
15932 
15933   SDLoc dl(Op);
15934   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15935 
15936   // Make sure the function does not optimize away the store of the RA to
15937   // the stack.
15938   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15939   FuncInfo->setLRStoreRequired();
15940   bool isPPC64 = Subtarget.isPPC64();
15941   auto PtrVT = getPointerTy(MF.getDataLayout());
15942 
15943   if (Depth > 0) {
15944     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15945     SDValue Offset =
15946         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15947                         isPPC64 ? MVT::i64 : MVT::i32);
15948     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15949                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15950                        MachinePointerInfo());
15951   }
15952 
15953   // Just load the return address off the stack.
15954   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15955   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15956                      MachinePointerInfo());
15957 }
15958 
15959 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15960                                           SelectionDAG &DAG) const {
15961   SDLoc dl(Op);
15962   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15963 
15964   MachineFunction &MF = DAG.getMachineFunction();
15965   MachineFrameInfo &MFI = MF.getFrameInfo();
15966   MFI.setFrameAddressIsTaken(true);
15967 
15968   EVT PtrVT = getPointerTy(MF.getDataLayout());
15969   bool isPPC64 = PtrVT == MVT::i64;
15970 
15971   // Naked functions never have a frame pointer, and so we use r1. For all
15972   // other functions, this decision must be delayed until during PEI.
15973   unsigned FrameReg;
15974   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15975     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15976   else
15977     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15978 
15979   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15980                                          PtrVT);
15981   while (Depth--)
15982     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15983                             FrameAddr, MachinePointerInfo());
15984   return FrameAddr;
15985 }
15986 
15987 // FIXME? Maybe this could be a TableGen attribute on some registers and
15988 // this table could be generated automatically from RegInfo.
15989 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15990                                               const MachineFunction &MF) const {
15991   bool isPPC64 = Subtarget.isPPC64();
15992 
15993   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15994   if (!is64Bit && VT != LLT::scalar(32))
15995     report_fatal_error("Invalid register global variable type");
15996 
15997   Register Reg = StringSwitch<Register>(RegName)
15998                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15999                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16000                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16001                      .Default(Register());
16002 
16003   if (Reg)
16004     return Reg;
16005   report_fatal_error("Invalid register name global variable");
16006 }
16007 
16008 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16009   // 32-bit SVR4 ABI access everything as got-indirect.
16010   if (Subtarget.is32BitELFABI())
16011     return true;
16012 
16013   // AIX accesses everything indirectly through the TOC, which is similar to
16014   // the GOT.
16015   if (Subtarget.isAIXABI())
16016     return true;
16017 
16018   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16019   // If it is small or large code model, module locals are accessed
16020   // indirectly by loading their address from .toc/.got.
16021   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16022     return true;
16023 
16024   // JumpTable and BlockAddress are accessed as got-indirect.
16025   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16026     return true;
16027 
16028   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16029     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16030 
16031   return false;
16032 }
16033 
16034 bool
16035 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16036   // The PowerPC target isn't yet aware of offsets.
16037   return false;
16038 }
16039 
16040 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16041                                            const CallInst &I,
16042                                            MachineFunction &MF,
16043                                            unsigned Intrinsic) const {
16044   switch (Intrinsic) {
16045   case Intrinsic::ppc_altivec_lvx:
16046   case Intrinsic::ppc_altivec_lvxl:
16047   case Intrinsic::ppc_altivec_lvebx:
16048   case Intrinsic::ppc_altivec_lvehx:
16049   case Intrinsic::ppc_altivec_lvewx:
16050   case Intrinsic::ppc_vsx_lxvd2x:
16051   case Intrinsic::ppc_vsx_lxvw4x:
16052   case Intrinsic::ppc_vsx_lxvd2x_be:
16053   case Intrinsic::ppc_vsx_lxvw4x_be:
16054   case Intrinsic::ppc_vsx_lxvl:
16055   case Intrinsic::ppc_vsx_lxvll: {
16056     EVT VT;
16057     switch (Intrinsic) {
16058     case Intrinsic::ppc_altivec_lvebx:
16059       VT = MVT::i8;
16060       break;
16061     case Intrinsic::ppc_altivec_lvehx:
16062       VT = MVT::i16;
16063       break;
16064     case Intrinsic::ppc_altivec_lvewx:
16065       VT = MVT::i32;
16066       break;
16067     case Intrinsic::ppc_vsx_lxvd2x:
16068     case Intrinsic::ppc_vsx_lxvd2x_be:
16069       VT = MVT::v2f64;
16070       break;
16071     default:
16072       VT = MVT::v4i32;
16073       break;
16074     }
16075 
16076     Info.opc = ISD::INTRINSIC_W_CHAIN;
16077     Info.memVT = VT;
16078     Info.ptrVal = I.getArgOperand(0);
16079     Info.offset = -VT.getStoreSize()+1;
16080     Info.size = 2*VT.getStoreSize()-1;
16081     Info.align = Align(1);
16082     Info.flags = MachineMemOperand::MOLoad;
16083     return true;
16084   }
16085   case Intrinsic::ppc_altivec_stvx:
16086   case Intrinsic::ppc_altivec_stvxl:
16087   case Intrinsic::ppc_altivec_stvebx:
16088   case Intrinsic::ppc_altivec_stvehx:
16089   case Intrinsic::ppc_altivec_stvewx:
16090   case Intrinsic::ppc_vsx_stxvd2x:
16091   case Intrinsic::ppc_vsx_stxvw4x:
16092   case Intrinsic::ppc_vsx_stxvd2x_be:
16093   case Intrinsic::ppc_vsx_stxvw4x_be:
16094   case Intrinsic::ppc_vsx_stxvl:
16095   case Intrinsic::ppc_vsx_stxvll: {
16096     EVT VT;
16097     switch (Intrinsic) {
16098     case Intrinsic::ppc_altivec_stvebx:
16099       VT = MVT::i8;
16100       break;
16101     case Intrinsic::ppc_altivec_stvehx:
16102       VT = MVT::i16;
16103       break;
16104     case Intrinsic::ppc_altivec_stvewx:
16105       VT = MVT::i32;
16106       break;
16107     case Intrinsic::ppc_vsx_stxvd2x:
16108     case Intrinsic::ppc_vsx_stxvd2x_be:
16109       VT = MVT::v2f64;
16110       break;
16111     default:
16112       VT = MVT::v4i32;
16113       break;
16114     }
16115 
16116     Info.opc = ISD::INTRINSIC_VOID;
16117     Info.memVT = VT;
16118     Info.ptrVal = I.getArgOperand(1);
16119     Info.offset = -VT.getStoreSize()+1;
16120     Info.size = 2*VT.getStoreSize()-1;
16121     Info.align = Align(1);
16122     Info.flags = MachineMemOperand::MOStore;
16123     return true;
16124   }
16125   default:
16126     break;
16127   }
16128 
16129   return false;
16130 }
16131 
16132 /// It returns EVT::Other if the type should be determined using generic
16133 /// target-independent logic.
16134 EVT PPCTargetLowering::getOptimalMemOpType(
16135     const MemOp &Op, const AttributeList &FuncAttributes) const {
16136   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16137     // We should use Altivec/VSX loads and stores when available. For unaligned
16138     // addresses, unaligned VSX loads are only fast starting with the P8.
16139     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16140         (Op.isAligned(Align(16)) ||
16141          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16142       return MVT::v4i32;
16143   }
16144 
16145   if (Subtarget.isPPC64()) {
16146     return MVT::i64;
16147   }
16148 
16149   return MVT::i32;
16150 }
16151 
16152 /// Returns true if it is beneficial to convert a load of a constant
16153 /// to just the constant itself.
16154 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16155                                                           Type *Ty) const {
16156   assert(Ty->isIntegerTy());
16157 
16158   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16159   return !(BitSize == 0 || BitSize > 64);
16160 }
16161 
16162 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16163   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16164     return false;
16165   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16166   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16167   return NumBits1 == 64 && NumBits2 == 32;
16168 }
16169 
16170 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16171   if (!VT1.isInteger() || !VT2.isInteger())
16172     return false;
16173   unsigned NumBits1 = VT1.getSizeInBits();
16174   unsigned NumBits2 = VT2.getSizeInBits();
16175   return NumBits1 == 64 && NumBits2 == 32;
16176 }
16177 
16178 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16179   // Generally speaking, zexts are not free, but they are free when they can be
16180   // folded with other operations.
16181   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16182     EVT MemVT = LD->getMemoryVT();
16183     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16184          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16185         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16186          LD->getExtensionType() == ISD::ZEXTLOAD))
16187       return true;
16188   }
16189 
16190   // FIXME: Add other cases...
16191   //  - 32-bit shifts with a zext to i64
16192   //  - zext after ctlz, bswap, etc.
16193   //  - zext after and by a constant mask
16194 
16195   return TargetLowering::isZExtFree(Val, VT2);
16196 }
16197 
16198 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16199   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16200          "invalid fpext types");
16201   // Extending to float128 is not free.
16202   if (DestVT == MVT::f128)
16203     return false;
16204   return true;
16205 }
16206 
16207 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16208   return isInt<16>(Imm) || isUInt<16>(Imm);
16209 }
16210 
16211 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16212   return isInt<16>(Imm) || isUInt<16>(Imm);
16213 }
16214 
16215 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16216                                                        MachineMemOperand::Flags,
16217                                                        bool *Fast) const {
16218   if (DisablePPCUnaligned)
16219     return false;
16220 
16221   // PowerPC supports unaligned memory access for simple non-vector types.
16222   // Although accessing unaligned addresses is not as efficient as accessing
16223   // aligned addresses, it is generally more efficient than manual expansion,
16224   // and generally only traps for software emulation when crossing page
16225   // boundaries.
16226 
16227   if (!VT.isSimple())
16228     return false;
16229 
16230   if (VT.isFloatingPoint() && !VT.isVector() &&
16231       !Subtarget.allowsUnalignedFPAccess())
16232     return false;
16233 
16234   if (VT.getSimpleVT().isVector()) {
16235     if (Subtarget.hasVSX()) {
16236       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16237           VT != MVT::v4f32 && VT != MVT::v4i32)
16238         return false;
16239     } else {
16240       return false;
16241     }
16242   }
16243 
16244   if (VT == MVT::ppcf128)
16245     return false;
16246 
16247   if (Fast)
16248     *Fast = true;
16249 
16250   return true;
16251 }
16252 
16253 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16254                                                SDValue C) const {
16255   // Check integral scalar types.
16256   if (!VT.isScalarInteger())
16257     return false;
16258   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16259     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16260       return false;
16261     // This transformation will generate >= 2 operations. But the following
16262     // cases will generate <= 2 instructions during ISEL. So exclude them.
16263     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16264     // HW instruction, ie. MULLI
16265     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16266     // instruction is needed than case 1, ie. MULLI and RLDICR
16267     int64_t Imm = ConstNode->getSExtValue();
16268     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16269     Imm >>= Shift;
16270     if (isInt<16>(Imm))
16271       return false;
16272     uint64_t UImm = static_cast<uint64_t>(Imm);
16273     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16274         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16275       return true;
16276   }
16277   return false;
16278 }
16279 
16280 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16281                                                    EVT VT) const {
16282   return isFMAFasterThanFMulAndFAdd(
16283       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16284 }
16285 
16286 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16287                                                    Type *Ty) const {
16288   switch (Ty->getScalarType()->getTypeID()) {
16289   case Type::FloatTyID:
16290   case Type::DoubleTyID:
16291     return true;
16292   case Type::FP128TyID:
16293     return Subtarget.hasP9Vector();
16294   default:
16295     return false;
16296   }
16297 }
16298 
16299 // FIXME: add more patterns which are not profitable to hoist.
16300 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16301   if (!I->hasOneUse())
16302     return true;
16303 
16304   Instruction *User = I->user_back();
16305   assert(User && "A single use instruction with no uses.");
16306 
16307   switch (I->getOpcode()) {
16308   case Instruction::FMul: {
16309     // Don't break FMA, PowerPC prefers FMA.
16310     if (User->getOpcode() != Instruction::FSub &&
16311         User->getOpcode() != Instruction::FAdd)
16312       return true;
16313 
16314     const TargetOptions &Options = getTargetMachine().Options;
16315     const Function *F = I->getFunction();
16316     const DataLayout &DL = F->getParent()->getDataLayout();
16317     Type *Ty = User->getOperand(0)->getType();
16318 
16319     return !(
16320         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16321         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16322         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16323   }
16324   case Instruction::Load: {
16325     // Don't break "store (load float*)" pattern, this pattern will be combined
16326     // to "store (load int32)" in later InstCombine pass. See function
16327     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16328     // cycles than loading a 32 bit integer.
16329     LoadInst *LI = cast<LoadInst>(I);
16330     // For the loads that combineLoadToOperationType does nothing, like
16331     // ordered load, it should be profitable to hoist them.
16332     // For swifterror load, it can only be used for pointer to pointer type, so
16333     // later type check should get rid of this case.
16334     if (!LI->isUnordered())
16335       return true;
16336 
16337     if (User->getOpcode() != Instruction::Store)
16338       return true;
16339 
16340     if (I->getType()->getTypeID() != Type::FloatTyID)
16341       return true;
16342 
16343     return false;
16344   }
16345   default:
16346     return true;
16347   }
16348   return true;
16349 }
16350 
16351 const MCPhysReg *
16352 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16353   // LR is a callee-save register, but we must treat it as clobbered by any call
16354   // site. Hence we include LR in the scratch registers, which are in turn added
16355   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16356   // to CTR, which is used by any indirect call.
16357   static const MCPhysReg ScratchRegs[] = {
16358     PPC::X12, PPC::LR8, PPC::CTR8, 0
16359   };
16360 
16361   return ScratchRegs;
16362 }
16363 
16364 Register PPCTargetLowering::getExceptionPointerRegister(
16365     const Constant *PersonalityFn) const {
16366   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16367 }
16368 
16369 Register PPCTargetLowering::getExceptionSelectorRegister(
16370     const Constant *PersonalityFn) const {
16371   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16372 }
16373 
16374 bool
16375 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16376                      EVT VT , unsigned DefinedValues) const {
16377   if (VT == MVT::v2i64)
16378     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16379 
16380   if (Subtarget.hasVSX())
16381     return true;
16382 
16383   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16384 }
16385 
16386 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16387   if (DisableILPPref || Subtarget.enableMachineScheduler())
16388     return TargetLowering::getSchedulingPreference(N);
16389 
16390   return Sched::ILP;
16391 }
16392 
16393 // Create a fast isel object.
16394 FastISel *
16395 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16396                                   const TargetLibraryInfo *LibInfo) const {
16397   return PPC::createFastISel(FuncInfo, LibInfo);
16398 }
16399 
16400 // 'Inverted' means the FMA opcode after negating one multiplicand.
16401 // For example, (fma -a b c) = (fnmsub a b c)
16402 static unsigned invertFMAOpcode(unsigned Opc) {
16403   switch (Opc) {
16404   default:
16405     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16406   case ISD::FMA:
16407     return PPCISD::FNMSUB;
16408   case PPCISD::FNMSUB:
16409     return ISD::FMA;
16410   }
16411 }
16412 
16413 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16414                                                 bool LegalOps, bool OptForSize,
16415                                                 NegatibleCost &Cost,
16416                                                 unsigned Depth) const {
16417   if (Depth > SelectionDAG::MaxRecursionDepth)
16418     return SDValue();
16419 
16420   unsigned Opc = Op.getOpcode();
16421   EVT VT = Op.getValueType();
16422   SDNodeFlags Flags = Op.getNode()->getFlags();
16423 
16424   switch (Opc) {
16425   case PPCISD::FNMSUB:
16426     if (!Op.hasOneUse() || !isTypeLegal(VT))
16427       break;
16428 
16429     const TargetOptions &Options = getTargetMachine().Options;
16430     SDValue N0 = Op.getOperand(0);
16431     SDValue N1 = Op.getOperand(1);
16432     SDValue N2 = Op.getOperand(2);
16433     SDLoc Loc(Op);
16434 
16435     NegatibleCost N2Cost = NegatibleCost::Expensive;
16436     SDValue NegN2 =
16437         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16438 
16439     if (!NegN2)
16440       return SDValue();
16441 
16442     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16443     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16444     // These transformations may change sign of zeroes. For example,
16445     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16446     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16447       // Try and choose the cheaper one to negate.
16448       NegatibleCost N0Cost = NegatibleCost::Expensive;
16449       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16450                                            N0Cost, Depth + 1);
16451 
16452       NegatibleCost N1Cost = NegatibleCost::Expensive;
16453       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16454                                            N1Cost, Depth + 1);
16455 
16456       if (NegN0 && N0Cost <= N1Cost) {
16457         Cost = std::min(N0Cost, N2Cost);
16458         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16459       } else if (NegN1) {
16460         Cost = std::min(N1Cost, N2Cost);
16461         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16462       }
16463     }
16464 
16465     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16466     if (isOperationLegal(ISD::FMA, VT)) {
16467       Cost = N2Cost;
16468       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16469     }
16470 
16471     break;
16472   }
16473 
16474   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16475                                               Cost, Depth);
16476 }
16477 
16478 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16479 bool PPCTargetLowering::useLoadStackGuardNode() const {
16480   if (!Subtarget.isTargetLinux())
16481     return TargetLowering::useLoadStackGuardNode();
16482   return true;
16483 }
16484 
16485 // Override to disable global variable loading on Linux and insert AIX canary
16486 // word declaration.
16487 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16488   if (Subtarget.isAIXABI()) {
16489     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16490                         Type::getInt8PtrTy(M.getContext()));
16491     return;
16492   }
16493   if (!Subtarget.isTargetLinux())
16494     return TargetLowering::insertSSPDeclarations(M);
16495 }
16496 
16497 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16498   if (Subtarget.isAIXABI())
16499     return M.getGlobalVariable(AIXSSPCanaryWordName);
16500   return TargetLowering::getSDagStackGuard(M);
16501 }
16502 
16503 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16504                                      bool ForCodeSize) const {
16505   if (!VT.isSimple() || !Subtarget.hasVSX())
16506     return false;
16507 
16508   switch(VT.getSimpleVT().SimpleTy) {
16509   default:
16510     // For FP types that are currently not supported by PPC backend, return
16511     // false. Examples: f16, f80.
16512     return false;
16513   case MVT::f32:
16514   case MVT::f64:
16515     if (Subtarget.hasPrefixInstrs()) {
16516       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16517       return true;
16518     }
16519     LLVM_FALLTHROUGH;
16520   case MVT::ppcf128:
16521     return Imm.isPosZero();
16522   }
16523 }
16524 
16525 // For vector shift operation op, fold
16526 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16527 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16528                                   SelectionDAG &DAG) {
16529   SDValue N0 = N->getOperand(0);
16530   SDValue N1 = N->getOperand(1);
16531   EVT VT = N0.getValueType();
16532   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16533   unsigned Opcode = N->getOpcode();
16534   unsigned TargetOpcode;
16535 
16536   switch (Opcode) {
16537   default:
16538     llvm_unreachable("Unexpected shift operation");
16539   case ISD::SHL:
16540     TargetOpcode = PPCISD::SHL;
16541     break;
16542   case ISD::SRL:
16543     TargetOpcode = PPCISD::SRL;
16544     break;
16545   case ISD::SRA:
16546     TargetOpcode = PPCISD::SRA;
16547     break;
16548   }
16549 
16550   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16551       N1->getOpcode() == ISD::AND)
16552     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16553       if (Mask->getZExtValue() == OpSizeInBits - 1)
16554         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16555 
16556   return SDValue();
16557 }
16558 
16559 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16560   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16561     return Value;
16562 
16563   SDValue N0 = N->getOperand(0);
16564   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16565   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16566       N0.getOpcode() != ISD::SIGN_EXTEND ||
16567       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16568       N->getValueType(0) != MVT::i64)
16569     return SDValue();
16570 
16571   // We can't save an operation here if the value is already extended, and
16572   // the existing shift is easier to combine.
16573   SDValue ExtsSrc = N0.getOperand(0);
16574   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16575       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16576     return SDValue();
16577 
16578   SDLoc DL(N0);
16579   SDValue ShiftBy = SDValue(CN1, 0);
16580   // We want the shift amount to be i32 on the extswli, but the shift could
16581   // have an i64.
16582   if (ShiftBy.getValueType() == MVT::i64)
16583     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16584 
16585   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16586                          ShiftBy);
16587 }
16588 
16589 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16590   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16591     return Value;
16592 
16593   return SDValue();
16594 }
16595 
16596 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16597   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16598     return Value;
16599 
16600   return SDValue();
16601 }
16602 
16603 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16604 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16605 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16606 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16607 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16608                                  const PPCSubtarget &Subtarget) {
16609   if (!Subtarget.isPPC64())
16610     return SDValue();
16611 
16612   SDValue LHS = N->getOperand(0);
16613   SDValue RHS = N->getOperand(1);
16614 
16615   auto isZextOfCompareWithConstant = [](SDValue Op) {
16616     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16617         Op.getValueType() != MVT::i64)
16618       return false;
16619 
16620     SDValue Cmp = Op.getOperand(0);
16621     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16622         Cmp.getOperand(0).getValueType() != MVT::i64)
16623       return false;
16624 
16625     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16626       int64_t NegConstant = 0 - Constant->getSExtValue();
16627       // Due to the limitations of the addi instruction,
16628       // -C is required to be [-32768, 32767].
16629       return isInt<16>(NegConstant);
16630     }
16631 
16632     return false;
16633   };
16634 
16635   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16636   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16637 
16638   // If there is a pattern, canonicalize a zext operand to the RHS.
16639   if (LHSHasPattern && !RHSHasPattern)
16640     std::swap(LHS, RHS);
16641   else if (!LHSHasPattern && !RHSHasPattern)
16642     return SDValue();
16643 
16644   SDLoc DL(N);
16645   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16646   SDValue Cmp = RHS.getOperand(0);
16647   SDValue Z = Cmp.getOperand(0);
16648   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
16649   int64_t NegConstant = 0 - Constant->getSExtValue();
16650 
16651   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16652   default: break;
16653   case ISD::SETNE: {
16654     //                                 when C == 0
16655     //                             --> addze X, (addic Z, -1).carry
16656     //                            /
16657     // add X, (zext(setne Z, C))--
16658     //                            \    when -32768 <= -C <= 32767 && C != 0
16659     //                             --> addze X, (addic (addi Z, -C), -1).carry
16660     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16661                               DAG.getConstant(NegConstant, DL, MVT::i64));
16662     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16663     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16664                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16665     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16666                        SDValue(Addc.getNode(), 1));
16667     }
16668   case ISD::SETEQ: {
16669     //                                 when C == 0
16670     //                             --> addze X, (subfic Z, 0).carry
16671     //                            /
16672     // add X, (zext(sete  Z, C))--
16673     //                            \    when -32768 <= -C <= 32767 && C != 0
16674     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16675     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16676                               DAG.getConstant(NegConstant, DL, MVT::i64));
16677     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16678     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16679                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16680     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16681                        SDValue(Subc.getNode(), 1));
16682     }
16683   }
16684 
16685   return SDValue();
16686 }
16687 
16688 // Transform
16689 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16690 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16691 // In this case both C1 and C2 must be known constants.
16692 // C1+C2 must fit into a 34 bit signed integer.
16693 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16694                                           const PPCSubtarget &Subtarget) {
16695   if (!Subtarget.isUsingPCRelativeCalls())
16696     return SDValue();
16697 
16698   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16699   // If we find that node try to cast the Global Address and the Constant.
16700   SDValue LHS = N->getOperand(0);
16701   SDValue RHS = N->getOperand(1);
16702 
16703   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16704     std::swap(LHS, RHS);
16705 
16706   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16707     return SDValue();
16708 
16709   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16710   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16711   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16712 
16713   // Check that both casts succeeded.
16714   if (!GSDN || !ConstNode)
16715     return SDValue();
16716 
16717   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16718   SDLoc DL(GSDN);
16719 
16720   // The signed int offset needs to fit in 34 bits.
16721   if (!isInt<34>(NewOffset))
16722     return SDValue();
16723 
16724   // The new global address is a copy of the old global address except
16725   // that it has the updated Offset.
16726   SDValue GA =
16727       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16728                                  NewOffset, GSDN->getTargetFlags());
16729   SDValue MatPCRel =
16730       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16731   return MatPCRel;
16732 }
16733 
16734 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16735   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16736     return Value;
16737 
16738   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16739     return Value;
16740 
16741   return SDValue();
16742 }
16743 
16744 // Detect TRUNCATE operations on bitcasts of float128 values.
16745 // What we are looking for here is the situtation where we extract a subset
16746 // of bits from a 128 bit float.
16747 // This can be of two forms:
16748 // 1) BITCAST of f128 feeding TRUNCATE
16749 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16750 // The reason this is required is because we do not have a legal i128 type
16751 // and so we want to prevent having to store the f128 and then reload part
16752 // of it.
16753 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16754                                            DAGCombinerInfo &DCI) const {
16755   // If we are using CRBits then try that first.
16756   if (Subtarget.useCRBits()) {
16757     // Check if CRBits did anything and return that if it did.
16758     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16759       return CRTruncValue;
16760   }
16761 
16762   SDLoc dl(N);
16763   SDValue Op0 = N->getOperand(0);
16764 
16765   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16766   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16767     EVT VT = N->getValueType(0);
16768     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16769       return SDValue();
16770     SDValue Sub = Op0.getOperand(0);
16771     if (Sub.getOpcode() == ISD::SUB) {
16772       SDValue SubOp0 = Sub.getOperand(0);
16773       SDValue SubOp1 = Sub.getOperand(1);
16774       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16775           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16776         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16777                                SubOp1.getOperand(0),
16778                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16779       }
16780     }
16781   }
16782 
16783   // Looking for a truncate of i128 to i64.
16784   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16785     return SDValue();
16786 
16787   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16788 
16789   // SRL feeding TRUNCATE.
16790   if (Op0.getOpcode() == ISD::SRL) {
16791     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16792     // The right shift has to be by 64 bits.
16793     if (!ConstNode || ConstNode->getZExtValue() != 64)
16794       return SDValue();
16795 
16796     // Switch the element number to extract.
16797     EltToExtract = EltToExtract ? 0 : 1;
16798     // Update Op0 past the SRL.
16799     Op0 = Op0.getOperand(0);
16800   }
16801 
16802   // BITCAST feeding a TRUNCATE possibly via SRL.
16803   if (Op0.getOpcode() == ISD::BITCAST &&
16804       Op0.getValueType() == MVT::i128 &&
16805       Op0.getOperand(0).getValueType() == MVT::f128) {
16806     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16807     return DCI.DAG.getNode(
16808         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16809         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16810   }
16811   return SDValue();
16812 }
16813 
16814 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16815   SelectionDAG &DAG = DCI.DAG;
16816 
16817   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16818   if (!ConstOpOrElement)
16819     return SDValue();
16820 
16821   // An imul is usually smaller than the alternative sequence for legal type.
16822   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16823       isOperationLegal(ISD::MUL, N->getValueType(0)))
16824     return SDValue();
16825 
16826   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16827     switch (this->Subtarget.getCPUDirective()) {
16828     default:
16829       // TODO: enhance the condition for subtarget before pwr8
16830       return false;
16831     case PPC::DIR_PWR8:
16832       //  type        mul     add    shl
16833       // scalar        4       1      1
16834       // vector        7       2      2
16835       return true;
16836     case PPC::DIR_PWR9:
16837     case PPC::DIR_PWR10:
16838     case PPC::DIR_PWR_FUTURE:
16839       //  type        mul     add    shl
16840       // scalar        5       2      2
16841       // vector        7       2      2
16842 
16843       // The cycle RATIO of related operations are showed as a table above.
16844       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16845       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16846       // are 4, it is always profitable; but for 3 instrs patterns
16847       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16848       // So we should only do it for vector type.
16849       return IsAddOne && IsNeg ? VT.isVector() : true;
16850     }
16851   };
16852 
16853   EVT VT = N->getValueType(0);
16854   SDLoc DL(N);
16855 
16856   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16857   bool IsNeg = MulAmt.isNegative();
16858   APInt MulAmtAbs = MulAmt.abs();
16859 
16860   if ((MulAmtAbs - 1).isPowerOf2()) {
16861     // (mul x, 2^N + 1) => (add (shl x, N), x)
16862     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16863 
16864     if (!IsProfitable(IsNeg, true, VT))
16865       return SDValue();
16866 
16867     SDValue Op0 = N->getOperand(0);
16868     SDValue Op1 =
16869         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16870                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16871     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16872 
16873     if (!IsNeg)
16874       return Res;
16875 
16876     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16877   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16878     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16879     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16880 
16881     if (!IsProfitable(IsNeg, false, VT))
16882       return SDValue();
16883 
16884     SDValue Op0 = N->getOperand(0);
16885     SDValue Op1 =
16886         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16887                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16888 
16889     if (!IsNeg)
16890       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16891     else
16892       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16893 
16894   } else {
16895     return SDValue();
16896   }
16897 }
16898 
16899 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16900 // in combiner since we need to check SD flags and other subtarget features.
16901 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16902                                           DAGCombinerInfo &DCI) const {
16903   SDValue N0 = N->getOperand(0);
16904   SDValue N1 = N->getOperand(1);
16905   SDValue N2 = N->getOperand(2);
16906   SDNodeFlags Flags = N->getFlags();
16907   EVT VT = N->getValueType(0);
16908   SelectionDAG &DAG = DCI.DAG;
16909   const TargetOptions &Options = getTargetMachine().Options;
16910   unsigned Opc = N->getOpcode();
16911   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16912   bool LegalOps = !DCI.isBeforeLegalizeOps();
16913   SDLoc Loc(N);
16914 
16915   if (!isOperationLegal(ISD::FMA, VT))
16916     return SDValue();
16917 
16918   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16919   // since (fnmsub a b c)=-0 while c-ab=+0.
16920   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16921     return SDValue();
16922 
16923   // (fma (fneg a) b c) => (fnmsub a b c)
16924   // (fnmsub (fneg a) b c) => (fma a b c)
16925   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16926     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16927 
16928   // (fma a (fneg b) c) => (fnmsub a b c)
16929   // (fnmsub a (fneg b) c) => (fma a b c)
16930   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16931     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16932 
16933   return SDValue();
16934 }
16935 
16936 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16937   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16938   if (!Subtarget.is64BitELFABI())
16939     return false;
16940 
16941   // If not a tail call then no need to proceed.
16942   if (!CI->isTailCall())
16943     return false;
16944 
16945   // If sibling calls have been disabled and tail-calls aren't guaranteed
16946   // there is no reason to duplicate.
16947   auto &TM = getTargetMachine();
16948   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16949     return false;
16950 
16951   // Can't tail call a function called indirectly, or if it has variadic args.
16952   const Function *Callee = CI->getCalledFunction();
16953   if (!Callee || Callee->isVarArg())
16954     return false;
16955 
16956   // Make sure the callee and caller calling conventions are eligible for tco.
16957   const Function *Caller = CI->getParent()->getParent();
16958   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16959                                            CI->getCallingConv()))
16960       return false;
16961 
16962   // If the function is local then we have a good chance at tail-calling it
16963   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16964 }
16965 
16966 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16967   if (!Subtarget.hasVSX())
16968     return false;
16969   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16970     return true;
16971   return VT == MVT::f32 || VT == MVT::f64 ||
16972     VT == MVT::v4f32 || VT == MVT::v2f64;
16973 }
16974 
16975 bool PPCTargetLowering::
16976 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16977   const Value *Mask = AndI.getOperand(1);
16978   // If the mask is suitable for andi. or andis. we should sink the and.
16979   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16980     // Can't handle constants wider than 64-bits.
16981     if (CI->getBitWidth() > 64)
16982       return false;
16983     int64_t ConstVal = CI->getZExtValue();
16984     return isUInt<16>(ConstVal) ||
16985       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16986   }
16987 
16988   // For non-constant masks, we can always use the record-form and.
16989   return true;
16990 }
16991 
16992 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16993 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16994 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16995 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16996 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16997 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16998   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16999   assert(Subtarget.hasP9Altivec() &&
17000          "Only combine this when P9 altivec supported!");
17001   EVT VT = N->getValueType(0);
17002   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17003     return SDValue();
17004 
17005   SelectionDAG &DAG = DCI.DAG;
17006   SDLoc dl(N);
17007   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17008     // Even for signed integers, if it's known to be positive (as signed
17009     // integer) due to zero-extended inputs.
17010     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17011     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17012     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17013          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17014         (SubOpcd1 == ISD::ZERO_EXTEND ||
17015          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17016       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17017                          N->getOperand(0)->getOperand(0),
17018                          N->getOperand(0)->getOperand(1),
17019                          DAG.getTargetConstant(0, dl, MVT::i32));
17020     }
17021 
17022     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17023     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17024         N->getOperand(0).hasOneUse()) {
17025       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17026                          N->getOperand(0)->getOperand(0),
17027                          N->getOperand(0)->getOperand(1),
17028                          DAG.getTargetConstant(1, dl, MVT::i32));
17029     }
17030   }
17031 
17032   return SDValue();
17033 }
17034 
17035 // For type v4i32/v8ii16/v16i8, transform
17036 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17037 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17038 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17039 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17040 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17041                                           DAGCombinerInfo &DCI) const {
17042   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17043   assert(Subtarget.hasP9Altivec() &&
17044          "Only combine this when P9 altivec supported!");
17045 
17046   SelectionDAG &DAG = DCI.DAG;
17047   SDLoc dl(N);
17048   SDValue Cond = N->getOperand(0);
17049   SDValue TrueOpnd = N->getOperand(1);
17050   SDValue FalseOpnd = N->getOperand(2);
17051   EVT VT = N->getOperand(1).getValueType();
17052 
17053   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17054       FalseOpnd.getOpcode() != ISD::SUB)
17055     return SDValue();
17056 
17057   // ABSD only available for type v4i32/v8i16/v16i8
17058   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17059     return SDValue();
17060 
17061   // At least to save one more dependent computation
17062   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17063     return SDValue();
17064 
17065   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17066 
17067   // Can only handle unsigned comparison here
17068   switch (CC) {
17069   default:
17070     return SDValue();
17071   case ISD::SETUGT:
17072   case ISD::SETUGE:
17073     break;
17074   case ISD::SETULT:
17075   case ISD::SETULE:
17076     std::swap(TrueOpnd, FalseOpnd);
17077     break;
17078   }
17079 
17080   SDValue CmpOpnd1 = Cond.getOperand(0);
17081   SDValue CmpOpnd2 = Cond.getOperand(1);
17082 
17083   // SETCC CmpOpnd1 CmpOpnd2 cond
17084   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17085   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17086   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17087       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17088       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17089       FalseOpnd.getOperand(1) == CmpOpnd1) {
17090     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17091                        CmpOpnd1, CmpOpnd2,
17092                        DAG.getTargetConstant(0, dl, MVT::i32));
17093   }
17094 
17095   return SDValue();
17096 }
17097 
17098 /// getAddrModeForFlags - Based on the set of address flags, select the most
17099 /// optimal instruction format to match by.
17100 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17101   // This is not a node we should be handling here.
17102   if (Flags == PPC::MOF_None)
17103     return PPC::AM_None;
17104   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17105   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17106     if ((Flags & FlagSet) == FlagSet)
17107       return PPC::AM_DForm;
17108   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17109     if ((Flags & FlagSet) == FlagSet)
17110       return PPC::AM_DSForm;
17111   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17112     if ((Flags & FlagSet) == FlagSet)
17113       return PPC::AM_DQForm;
17114   // If no other forms are selected, return an X-Form as it is the most
17115   // general addressing mode.
17116   return PPC::AM_XForm;
17117 }
17118 
17119 /// Set alignment flags based on whether or not the Frame Index is aligned.
17120 /// Utilized when computing flags for address computation when selecting
17121 /// load and store instructions.
17122 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17123                                SelectionDAG &DAG) {
17124   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17125   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17126   if (!FI)
17127     return;
17128   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17129   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17130   // If this is (add $FI, $S16Imm), the alignment flags are already set
17131   // based on the immediate. We just need to clear the alignment flags
17132   // if the FI alignment is weaker.
17133   if ((FrameIndexAlign % 4) != 0)
17134     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17135   if ((FrameIndexAlign % 16) != 0)
17136     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17137   // If the address is a plain FrameIndex, set alignment flags based on
17138   // FI alignment.
17139   if (!IsAdd) {
17140     if ((FrameIndexAlign % 4) == 0)
17141       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17142     if ((FrameIndexAlign % 16) == 0)
17143       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17144   }
17145 }
17146 
17147 /// Given a node, compute flags that are used for address computation when
17148 /// selecting load and store instructions. The flags computed are stored in
17149 /// FlagSet. This function takes into account whether the node is a constant,
17150 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17151 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17152                                               SelectionDAG &DAG) {
17153   // Set the alignment flags for the node depending on if the node is
17154   // 4-byte or 16-byte aligned.
17155   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17156     if ((Imm & 0x3) == 0)
17157       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17158     if ((Imm & 0xf) == 0)
17159       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17160   };
17161 
17162   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17163     // All 32-bit constants can be computed as LIS + Disp.
17164     const APInt &ConstImm = CN->getAPIntValue();
17165     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17166       FlagSet |= PPC::MOF_AddrIsSImm32;
17167       SetAlignFlagsForImm(ConstImm.getZExtValue());
17168       setAlignFlagsForFI(N, FlagSet, DAG);
17169     }
17170     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17171       FlagSet |= PPC::MOF_RPlusSImm34;
17172     else // Let constant materialization handle large constants.
17173       FlagSet |= PPC::MOF_NotAddNorCst;
17174   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17175     // This address can be represented as an addition of:
17176     // - Register + Imm16 (possibly a multiple of 4/16)
17177     // - Register + Imm34
17178     // - Register + PPCISD::Lo
17179     // - Register + Register
17180     // In any case, we won't have to match this as Base + Zero.
17181     SDValue RHS = N.getOperand(1);
17182     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17183       const APInt &ConstImm = CN->getAPIntValue();
17184       if (ConstImm.isSignedIntN(16)) {
17185         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17186         SetAlignFlagsForImm(ConstImm.getZExtValue());
17187         setAlignFlagsForFI(N, FlagSet, DAG);
17188       }
17189       if (ConstImm.isSignedIntN(34))
17190         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17191       else
17192         FlagSet |= PPC::MOF_RPlusR; // Register.
17193     } else if (RHS.getOpcode() == PPCISD::Lo &&
17194                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17195       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17196     else
17197       FlagSet |= PPC::MOF_RPlusR;
17198   } else { // The address computation is not a constant or an addition.
17199     setAlignFlagsForFI(N, FlagSet, DAG);
17200     FlagSet |= PPC::MOF_NotAddNorCst;
17201   }
17202 }
17203 
17204 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17205 /// the address flags of the load/store instruction that is to be matched.
17206 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17207                                            SelectionDAG &DAG) const {
17208   unsigned FlagSet = PPC::MOF_None;
17209 
17210   // Compute subtarget flags.
17211   if (!Subtarget.hasP9Vector())
17212     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17213   else {
17214     FlagSet |= PPC::MOF_SubtargetP9;
17215     if (Subtarget.hasPrefixInstrs())
17216       FlagSet |= PPC::MOF_SubtargetP10;
17217   }
17218   if (Subtarget.hasSPE())
17219     FlagSet |= PPC::MOF_SubtargetSPE;
17220 
17221   // Mark this as something we don't want to handle here if it is atomic
17222   // or pre-increment instruction.
17223   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17224     if (LSB->isIndexed())
17225       return PPC::MOF_None;
17226 
17227   // Compute in-memory type flags. This is based on if there are scalars,
17228   // floats or vectors.
17229   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17230   assert(MN && "Parent should be a MemSDNode!");
17231   EVT MemVT = MN->getMemoryVT();
17232   unsigned Size = MemVT.getSizeInBits();
17233   if (MemVT.isScalarInteger()) {
17234     assert(Size <= 64 && "Not expecting scalar integers larger than 8 bytes!");
17235     if (Size < 32)
17236       FlagSet |= PPC::MOF_SubWordInt;
17237     else if (Size == 32)
17238       FlagSet |= PPC::MOF_WordInt;
17239     else
17240       FlagSet |= PPC::MOF_DoubleWordInt;
17241   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17242     if (Size == 128)
17243       FlagSet |= PPC::MOF_Vector;
17244     else if (Size == 256)
17245       FlagSet |= PPC::MOF_Vector256;
17246     else
17247       llvm_unreachable("Not expecting illegal vectors!");
17248   } else { // Floating point type: can be scalar, f128 or vector types.
17249     if (Size == 32 || Size == 64)
17250       FlagSet |= PPC::MOF_ScalarFloat;
17251     else if (MemVT == MVT::f128 || MemVT.isVector())
17252       FlagSet |= PPC::MOF_Vector;
17253     else
17254       llvm_unreachable("Not expecting illegal scalar floats!");
17255   }
17256 
17257   // Compute flags for address computation.
17258   computeFlagsForAddressComputation(N, FlagSet, DAG);
17259 
17260   // Compute type extension flags.
17261   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17262     switch (LN->getExtensionType()) {
17263     case ISD::SEXTLOAD:
17264       FlagSet |= PPC::MOF_SExt;
17265       break;
17266     case ISD::EXTLOAD:
17267     case ISD::ZEXTLOAD:
17268       FlagSet |= PPC::MOF_ZExt;
17269       break;
17270     case ISD::NON_EXTLOAD:
17271       FlagSet |= PPC::MOF_NoExt;
17272       break;
17273     }
17274   } else
17275     FlagSet |= PPC::MOF_NoExt;
17276 
17277   // For integers, no extension is the same as zero extension.
17278   // We set the extension mode to zero extension so we don't have
17279   // to add separate entries in AddrModesMap for loads and stores.
17280   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17281     FlagSet |= PPC::MOF_ZExt;
17282     FlagSet &= ~PPC::MOF_NoExt;
17283   }
17284 
17285   // If we don't have prefixed instructions, 34-bit constants should be
17286   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17287   bool IsNonP1034BitConst =
17288       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17289        FlagSet) == PPC::MOF_RPlusSImm34;
17290   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17291       IsNonP1034BitConst)
17292     FlagSet |= PPC::MOF_NotAddNorCst;
17293 
17294   return FlagSet;
17295 }
17296 
17297 /// SelectForceXFormMode - Given the specified address, force it to be
17298 /// represented as an indexed [r+r] operation (an XForm instruction).
17299 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17300                                                       SDValue &Base,
17301                                                       SelectionDAG &DAG) const {
17302 
17303   PPC::AddrMode Mode = PPC::AM_XForm;
17304   int16_t ForceXFormImm = 0;
17305   if (provablyDisjointOr(DAG, N) &&
17306       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17307     Disp = N.getOperand(0);
17308     Base = N.getOperand(1);
17309     return Mode;
17310   }
17311 
17312   // If the address is the result of an add, we will utilize the fact that the
17313   // address calculation includes an implicit add.  However, we can reduce
17314   // register pressure if we do not materialize a constant just for use as the
17315   // index register.  We only get rid of the add if it is not an add of a
17316   // value and a 16-bit signed constant and both have a single use.
17317   if (N.getOpcode() == ISD::ADD &&
17318       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17319        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17320     Disp = N.getOperand(0);
17321     Base = N.getOperand(1);
17322     return Mode;
17323   }
17324 
17325   // Otherwise, use R0 as the base register.
17326   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17327                          N.getValueType());
17328   Base = N;
17329 
17330   return Mode;
17331 }
17332 
17333 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17334 /// compute the address flags of the node, get the optimal address mode based
17335 /// on the flags, and set the Base and Disp based on the address mode.
17336 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17337                                                        SDValue N, SDValue &Disp,
17338                                                        SDValue &Base,
17339                                                        SelectionDAG &DAG,
17340                                                        MaybeAlign Align) const {
17341   SDLoc DL(Parent);
17342 
17343   // Compute the address flags.
17344   unsigned Flags = computeMOFlags(Parent, N, DAG);
17345 
17346   // Get the optimal address mode based on the Flags.
17347   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17348 
17349   // Set Base and Disp accordingly depending on the address mode.
17350   switch (Mode) {
17351   case PPC::AM_DForm:
17352   case PPC::AM_DSForm:
17353   case PPC::AM_DQForm: {
17354     // This is a register plus a 16-bit immediate. The base will be the
17355     // register and the displacement will be the immediate unless it
17356     // isn't sufficiently aligned.
17357     if (Flags & PPC::MOF_RPlusSImm16) {
17358       SDValue Op0 = N.getOperand(0);
17359       SDValue Op1 = N.getOperand(1);
17360       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17361       if (!Align || isAligned(*Align, Imm)) {
17362         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17363         Base = Op0;
17364         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17365           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17366           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17367         }
17368         break;
17369       }
17370     }
17371     // This is a register plus the @lo relocation. The base is the register
17372     // and the displacement is the global address.
17373     else if (Flags & PPC::MOF_RPlusLo) {
17374       Disp = N.getOperand(1).getOperand(0); // The global address.
17375       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17376              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17377              Disp.getOpcode() == ISD::TargetConstantPool ||
17378              Disp.getOpcode() == ISD::TargetJumpTable);
17379       Base = N.getOperand(0);
17380       break;
17381     }
17382     // This is a constant address at most 32 bits. The base will be
17383     // zero or load-immediate-shifted and the displacement will be
17384     // the low 16 bits of the address.
17385     else if (Flags & PPC::MOF_AddrIsSImm32) {
17386       auto *CN = cast<ConstantSDNode>(N);
17387       EVT CNType = CN->getValueType(0);
17388       uint64_t CNImm = CN->getZExtValue();
17389       // If this address fits entirely in a 16-bit sext immediate field, codegen
17390       // this as "d, 0".
17391       int16_t Imm;
17392       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17393         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17394         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17395                                CNType);
17396         break;
17397       }
17398       // Handle 32-bit sext immediate with LIS + Addr mode.
17399       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17400           (!Align || isAligned(*Align, CNImm))) {
17401         int32_t Addr = (int32_t)CNImm;
17402         // Otherwise, break this down into LIS + Disp.
17403         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17404         Base =
17405             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17406         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17407         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17408         break;
17409       }
17410     }
17411     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17412     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17413     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17414       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17415       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17416     } else
17417       Base = N;
17418     break;
17419   }
17420   case PPC::AM_None:
17421     break;
17422   default: { // By default, X-Form is always available to be selected.
17423     // When a frame index is not aligned, we also match by XForm.
17424     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
17425     Base = FI ? N : N.getOperand(1);
17426     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17427                                 N.getValueType())
17428               : N.getOperand(0);
17429     break;
17430   }
17431   }
17432   return Mode;
17433 }
17434 
17435 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
17436                                                  bool Return,
17437                                                  bool IsVarArg) const {
17438   switch (CC) {
17439   case CallingConv::Cold:
17440     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
17441   default:
17442     return CC_PPC64_ELF_FIS;
17443   }
17444 }
17445