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 static cl::opt<bool> EnableQuadwordAtomics(
125     "ppc-quadword-atomics",
126     cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127     cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
139 
140 // FIXME: Remove this once the bug has been fixed!
141 extern cl::opt<bool> ANDIGlueBug;
142 
143 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
144                                      const PPCSubtarget &STI)
145     : TargetLowering(TM), Subtarget(STI) {
146   // Initialize map that relates the PPC addressing modes to the computed flags
147   // of a load/store instruction. The map is used to determine the optimal
148   // addressing mode when selecting load and stores.
149   initializeAddrModeMap();
150   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
151   // arguments are at least 4/8 bytes aligned.
152   bool isPPC64 = Subtarget.isPPC64();
153   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
154 
155   // Set up the register classes.
156   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
157   if (!useSoftFloat()) {
158     if (hasSPE()) {
159       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
160       // EFPU2 APU only supports f32
161       if (!Subtarget.hasEFPU2())
162         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
163     } else {
164       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
165       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
166     }
167   }
168 
169   // Match BITREVERSE to customized fast code sequence in the td file.
170   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
171   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
172 
173   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
174   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
175 
176   // Custom lower inline assembly to check for special registers.
177   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
178   setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
179 
180   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
181   for (MVT VT : MVT::integer_valuetypes()) {
182     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
183     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
184   }
185 
186   if (Subtarget.isISA3_0()) {
187     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
188     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
189     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
190     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
191   } else {
192     // No extending loads from f16 or HW conversions back and forth.
193     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
194     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
195     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
196     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
197     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
198     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
199     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
200     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
201   }
202 
203   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
204 
205   // PowerPC has pre-inc load and store's.
206   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
207   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
208   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
209   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
210   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
211   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
212   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
213   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
214   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
215   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
216   if (!Subtarget.hasSPE()) {
217     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
218     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
219     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
220     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
221   }
222 
223   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
224   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
225   for (MVT VT : ScalarIntVTs) {
226     setOperationAction(ISD::ADDC, VT, Legal);
227     setOperationAction(ISD::ADDE, VT, Legal);
228     setOperationAction(ISD::SUBC, VT, Legal);
229     setOperationAction(ISD::SUBE, VT, Legal);
230   }
231 
232   if (Subtarget.useCRBits()) {
233     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
234 
235     if (isPPC64 || Subtarget.hasFPCVT()) {
236       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
237       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
238                         isPPC64 ? MVT::i64 : MVT::i32);
239       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
240       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
241                         isPPC64 ? MVT::i64 : MVT::i32);
242 
243       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
244       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
245                          isPPC64 ? MVT::i64 : MVT::i32);
246       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
247       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
248                         isPPC64 ? MVT::i64 : MVT::i32);
249 
250       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
251       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
252                         isPPC64 ? MVT::i64 : MVT::i32);
253       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
254       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
255                         isPPC64 ? MVT::i64 : MVT::i32);
256 
257       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
258       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
259                         isPPC64 ? MVT::i64 : MVT::i32);
260       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
261       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
262                         isPPC64 ? MVT::i64 : MVT::i32);
263     } else {
264       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
265       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
266       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
267       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
268     }
269 
270     // PowerPC does not support direct load/store of condition registers.
271     setOperationAction(ISD::LOAD, MVT::i1, Custom);
272     setOperationAction(ISD::STORE, MVT::i1, Custom);
273 
274     // FIXME: Remove this once the ANDI glue bug is fixed:
275     if (ANDIGlueBug)
276       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
277 
278     for (MVT VT : MVT::integer_valuetypes()) {
279       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
280       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
281       setTruncStoreAction(VT, MVT::i1, Expand);
282     }
283 
284     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
285   }
286 
287   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
288   // PPC (the libcall is not available).
289   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
290   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
291   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
292   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
293 
294   // We do not currently implement these libm ops for PowerPC.
295   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
296   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
297   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
298   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
299   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
300   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
301 
302   // PowerPC has no SREM/UREM instructions unless we are on P9
303   // On P9 we may use a hardware instruction to compute the remainder.
304   // When the result of both the remainder and the division is required it is
305   // more efficient to compute the remainder from the result of the division
306   // rather than use the remainder instruction. The instructions are legalized
307   // directly because the DivRemPairsPass performs the transformation at the IR
308   // level.
309   if (Subtarget.isISA3_0()) {
310     setOperationAction(ISD::SREM, MVT::i32, Legal);
311     setOperationAction(ISD::UREM, MVT::i32, Legal);
312     setOperationAction(ISD::SREM, MVT::i64, Legal);
313     setOperationAction(ISD::UREM, MVT::i64, Legal);
314   } else {
315     setOperationAction(ISD::SREM, MVT::i32, Expand);
316     setOperationAction(ISD::UREM, MVT::i32, Expand);
317     setOperationAction(ISD::SREM, MVT::i64, Expand);
318     setOperationAction(ISD::UREM, MVT::i64, Expand);
319   }
320 
321   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
322   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
323   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
324   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
325   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
326   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
327   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
328   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
329   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
330 
331   // Handle constrained floating-point operations of scalar.
332   // TODO: Handle SPE specific operation.
333   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
334   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
335   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
336   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
337   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
338 
339   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
340   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
341   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
342   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
343 
344   if (!Subtarget.hasSPE()) {
345     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
346     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
347   }
348 
349   if (Subtarget.hasVSX()) {
350     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
352   }
353 
354   if (Subtarget.hasFSQRT()) {
355     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
357   }
358 
359   if (Subtarget.hasFPRND()) {
360     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
361     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
362     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
363     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
364 
365     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
366     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
367     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
368     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
369   }
370 
371   // We don't support sin/cos/sqrt/fmod/pow
372   setOperationAction(ISD::FSIN , MVT::f64, Expand);
373   setOperationAction(ISD::FCOS , MVT::f64, Expand);
374   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
375   setOperationAction(ISD::FREM , MVT::f64, Expand);
376   setOperationAction(ISD::FPOW , MVT::f64, Expand);
377   setOperationAction(ISD::FSIN , MVT::f32, Expand);
378   setOperationAction(ISD::FCOS , MVT::f32, Expand);
379   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
380   setOperationAction(ISD::FREM , MVT::f32, Expand);
381   setOperationAction(ISD::FPOW , MVT::f32, Expand);
382   if (Subtarget.hasSPE()) {
383     setOperationAction(ISD::FMA  , MVT::f64, Expand);
384     setOperationAction(ISD::FMA  , MVT::f32, Expand);
385   } else {
386     setOperationAction(ISD::FMA  , MVT::f64, Legal);
387     setOperationAction(ISD::FMA  , MVT::f32, Legal);
388   }
389 
390   if (Subtarget.hasSPE())
391     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
392 
393   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
394 
395   // If we're enabling GP optimizations, use hardware square root
396   if (!Subtarget.hasFSQRT() &&
397       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
398         Subtarget.hasFRE()))
399     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
400 
401   if (!Subtarget.hasFSQRT() &&
402       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
403         Subtarget.hasFRES()))
404     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
405 
406   if (Subtarget.hasFCPSGN()) {
407     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
408     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
409   } else {
410     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
411     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
412   }
413 
414   if (Subtarget.hasFPRND()) {
415     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
416     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
417     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
418     setOperationAction(ISD::FROUND, MVT::f64, Legal);
419 
420     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
421     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
422     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
423     setOperationAction(ISD::FROUND, MVT::f32, Legal);
424   }
425 
426   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
427   // to speed up scalar BSWAP64.
428   // CTPOP or CTTZ were introduced in P8/P9 respectively
429   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
430   if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
431     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
432   else
433     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
434   if (Subtarget.isISA3_0()) {
435     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
436     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
437   } else {
438     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
439     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
440   }
441 
442   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
443     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
444     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
445   } else {
446     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
447     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
448   }
449 
450   // PowerPC does not have ROTR
451   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
452   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
453 
454   if (!Subtarget.useCRBits()) {
455     // PowerPC does not have Select
456     setOperationAction(ISD::SELECT, MVT::i32, Expand);
457     setOperationAction(ISD::SELECT, MVT::i64, Expand);
458     setOperationAction(ISD::SELECT, MVT::f32, Expand);
459     setOperationAction(ISD::SELECT, MVT::f64, Expand);
460   }
461 
462   // PowerPC wants to turn select_cc of FP into fsel when possible.
463   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
464   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
465 
466   // PowerPC wants to optimize integer setcc a bit
467   if (!Subtarget.useCRBits())
468     setOperationAction(ISD::SETCC, MVT::i32, Custom);
469 
470   if (Subtarget.hasFPU()) {
471     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
472     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
473     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
474 
475     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
476     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
477     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
478   }
479 
480   // PowerPC does not have BRCOND which requires SetCC
481   if (!Subtarget.useCRBits())
482     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
483 
484   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
485 
486   if (Subtarget.hasSPE()) {
487     // SPE has built-in conversions
488     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
489     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
490     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
491     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
492     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
493     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
494 
495     // SPE supports signaling compare of f32/f64.
496     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
497     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
498   } else {
499     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
500     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
501     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
502 
503     // PowerPC does not have [U|S]INT_TO_FP
504     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
505     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
506     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
507     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
508   }
509 
510   if (Subtarget.hasDirectMove() && isPPC64) {
511     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
512     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
513     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
514     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
515     if (TM.Options.UnsafeFPMath) {
516       setOperationAction(ISD::LRINT, MVT::f64, Legal);
517       setOperationAction(ISD::LRINT, MVT::f32, Legal);
518       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
519       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
520       setOperationAction(ISD::LROUND, MVT::f64, Legal);
521       setOperationAction(ISD::LROUND, MVT::f32, Legal);
522       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
523       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
524     }
525   } else {
526     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
527     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
528     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
529     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
530   }
531 
532   // We cannot sextinreg(i1).  Expand to shifts.
533   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
534 
535   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537   // support continuation, user-level threading, and etc.. As a result, no
538   // other SjLj exception interfaces are implemented and please don't build
539   // your own exception handling based on them.
540   // LLVM/Clang supports zero-cost DWARF exception handling.
541   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543 
544   // We want to legalize GlobalAddress and ConstantPool nodes into the
545   // appropriate instructions to materialize the address.
546   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
547   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
548   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
549   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
550   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
551   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
552   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
553   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
554   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
555   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
556 
557   // TRAP is legal.
558   setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 
560   // TRAMPOLINE is custom lowered.
561   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
562   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
563 
564   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
565   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
566 
567   if (Subtarget.is64BitELFABI()) {
568     // VAARG always uses double-word chunks, so promote anything smaller.
569     setOperationAction(ISD::VAARG, MVT::i1, Promote);
570     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
571     setOperationAction(ISD::VAARG, MVT::i8, Promote);
572     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
573     setOperationAction(ISD::VAARG, MVT::i16, Promote);
574     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
575     setOperationAction(ISD::VAARG, MVT::i32, Promote);
576     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
577     setOperationAction(ISD::VAARG, MVT::Other, Expand);
578   } else if (Subtarget.is32BitELFABI()) {
579     // VAARG is custom lowered with the 32-bit SVR4 ABI.
580     setOperationAction(ISD::VAARG, MVT::Other, Custom);
581     setOperationAction(ISD::VAARG, MVT::i64, Custom);
582   } else
583     setOperationAction(ISD::VAARG, MVT::Other, Expand);
584 
585   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
586   if (Subtarget.is32BitELFABI())
587     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
588   else
589     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
590 
591   // Use the default implementation.
592   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
593   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
594   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
595   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
596   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
597   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
598   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
599   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
600   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
601 
602   // We want to custom lower some of our intrinsics.
603   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
604   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
605   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
606 
607   // To handle counter-based loop conditions.
608   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
609 
610   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
611   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
612   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
613   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
614 
615   // Comparisons that require checking two conditions.
616   if (Subtarget.hasSPE()) {
617     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
618     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
619     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
620     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
621   }
622   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
623   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
624   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
625   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
626   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
627   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
628   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
629   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
630   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
631   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
632   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
633   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
634 
635   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
636   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
637 
638   if (Subtarget.has64BitSupport()) {
639     // They also have instructions for converting between i64 and fp.
640     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
641     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
642     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
643     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
644     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
645     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
646     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
647     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
648     // This is just the low 32 bits of a (signed) fp->i64 conversion.
649     // We cannot do this with Promote because i64 is not a legal type.
650     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
651     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
652 
653     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
654       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
655       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
656     }
657   } else {
658     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
659     if (Subtarget.hasSPE()) {
660       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
661       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
662     } else {
663       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
664       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
665     }
666   }
667 
668   // With the instructions enabled under FPCVT, we can do everything.
669   if (Subtarget.hasFPCVT()) {
670     if (Subtarget.has64BitSupport()) {
671       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
672       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
673       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
674       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
675       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
676       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
677       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
678       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
679     }
680 
681     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
682     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
683     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
684     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
685     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
686     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
687     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
688     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
689   }
690 
691   if (Subtarget.use64BitRegs()) {
692     // 64-bit PowerPC implementations can support i64 types directly
693     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
694     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
695     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
696     // 64-bit PowerPC wants to expand i128 shifts itself.
697     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
698     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
699     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
700   } else {
701     // 32-bit PowerPC wants to expand i64 shifts itself.
702     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
703     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
704     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
705   }
706 
707   // PowerPC has better expansions for funnel shifts than the generic
708   // TargetLowering::expandFunnelShift.
709   if (Subtarget.has64BitSupport()) {
710     setOperationAction(ISD::FSHL, MVT::i64, Custom);
711     setOperationAction(ISD::FSHR, MVT::i64, Custom);
712   }
713   setOperationAction(ISD::FSHL, MVT::i32, Custom);
714   setOperationAction(ISD::FSHR, MVT::i32, Custom);
715 
716   if (Subtarget.hasVSX()) {
717     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
718     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
719     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
720     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
721   }
722 
723   if (Subtarget.hasAltivec()) {
724     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
725       setOperationAction(ISD::SADDSAT, VT, Legal);
726       setOperationAction(ISD::SSUBSAT, VT, Legal);
727       setOperationAction(ISD::UADDSAT, VT, Legal);
728       setOperationAction(ISD::USUBSAT, VT, Legal);
729     }
730     // First set operation action for all vector types to expand. Then we
731     // will selectively turn on ones that can be effectively codegen'd.
732     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
733       // add/sub are legal for all supported vector VT's.
734       setOperationAction(ISD::ADD, VT, Legal);
735       setOperationAction(ISD::SUB, VT, Legal);
736 
737       // For v2i64, these are only valid with P8Vector. This is corrected after
738       // the loop.
739       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
740         setOperationAction(ISD::SMAX, VT, Legal);
741         setOperationAction(ISD::SMIN, VT, Legal);
742         setOperationAction(ISD::UMAX, VT, Legal);
743         setOperationAction(ISD::UMIN, VT, Legal);
744       }
745       else {
746         setOperationAction(ISD::SMAX, VT, Expand);
747         setOperationAction(ISD::SMIN, VT, Expand);
748         setOperationAction(ISD::UMAX, VT, Expand);
749         setOperationAction(ISD::UMIN, VT, Expand);
750       }
751 
752       if (Subtarget.hasVSX()) {
753         setOperationAction(ISD::FMAXNUM, VT, Legal);
754         setOperationAction(ISD::FMINNUM, VT, Legal);
755       }
756 
757       // Vector instructions introduced in P8
758       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
759         setOperationAction(ISD::CTPOP, VT, Legal);
760         setOperationAction(ISD::CTLZ, VT, Legal);
761       }
762       else {
763         setOperationAction(ISD::CTPOP, VT, Expand);
764         setOperationAction(ISD::CTLZ, VT, Expand);
765       }
766 
767       // Vector instructions introduced in P9
768       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
769         setOperationAction(ISD::CTTZ, VT, Legal);
770       else
771         setOperationAction(ISD::CTTZ, VT, Expand);
772 
773       // We promote all shuffles to v16i8.
774       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
775       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
776 
777       // We promote all non-typed operations to v4i32.
778       setOperationAction(ISD::AND   , VT, Promote);
779       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
780       setOperationAction(ISD::OR    , VT, Promote);
781       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
782       setOperationAction(ISD::XOR   , VT, Promote);
783       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
784       setOperationAction(ISD::LOAD  , VT, Promote);
785       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
786       setOperationAction(ISD::SELECT, VT, Promote);
787       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
788       setOperationAction(ISD::VSELECT, VT, Legal);
789       setOperationAction(ISD::SELECT_CC, VT, Promote);
790       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
791       setOperationAction(ISD::STORE, VT, Promote);
792       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
793 
794       // No other operations are legal.
795       setOperationAction(ISD::MUL , VT, Expand);
796       setOperationAction(ISD::SDIV, VT, Expand);
797       setOperationAction(ISD::SREM, VT, Expand);
798       setOperationAction(ISD::UDIV, VT, Expand);
799       setOperationAction(ISD::UREM, VT, Expand);
800       setOperationAction(ISD::FDIV, VT, Expand);
801       setOperationAction(ISD::FREM, VT, Expand);
802       setOperationAction(ISD::FNEG, VT, Expand);
803       setOperationAction(ISD::FSQRT, VT, Expand);
804       setOperationAction(ISD::FLOG, VT, Expand);
805       setOperationAction(ISD::FLOG10, VT, Expand);
806       setOperationAction(ISD::FLOG2, VT, Expand);
807       setOperationAction(ISD::FEXP, VT, Expand);
808       setOperationAction(ISD::FEXP2, VT, Expand);
809       setOperationAction(ISD::FSIN, VT, Expand);
810       setOperationAction(ISD::FCOS, VT, Expand);
811       setOperationAction(ISD::FABS, VT, Expand);
812       setOperationAction(ISD::FFLOOR, VT, Expand);
813       setOperationAction(ISD::FCEIL,  VT, Expand);
814       setOperationAction(ISD::FTRUNC, VT, Expand);
815       setOperationAction(ISD::FRINT,  VT, Expand);
816       setOperationAction(ISD::FNEARBYINT, VT, Expand);
817       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
818       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
819       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
820       setOperationAction(ISD::MULHU, VT, Expand);
821       setOperationAction(ISD::MULHS, VT, Expand);
822       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
823       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
824       setOperationAction(ISD::UDIVREM, VT, Expand);
825       setOperationAction(ISD::SDIVREM, VT, Expand);
826       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
827       setOperationAction(ISD::FPOW, VT, Expand);
828       setOperationAction(ISD::BSWAP, VT, Expand);
829       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
830       setOperationAction(ISD::ROTL, VT, Expand);
831       setOperationAction(ISD::ROTR, VT, Expand);
832 
833       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
834         setTruncStoreAction(VT, InnerVT, Expand);
835         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
836         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
837         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
838       }
839     }
840     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
841     if (!Subtarget.hasP8Vector()) {
842       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
843       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
844       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
845       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
846     }
847 
848     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
849     // with merges, splats, etc.
850     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
851 
852     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
853     // are cheap, so handle them before they get expanded to scalar.
854     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
855     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
856     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
857     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
858     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
859 
860     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
861     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
862     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
863     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
864     setOperationAction(ISD::SELECT, MVT::v4i32,
865                        Subtarget.useCRBits() ? Legal : Expand);
866     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
867     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
868     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
869     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
870     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
871     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
872     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
873     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
874     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
875     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
876     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
877     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
878     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
879 
880     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
881     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
882     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
883     if (Subtarget.hasAltivec())
884       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
885         setOperationAction(ISD::ROTL, VT, Legal);
886     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
887     if (Subtarget.hasP8Altivec())
888       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
889 
890     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
891     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
892     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
893     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
894 
895     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
896     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
897 
898     if (Subtarget.hasVSX()) {
899       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
900       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
901       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
902     }
903 
904     if (Subtarget.hasP8Altivec())
905       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
906     else
907       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
908 
909     if (Subtarget.isISA3_1()) {
910       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
911       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
912       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
913       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
914       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
915       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
916       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
917       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
918       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
919       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
920       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
921       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
922       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
923       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
924       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
925       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
926       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
927       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
928     }
929 
930     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
931     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
932 
933     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
934     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
935 
936     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
937     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
938     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
939     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
940 
941     // Altivec does not contain unordered floating-point compare instructions
942     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
943     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
944     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
945     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
946 
947     if (Subtarget.hasVSX()) {
948       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
949       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
950       if (Subtarget.hasP8Vector()) {
951         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
952         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
953       }
954       if (Subtarget.hasDirectMove() && isPPC64) {
955         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
956         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
957         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
958         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
959         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
960         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
961         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
962         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
963       }
964       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
965 
966       // The nearbyint variants are not allowed to raise the inexact exception
967       // so we can only code-gen them with unsafe math.
968       if (TM.Options.UnsafeFPMath) {
969         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
970         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
971       }
972 
973       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
974       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
975       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
976       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
977       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
978       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
979       setOperationAction(ISD::FROUND, MVT::f64, Legal);
980       setOperationAction(ISD::FRINT, MVT::f64, Legal);
981 
982       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
983       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
984       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
985       setOperationAction(ISD::FROUND, MVT::f32, Legal);
986       setOperationAction(ISD::FRINT, MVT::f32, Legal);
987 
988       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
989       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
990 
991       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
992       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
993 
994       // Share the Altivec comparison restrictions.
995       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
996       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
997       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
998       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
999 
1000       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1001       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1002 
1003       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1004 
1005       if (Subtarget.hasP8Vector())
1006         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1007 
1008       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1009 
1010       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1011       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1012       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1013 
1014       if (Subtarget.hasP8Altivec()) {
1015         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1016         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1017         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1018 
1019         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1020         // SRL, but not for SRA because of the instructions available:
1021         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1022         // doing
1023         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1024         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1025         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1026 
1027         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1028       }
1029       else {
1030         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1031         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1032         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1033 
1034         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1035 
1036         // VSX v2i64 only supports non-arithmetic operations.
1037         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1038         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1039       }
1040 
1041       if (Subtarget.isISA3_1())
1042         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1043       else
1044         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1045 
1046       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1047       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1048       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1049       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1050 
1051       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1052 
1053       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1054       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1055       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1056       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1057       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1058       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1059       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1060       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1061 
1062       // Custom handling for partial vectors of integers converted to
1063       // floating point. We already have optimal handling for v2i32 through
1064       // the DAG combine, so those aren't necessary.
1065       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1066       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1067       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1068       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1069       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1070       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1071       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1072       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1073       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1074       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1075       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1076       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1077       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1078       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1079       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1080       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1081 
1082       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1083       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1084       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1085       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1086       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1087       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1088 
1089       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1090       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1091 
1092       // Handle constrained floating-point operations of vector.
1093       // The predictor is `hasVSX` because altivec instruction has
1094       // no exception but VSX vector instruction has.
1095       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1096       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1097       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1098       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1099       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1100       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1101       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1102       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1103       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1104       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1105       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1106       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1107       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1108 
1109       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1110       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1111       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1112       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1113       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1114       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1115       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1116       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1117       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1118       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1119       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1120       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1121       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1122 
1123       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1124       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1125 
1126       for (MVT FPT : MVT::fp_valuetypes())
1127         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1128 
1129       // Expand the SELECT to SELECT_CC
1130       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1131 
1132       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1133       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1134 
1135       // No implementation for these ops for PowerPC.
1136       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1137       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1138       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1139       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1140       setOperationAction(ISD::FREM, MVT::f128, Expand);
1141     }
1142 
1143     if (Subtarget.hasP8Altivec()) {
1144       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1145       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1146     }
1147 
1148     if (Subtarget.hasP9Vector()) {
1149       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1150       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1151 
1152       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1153       // SRL, but not for SRA because of the instructions available:
1154       // VS{RL} and VS{RL}O.
1155       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1156       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1157       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1158 
1159       setOperationAction(ISD::FADD, MVT::f128, Legal);
1160       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1161       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1162       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1163       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1164 
1165       setOperationAction(ISD::FMA, MVT::f128, Legal);
1166       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1167       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1168       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1169       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1170       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1171       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1172 
1173       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1174       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1175       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1176       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1177       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1178       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1179 
1180       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1181       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1182       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1183 
1184       // Handle constrained floating-point operations of fp128
1185       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1186       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1187       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1188       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1189       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1190       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1191       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1192       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1193       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1194       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1195       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1196       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1197       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1198       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1199       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1200       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1201       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1202       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1203       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1204       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1205     } else if (Subtarget.hasVSX()) {
1206       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1207       setOperationAction(ISD::STORE, MVT::f128, Promote);
1208 
1209       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1210       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1211 
1212       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1213       // fp_to_uint and int_to_fp.
1214       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1215       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1216 
1217       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1218       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1219       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1220       setOperationAction(ISD::FABS, MVT::f128, Expand);
1221       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1222       setOperationAction(ISD::FMA, MVT::f128, Expand);
1223       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1224 
1225       // Expand the fp_extend if the target type is fp128.
1226       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1227       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1228 
1229       // Expand the fp_round if the source type is fp128.
1230       for (MVT VT : {MVT::f32, MVT::f64}) {
1231         setOperationAction(ISD::FP_ROUND, VT, Custom);
1232         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1233       }
1234 
1235       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1236       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1237       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1238       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1239 
1240       // Lower following f128 select_cc pattern:
1241       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1242       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1243 
1244       // We need to handle f128 SELECT_CC with integer result type.
1245       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1246       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1247     }
1248 
1249     if (Subtarget.hasP9Altivec()) {
1250       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1251       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1252 
1253       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1254       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1255       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1256       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1257       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1258       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1259       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1260     }
1261 
1262     if (Subtarget.isISA3_1())
1263       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1264   }
1265 
1266   if (Subtarget.pairedVectorMemops()) {
1267     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1268     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1269     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1270   }
1271   if (Subtarget.hasMMA()) {
1272     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1273     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1274     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1275     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1276   }
1277 
1278   if (Subtarget.has64BitSupport())
1279     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1280 
1281   if (Subtarget.isISA3_1())
1282     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1283 
1284   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1285 
1286   if (!isPPC64) {
1287     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1288     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1289   }
1290 
1291   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1292     setMaxAtomicSizeInBitsSupported(128);
1293     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1294     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1295     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1296   }
1297 
1298   setBooleanContents(ZeroOrOneBooleanContent);
1299 
1300   if (Subtarget.hasAltivec()) {
1301     // Altivec instructions set fields to all zeros or all ones.
1302     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1303   }
1304 
1305   if (!isPPC64) {
1306     // These libcalls are not available in 32-bit.
1307     setLibcallName(RTLIB::SHL_I128, nullptr);
1308     setLibcallName(RTLIB::SRL_I128, nullptr);
1309     setLibcallName(RTLIB::SRA_I128, nullptr);
1310     setLibcallName(RTLIB::MULO_I64, nullptr);
1311   }
1312 
1313   if (!isPPC64)
1314     setMaxAtomicSizeInBitsSupported(32);
1315 
1316   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1317 
1318   // We have target-specific dag combine patterns for the following nodes:
1319   setTargetDAGCombine(ISD::ADD);
1320   setTargetDAGCombine(ISD::SHL);
1321   setTargetDAGCombine(ISD::SRA);
1322   setTargetDAGCombine(ISD::SRL);
1323   setTargetDAGCombine(ISD::MUL);
1324   setTargetDAGCombine(ISD::FMA);
1325   setTargetDAGCombine(ISD::SINT_TO_FP);
1326   setTargetDAGCombine(ISD::BUILD_VECTOR);
1327   if (Subtarget.hasFPCVT())
1328     setTargetDAGCombine(ISD::UINT_TO_FP);
1329   setTargetDAGCombine(ISD::LOAD);
1330   setTargetDAGCombine(ISD::STORE);
1331   setTargetDAGCombine(ISD::BR_CC);
1332   if (Subtarget.useCRBits())
1333     setTargetDAGCombine(ISD::BRCOND);
1334   setTargetDAGCombine(ISD::BSWAP);
1335   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1336   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1337   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1338 
1339   setTargetDAGCombine(ISD::SIGN_EXTEND);
1340   setTargetDAGCombine(ISD::ZERO_EXTEND);
1341   setTargetDAGCombine(ISD::ANY_EXTEND);
1342 
1343   setTargetDAGCombine(ISD::TRUNCATE);
1344   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1345 
1346 
1347   if (Subtarget.useCRBits()) {
1348     setTargetDAGCombine(ISD::TRUNCATE);
1349     setTargetDAGCombine(ISD::SETCC);
1350     setTargetDAGCombine(ISD::SELECT_CC);
1351   }
1352 
1353   if (Subtarget.hasP9Altivec()) {
1354     setTargetDAGCombine(ISD::ABS);
1355     setTargetDAGCombine(ISD::VSELECT);
1356   }
1357 
1358   setLibcallName(RTLIB::LOG_F128, "logf128");
1359   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1360   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1361   setLibcallName(RTLIB::EXP_F128, "expf128");
1362   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1363   setLibcallName(RTLIB::SIN_F128, "sinf128");
1364   setLibcallName(RTLIB::COS_F128, "cosf128");
1365   setLibcallName(RTLIB::POW_F128, "powf128");
1366   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1367   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1368   setLibcallName(RTLIB::REM_F128, "fmodf128");
1369   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1370   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1371   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1372   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1373   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1374   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1375   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1376   setLibcallName(RTLIB::RINT_F128, "rintf128");
1377   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1378   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1379   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1380   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1381 
1382   // With 32 condition bits, we don't need to sink (and duplicate) compares
1383   // aggressively in CodeGenPrep.
1384   if (Subtarget.useCRBits()) {
1385     setHasMultipleConditionRegisters();
1386     setJumpIsExpensive();
1387   }
1388 
1389   setMinFunctionAlignment(Align(4));
1390 
1391   switch (Subtarget.getCPUDirective()) {
1392   default: break;
1393   case PPC::DIR_970:
1394   case PPC::DIR_A2:
1395   case PPC::DIR_E500:
1396   case PPC::DIR_E500mc:
1397   case PPC::DIR_E5500:
1398   case PPC::DIR_PWR4:
1399   case PPC::DIR_PWR5:
1400   case PPC::DIR_PWR5X:
1401   case PPC::DIR_PWR6:
1402   case PPC::DIR_PWR6X:
1403   case PPC::DIR_PWR7:
1404   case PPC::DIR_PWR8:
1405   case PPC::DIR_PWR9:
1406   case PPC::DIR_PWR10:
1407   case PPC::DIR_PWR_FUTURE:
1408     setPrefLoopAlignment(Align(16));
1409     setPrefFunctionAlignment(Align(16));
1410     break;
1411   }
1412 
1413   if (Subtarget.enableMachineScheduler())
1414     setSchedulingPreference(Sched::Source);
1415   else
1416     setSchedulingPreference(Sched::Hybrid);
1417 
1418   computeRegisterProperties(STI.getRegisterInfo());
1419 
1420   // The Freescale cores do better with aggressive inlining of memcpy and
1421   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1422   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1423       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1424     MaxStoresPerMemset = 32;
1425     MaxStoresPerMemsetOptSize = 16;
1426     MaxStoresPerMemcpy = 32;
1427     MaxStoresPerMemcpyOptSize = 8;
1428     MaxStoresPerMemmove = 32;
1429     MaxStoresPerMemmoveOptSize = 8;
1430   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1431     // The A2 also benefits from (very) aggressive inlining of memcpy and
1432     // friends. The overhead of a the function call, even when warm, can be
1433     // over one hundred cycles.
1434     MaxStoresPerMemset = 128;
1435     MaxStoresPerMemcpy = 128;
1436     MaxStoresPerMemmove = 128;
1437     MaxLoadsPerMemcmp = 128;
1438   } else {
1439     MaxLoadsPerMemcmp = 8;
1440     MaxLoadsPerMemcmpOptSize = 4;
1441   }
1442 
1443   IsStrictFPEnabled = true;
1444 
1445   // Let the subtarget (CPU) decide if a predictable select is more expensive
1446   // than the corresponding branch. This information is used in CGP to decide
1447   // when to convert selects into branches.
1448   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1449 }
1450 
1451 // *********************************** NOTE ************************************
1452 // For selecting load and store instructions, the addressing modes are defined
1453 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1454 // patterns to match the load the store instructions.
1455 //
1456 // The TD definitions for the addressing modes correspond to their respective
1457 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1458 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1459 // address mode flags of a particular node. Afterwards, the computed address
1460 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1461 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1462 // accordingly, based on the preferred addressing mode.
1463 //
1464 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1465 // MemOpFlags contains all the possible flags that can be used to compute the
1466 // optimal addressing mode for load and store instructions.
1467 // AddrMode contains all the possible load and store addressing modes available
1468 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1469 //
1470 // When adding new load and store instructions, it is possible that new address
1471 // flags may need to be added into MemOpFlags, and a new addressing mode will
1472 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1473 // of the minimal and main distinguishing address flags for the new load/store
1474 // instructions) will need to be added into initializeAddrModeMap() below.
1475 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1476 // need to be updated to account for selecting the optimal addressing mode.
1477 // *****************************************************************************
1478 /// Initialize the map that relates the different addressing modes of the load
1479 /// and store instructions to a set of flags. This ensures the load/store
1480 /// instruction is correctly matched during instruction selection.
1481 void PPCTargetLowering::initializeAddrModeMap() {
1482   AddrModesMap[PPC::AM_DForm] = {
1483       // LWZ, STW
1484       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1485       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1486       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1487       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1488       // LBZ, LHZ, STB, STH
1489       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1490       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1491       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1492       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1493       // LHA
1494       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1495       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1496       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1497       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1498       // LFS, LFD, STFS, STFD
1499       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1500       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1501       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1502       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1503   };
1504   AddrModesMap[PPC::AM_DSForm] = {
1505       // LWA
1506       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1507       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1508       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1509       // LD, STD
1510       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1511       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1512       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1513       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1514       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1515       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1516       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1517   };
1518   AddrModesMap[PPC::AM_DQForm] = {
1519       // LXV, STXV
1520       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1521       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1522       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1523   };
1524   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1525                                        PPC::MOF_SubtargetP10};
1526   // TODO: Add mapping for quadword load/store.
1527 }
1528 
1529 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1530 /// the desired ByVal argument alignment.
1531 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1532   if (MaxAlign == MaxMaxAlign)
1533     return;
1534   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1535     if (MaxMaxAlign >= 32 &&
1536         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1537       MaxAlign = Align(32);
1538     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1539              MaxAlign < 16)
1540       MaxAlign = Align(16);
1541   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1542     Align EltAlign;
1543     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1544     if (EltAlign > MaxAlign)
1545       MaxAlign = EltAlign;
1546   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1547     for (auto *EltTy : STy->elements()) {
1548       Align EltAlign;
1549       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1550       if (EltAlign > MaxAlign)
1551         MaxAlign = EltAlign;
1552       if (MaxAlign == MaxMaxAlign)
1553         break;
1554     }
1555   }
1556 }
1557 
1558 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1559 /// function arguments in the caller parameter area.
1560 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1561                                                   const DataLayout &DL) const {
1562   // 16byte and wider vectors are passed on 16byte boundary.
1563   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1564   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1565   if (Subtarget.hasAltivec())
1566     getMaxByValAlign(Ty, Alignment, Align(16));
1567   return Alignment.value();
1568 }
1569 
1570 bool PPCTargetLowering::useSoftFloat() const {
1571   return Subtarget.useSoftFloat();
1572 }
1573 
1574 bool PPCTargetLowering::hasSPE() const {
1575   return Subtarget.hasSPE();
1576 }
1577 
1578 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1579   return VT.isScalarInteger();
1580 }
1581 
1582 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1583   switch ((PPCISD::NodeType)Opcode) {
1584   case PPCISD::FIRST_NUMBER:    break;
1585   case PPCISD::FSEL:            return "PPCISD::FSEL";
1586   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1587   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1588   case PPCISD::FCFID:           return "PPCISD::FCFID";
1589   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1590   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1591   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1592   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1593   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1594   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1595   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1596   case PPCISD::FP_TO_UINT_IN_VSR:
1597                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1598   case PPCISD::FP_TO_SINT_IN_VSR:
1599                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1600   case PPCISD::FRE:             return "PPCISD::FRE";
1601   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1602   case PPCISD::FTSQRT:
1603     return "PPCISD::FTSQRT";
1604   case PPCISD::FSQRT:
1605     return "PPCISD::FSQRT";
1606   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1607   case PPCISD::VPERM:           return "PPCISD::VPERM";
1608   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1609   case PPCISD::XXSPLTI_SP_TO_DP:
1610     return "PPCISD::XXSPLTI_SP_TO_DP";
1611   case PPCISD::XXSPLTI32DX:
1612     return "PPCISD::XXSPLTI32DX";
1613   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1614   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1615   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1616   case PPCISD::CMPB:            return "PPCISD::CMPB";
1617   case PPCISD::Hi:              return "PPCISD::Hi";
1618   case PPCISD::Lo:              return "PPCISD::Lo";
1619   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1620   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1621   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1622   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1623   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1624   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1625   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1626   case PPCISD::SRL:             return "PPCISD::SRL";
1627   case PPCISD::SRA:             return "PPCISD::SRA";
1628   case PPCISD::SHL:             return "PPCISD::SHL";
1629   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1630   case PPCISD::CALL:            return "PPCISD::CALL";
1631   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1632   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1633   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1634   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1635   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1636   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1637   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1638   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1639   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1640   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1641   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1642   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1643   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1644   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1645   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1646   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1647     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1648   case PPCISD::ANDI_rec_1_EQ_BIT:
1649     return "PPCISD::ANDI_rec_1_EQ_BIT";
1650   case PPCISD::ANDI_rec_1_GT_BIT:
1651     return "PPCISD::ANDI_rec_1_GT_BIT";
1652   case PPCISD::VCMP:            return "PPCISD::VCMP";
1653   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1654   case PPCISD::LBRX:            return "PPCISD::LBRX";
1655   case PPCISD::STBRX:           return "PPCISD::STBRX";
1656   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1657   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1658   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1659   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1660   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1661   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1662   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1663   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1664   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1665   case PPCISD::ST_VSR_SCAL_INT:
1666                                 return "PPCISD::ST_VSR_SCAL_INT";
1667   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1668   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1669   case PPCISD::BDZ:             return "PPCISD::BDZ";
1670   case PPCISD::MFFS:            return "PPCISD::MFFS";
1671   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1672   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1673   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1674   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1675   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1676   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1677   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1678   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1679   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1680   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1681   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1682   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1683   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1684   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1685   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1686   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1687   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1688   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1689   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1690   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1691   case PPCISD::PADDI_DTPREL:
1692     return "PPCISD::PADDI_DTPREL";
1693   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1694   case PPCISD::SC:              return "PPCISD::SC";
1695   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1696   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1697   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1698   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1699   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1700   case PPCISD::VABSD:           return "PPCISD::VABSD";
1701   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1702   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1703   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1704   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1705   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1706   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1707   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1708   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1709     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1710   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1711     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1712   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1713   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1714   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1715   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1716   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1717   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1718   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1719   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1720   case PPCISD::STRICT_FADDRTZ:
1721     return "PPCISD::STRICT_FADDRTZ";
1722   case PPCISD::STRICT_FCTIDZ:
1723     return "PPCISD::STRICT_FCTIDZ";
1724   case PPCISD::STRICT_FCTIWZ:
1725     return "PPCISD::STRICT_FCTIWZ";
1726   case PPCISD::STRICT_FCTIDUZ:
1727     return "PPCISD::STRICT_FCTIDUZ";
1728   case PPCISD::STRICT_FCTIWUZ:
1729     return "PPCISD::STRICT_FCTIWUZ";
1730   case PPCISD::STRICT_FCFID:
1731     return "PPCISD::STRICT_FCFID";
1732   case PPCISD::STRICT_FCFIDU:
1733     return "PPCISD::STRICT_FCFIDU";
1734   case PPCISD::STRICT_FCFIDS:
1735     return "PPCISD::STRICT_FCFIDS";
1736   case PPCISD::STRICT_FCFIDUS:
1737     return "PPCISD::STRICT_FCFIDUS";
1738   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1739   }
1740   return nullptr;
1741 }
1742 
1743 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1744                                           EVT VT) const {
1745   if (!VT.isVector())
1746     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1747 
1748   return VT.changeVectorElementTypeToInteger();
1749 }
1750 
1751 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1752   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1753   return true;
1754 }
1755 
1756 //===----------------------------------------------------------------------===//
1757 // Node matching predicates, for use by the tblgen matching code.
1758 //===----------------------------------------------------------------------===//
1759 
1760 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1761 static bool isFloatingPointZero(SDValue Op) {
1762   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1763     return CFP->getValueAPF().isZero();
1764   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1765     // Maybe this has already been legalized into the constant pool?
1766     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1767       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1768         return CFP->getValueAPF().isZero();
1769   }
1770   return false;
1771 }
1772 
1773 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1774 /// true if Op is undef or if it matches the specified value.
1775 static bool isConstantOrUndef(int Op, int Val) {
1776   return Op < 0 || Op == Val;
1777 }
1778 
1779 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1780 /// VPKUHUM instruction.
1781 /// The ShuffleKind distinguishes between big-endian operations with
1782 /// two different inputs (0), either-endian operations with two identical
1783 /// inputs (1), and little-endian operations with two different inputs (2).
1784 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1785 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1786                                SelectionDAG &DAG) {
1787   bool IsLE = DAG.getDataLayout().isLittleEndian();
1788   if (ShuffleKind == 0) {
1789     if (IsLE)
1790       return false;
1791     for (unsigned i = 0; i != 16; ++i)
1792       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1793         return false;
1794   } else if (ShuffleKind == 2) {
1795     if (!IsLE)
1796       return false;
1797     for (unsigned i = 0; i != 16; ++i)
1798       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1799         return false;
1800   } else if (ShuffleKind == 1) {
1801     unsigned j = IsLE ? 0 : 1;
1802     for (unsigned i = 0; i != 8; ++i)
1803       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1804           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1805         return false;
1806   }
1807   return true;
1808 }
1809 
1810 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1811 /// VPKUWUM instruction.
1812 /// The ShuffleKind distinguishes between big-endian operations with
1813 /// two different inputs (0), either-endian operations with two identical
1814 /// inputs (1), and little-endian operations with two different inputs (2).
1815 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1816 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1817                                SelectionDAG &DAG) {
1818   bool IsLE = DAG.getDataLayout().isLittleEndian();
1819   if (ShuffleKind == 0) {
1820     if (IsLE)
1821       return false;
1822     for (unsigned i = 0; i != 16; i += 2)
1823       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1824           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1825         return false;
1826   } else if (ShuffleKind == 2) {
1827     if (!IsLE)
1828       return false;
1829     for (unsigned i = 0; i != 16; i += 2)
1830       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1831           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1832         return false;
1833   } else if (ShuffleKind == 1) {
1834     unsigned j = IsLE ? 0 : 2;
1835     for (unsigned i = 0; i != 8; i += 2)
1836       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1837           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1838           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1839           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1840         return false;
1841   }
1842   return true;
1843 }
1844 
1845 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1846 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1847 /// current subtarget.
1848 ///
1849 /// The ShuffleKind distinguishes between big-endian operations with
1850 /// two different inputs (0), either-endian operations with two identical
1851 /// inputs (1), and little-endian operations with two different inputs (2).
1852 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1853 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1854                                SelectionDAG &DAG) {
1855   const PPCSubtarget& Subtarget =
1856       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1857   if (!Subtarget.hasP8Vector())
1858     return false;
1859 
1860   bool IsLE = DAG.getDataLayout().isLittleEndian();
1861   if (ShuffleKind == 0) {
1862     if (IsLE)
1863       return false;
1864     for (unsigned i = 0; i != 16; i += 4)
1865       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1866           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1867           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1868           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1869         return false;
1870   } else if (ShuffleKind == 2) {
1871     if (!IsLE)
1872       return false;
1873     for (unsigned i = 0; i != 16; i += 4)
1874       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1875           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1876           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1877           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1878         return false;
1879   } else if (ShuffleKind == 1) {
1880     unsigned j = IsLE ? 0 : 4;
1881     for (unsigned i = 0; i != 8; i += 4)
1882       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1883           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1884           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1885           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1886           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1887           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1888           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1889           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1890         return false;
1891   }
1892   return true;
1893 }
1894 
1895 /// isVMerge - Common function, used to match vmrg* shuffles.
1896 ///
1897 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1898                      unsigned LHSStart, unsigned RHSStart) {
1899   if (N->getValueType(0) != MVT::v16i8)
1900     return false;
1901   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1902          "Unsupported merge size!");
1903 
1904   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1905     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1906       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1907                              LHSStart+j+i*UnitSize) ||
1908           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1909                              RHSStart+j+i*UnitSize))
1910         return false;
1911     }
1912   return true;
1913 }
1914 
1915 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1916 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1917 /// The ShuffleKind distinguishes between big-endian merges with two
1918 /// different inputs (0), either-endian merges with two identical inputs (1),
1919 /// and little-endian merges with two different inputs (2).  For the latter,
1920 /// the input operands are swapped (see PPCInstrAltivec.td).
1921 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1922                              unsigned ShuffleKind, SelectionDAG &DAG) {
1923   if (DAG.getDataLayout().isLittleEndian()) {
1924     if (ShuffleKind == 1) // unary
1925       return isVMerge(N, UnitSize, 0, 0);
1926     else if (ShuffleKind == 2) // swapped
1927       return isVMerge(N, UnitSize, 0, 16);
1928     else
1929       return false;
1930   } else {
1931     if (ShuffleKind == 1) // unary
1932       return isVMerge(N, UnitSize, 8, 8);
1933     else if (ShuffleKind == 0) // normal
1934       return isVMerge(N, UnitSize, 8, 24);
1935     else
1936       return false;
1937   }
1938 }
1939 
1940 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1941 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1942 /// The ShuffleKind distinguishes between big-endian merges with two
1943 /// different inputs (0), either-endian merges with two identical inputs (1),
1944 /// and little-endian merges with two different inputs (2).  For the latter,
1945 /// the input operands are swapped (see PPCInstrAltivec.td).
1946 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1947                              unsigned ShuffleKind, SelectionDAG &DAG) {
1948   if (DAG.getDataLayout().isLittleEndian()) {
1949     if (ShuffleKind == 1) // unary
1950       return isVMerge(N, UnitSize, 8, 8);
1951     else if (ShuffleKind == 2) // swapped
1952       return isVMerge(N, UnitSize, 8, 24);
1953     else
1954       return false;
1955   } else {
1956     if (ShuffleKind == 1) // unary
1957       return isVMerge(N, UnitSize, 0, 0);
1958     else if (ShuffleKind == 0) // normal
1959       return isVMerge(N, UnitSize, 0, 16);
1960     else
1961       return false;
1962   }
1963 }
1964 
1965 /**
1966  * Common function used to match vmrgew and vmrgow shuffles
1967  *
1968  * The indexOffset determines whether to look for even or odd words in
1969  * the shuffle mask. This is based on the of the endianness of the target
1970  * machine.
1971  *   - Little Endian:
1972  *     - Use offset of 0 to check for odd elements
1973  *     - Use offset of 4 to check for even elements
1974  *   - Big Endian:
1975  *     - Use offset of 0 to check for even elements
1976  *     - Use offset of 4 to check for odd elements
1977  * A detailed description of the vector element ordering for little endian and
1978  * big endian can be found at
1979  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1980  * Targeting your applications - what little endian and big endian IBM XL C/C++
1981  * compiler differences mean to you
1982  *
1983  * The mask to the shuffle vector instruction specifies the indices of the
1984  * elements from the two input vectors to place in the result. The elements are
1985  * numbered in array-access order, starting with the first vector. These vectors
1986  * are always of type v16i8, thus each vector will contain 16 elements of size
1987  * 8. More info on the shuffle vector can be found in the
1988  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1989  * Language Reference.
1990  *
1991  * The RHSStartValue indicates whether the same input vectors are used (unary)
1992  * or two different input vectors are used, based on the following:
1993  *   - If the instruction uses the same vector for both inputs, the range of the
1994  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1995  *     be 0.
1996  *   - If the instruction has two different vectors then the range of the
1997  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1998  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1999  *     to 31 specify elements in the second vector).
2000  *
2001  * \param[in] N The shuffle vector SD Node to analyze
2002  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2003  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2004  * vector to the shuffle_vector instruction
2005  * \return true iff this shuffle vector represents an even or odd word merge
2006  */
2007 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2008                      unsigned RHSStartValue) {
2009   if (N->getValueType(0) != MVT::v16i8)
2010     return false;
2011 
2012   for (unsigned i = 0; i < 2; ++i)
2013     for (unsigned j = 0; j < 4; ++j)
2014       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2015                              i*RHSStartValue+j+IndexOffset) ||
2016           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2017                              i*RHSStartValue+j+IndexOffset+8))
2018         return false;
2019   return true;
2020 }
2021 
2022 /**
2023  * Determine if the specified shuffle mask is suitable for the vmrgew or
2024  * vmrgow instructions.
2025  *
2026  * \param[in] N The shuffle vector SD Node to analyze
2027  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2028  * \param[in] ShuffleKind Identify the type of merge:
2029  *   - 0 = big-endian merge with two different inputs;
2030  *   - 1 = either-endian merge with two identical inputs;
2031  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2032  *     little-endian merges).
2033  * \param[in] DAG The current SelectionDAG
2034  * \return true iff this shuffle mask
2035  */
2036 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2037                               unsigned ShuffleKind, SelectionDAG &DAG) {
2038   if (DAG.getDataLayout().isLittleEndian()) {
2039     unsigned indexOffset = CheckEven ? 4 : 0;
2040     if (ShuffleKind == 1) // Unary
2041       return isVMerge(N, indexOffset, 0);
2042     else if (ShuffleKind == 2) // swapped
2043       return isVMerge(N, indexOffset, 16);
2044     else
2045       return false;
2046   }
2047   else {
2048     unsigned indexOffset = CheckEven ? 0 : 4;
2049     if (ShuffleKind == 1) // Unary
2050       return isVMerge(N, indexOffset, 0);
2051     else if (ShuffleKind == 0) // Normal
2052       return isVMerge(N, indexOffset, 16);
2053     else
2054       return false;
2055   }
2056   return false;
2057 }
2058 
2059 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2060 /// amount, otherwise return -1.
2061 /// The ShuffleKind distinguishes between big-endian operations with two
2062 /// different inputs (0), either-endian operations with two identical inputs
2063 /// (1), and little-endian operations with two different inputs (2).  For the
2064 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2065 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2066                              SelectionDAG &DAG) {
2067   if (N->getValueType(0) != MVT::v16i8)
2068     return -1;
2069 
2070   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2071 
2072   // Find the first non-undef value in the shuffle mask.
2073   unsigned i;
2074   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2075     /*search*/;
2076 
2077   if (i == 16) return -1;  // all undef.
2078 
2079   // Otherwise, check to see if the rest of the elements are consecutively
2080   // numbered from this value.
2081   unsigned ShiftAmt = SVOp->getMaskElt(i);
2082   if (ShiftAmt < i) return -1;
2083 
2084   ShiftAmt -= i;
2085   bool isLE = DAG.getDataLayout().isLittleEndian();
2086 
2087   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2088     // Check the rest of the elements to see if they are consecutive.
2089     for (++i; i != 16; ++i)
2090       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2091         return -1;
2092   } else if (ShuffleKind == 1) {
2093     // Check the rest of the elements to see if they are consecutive.
2094     for (++i; i != 16; ++i)
2095       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2096         return -1;
2097   } else
2098     return -1;
2099 
2100   if (isLE)
2101     ShiftAmt = 16 - ShiftAmt;
2102 
2103   return ShiftAmt;
2104 }
2105 
2106 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2107 /// specifies a splat of a single element that is suitable for input to
2108 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2109 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2110   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2111          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2112 
2113   // The consecutive indices need to specify an element, not part of two
2114   // different elements.  So abandon ship early if this isn't the case.
2115   if (N->getMaskElt(0) % EltSize != 0)
2116     return false;
2117 
2118   // This is a splat operation if each element of the permute is the same, and
2119   // if the value doesn't reference the second vector.
2120   unsigned ElementBase = N->getMaskElt(0);
2121 
2122   // FIXME: Handle UNDEF elements too!
2123   if (ElementBase >= 16)
2124     return false;
2125 
2126   // Check that the indices are consecutive, in the case of a multi-byte element
2127   // splatted with a v16i8 mask.
2128   for (unsigned i = 1; i != EltSize; ++i)
2129     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2130       return false;
2131 
2132   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2133     if (N->getMaskElt(i) < 0) continue;
2134     for (unsigned j = 0; j != EltSize; ++j)
2135       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2136         return false;
2137   }
2138   return true;
2139 }
2140 
2141 /// Check that the mask is shuffling N byte elements. Within each N byte
2142 /// element of the mask, the indices could be either in increasing or
2143 /// decreasing order as long as they are consecutive.
2144 /// \param[in] N the shuffle vector SD Node to analyze
2145 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2146 /// Word/DoubleWord/QuadWord).
2147 /// \param[in] StepLen the delta indices number among the N byte element, if
2148 /// the mask is in increasing/decreasing order then it is 1/-1.
2149 /// \return true iff the mask is shuffling N byte elements.
2150 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2151                                    int StepLen) {
2152   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2153          "Unexpected element width.");
2154   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2155 
2156   unsigned NumOfElem = 16 / Width;
2157   unsigned MaskVal[16]; //  Width is never greater than 16
2158   for (unsigned i = 0; i < NumOfElem; ++i) {
2159     MaskVal[0] = N->getMaskElt(i * Width);
2160     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2161       return false;
2162     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2163       return false;
2164     }
2165 
2166     for (unsigned int j = 1; j < Width; ++j) {
2167       MaskVal[j] = N->getMaskElt(i * Width + j);
2168       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2169         return false;
2170       }
2171     }
2172   }
2173 
2174   return true;
2175 }
2176 
2177 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2178                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2179   if (!isNByteElemShuffleMask(N, 4, 1))
2180     return false;
2181 
2182   // Now we look at mask elements 0,4,8,12
2183   unsigned M0 = N->getMaskElt(0) / 4;
2184   unsigned M1 = N->getMaskElt(4) / 4;
2185   unsigned M2 = N->getMaskElt(8) / 4;
2186   unsigned M3 = N->getMaskElt(12) / 4;
2187   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2188   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2189 
2190   // Below, let H and L be arbitrary elements of the shuffle mask
2191   // where H is in the range [4,7] and L is in the range [0,3].
2192   // H, 1, 2, 3 or L, 5, 6, 7
2193   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2194       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2195     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2196     InsertAtByte = IsLE ? 12 : 0;
2197     Swap = M0 < 4;
2198     return true;
2199   }
2200   // 0, H, 2, 3 or 4, L, 6, 7
2201   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2202       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2203     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2204     InsertAtByte = IsLE ? 8 : 4;
2205     Swap = M1 < 4;
2206     return true;
2207   }
2208   // 0, 1, H, 3 or 4, 5, L, 7
2209   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2210       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2211     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2212     InsertAtByte = IsLE ? 4 : 8;
2213     Swap = M2 < 4;
2214     return true;
2215   }
2216   // 0, 1, 2, H or 4, 5, 6, L
2217   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2218       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2219     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2220     InsertAtByte = IsLE ? 0 : 12;
2221     Swap = M3 < 4;
2222     return true;
2223   }
2224 
2225   // If both vector operands for the shuffle are the same vector, the mask will
2226   // contain only elements from the first one and the second one will be undef.
2227   if (N->getOperand(1).isUndef()) {
2228     ShiftElts = 0;
2229     Swap = true;
2230     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2231     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2232       InsertAtByte = IsLE ? 12 : 0;
2233       return true;
2234     }
2235     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2236       InsertAtByte = IsLE ? 8 : 4;
2237       return true;
2238     }
2239     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2240       InsertAtByte = IsLE ? 4 : 8;
2241       return true;
2242     }
2243     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2244       InsertAtByte = IsLE ? 0 : 12;
2245       return true;
2246     }
2247   }
2248 
2249   return false;
2250 }
2251 
2252 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2253                                bool &Swap, bool IsLE) {
2254   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2255   // Ensure each byte index of the word is consecutive.
2256   if (!isNByteElemShuffleMask(N, 4, 1))
2257     return false;
2258 
2259   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2260   unsigned M0 = N->getMaskElt(0) / 4;
2261   unsigned M1 = N->getMaskElt(4) / 4;
2262   unsigned M2 = N->getMaskElt(8) / 4;
2263   unsigned M3 = N->getMaskElt(12) / 4;
2264 
2265   // If both vector operands for the shuffle are the same vector, the mask will
2266   // contain only elements from the first one and the second one will be undef.
2267   if (N->getOperand(1).isUndef()) {
2268     assert(M0 < 4 && "Indexing into an undef vector?");
2269     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2270       return false;
2271 
2272     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2273     Swap = false;
2274     return true;
2275   }
2276 
2277   // Ensure each word index of the ShuffleVector Mask is consecutive.
2278   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2279     return false;
2280 
2281   if (IsLE) {
2282     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2283       // Input vectors don't need to be swapped if the leading element
2284       // of the result is one of the 3 left elements of the second vector
2285       // (or if there is no shift to be done at all).
2286       Swap = false;
2287       ShiftElts = (8 - M0) % 8;
2288     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2289       // Input vectors need to be swapped if the leading element
2290       // of the result is one of the 3 left elements of the first vector
2291       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2292       Swap = true;
2293       ShiftElts = (4 - M0) % 4;
2294     }
2295 
2296     return true;
2297   } else {                                          // BE
2298     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2299       // Input vectors don't need to be swapped if the leading element
2300       // of the result is one of the 4 elements of the first vector.
2301       Swap = false;
2302       ShiftElts = M0;
2303     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2304       // Input vectors need to be swapped if the leading element
2305       // of the result is one of the 4 elements of the right vector.
2306       Swap = true;
2307       ShiftElts = M0 - 4;
2308     }
2309 
2310     return true;
2311   }
2312 }
2313 
2314 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2315   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2316 
2317   if (!isNByteElemShuffleMask(N, Width, -1))
2318     return false;
2319 
2320   for (int i = 0; i < 16; i += Width)
2321     if (N->getMaskElt(i) != i + Width - 1)
2322       return false;
2323 
2324   return true;
2325 }
2326 
2327 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2328   return isXXBRShuffleMaskHelper(N, 2);
2329 }
2330 
2331 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2332   return isXXBRShuffleMaskHelper(N, 4);
2333 }
2334 
2335 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2336   return isXXBRShuffleMaskHelper(N, 8);
2337 }
2338 
2339 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2340   return isXXBRShuffleMaskHelper(N, 16);
2341 }
2342 
2343 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2344 /// if the inputs to the instruction should be swapped and set \p DM to the
2345 /// value for the immediate.
2346 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2347 /// AND element 0 of the result comes from the first input (LE) or second input
2348 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2349 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2350 /// mask.
2351 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2352                                bool &Swap, bool IsLE) {
2353   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2354 
2355   // Ensure each byte index of the double word is consecutive.
2356   if (!isNByteElemShuffleMask(N, 8, 1))
2357     return false;
2358 
2359   unsigned M0 = N->getMaskElt(0) / 8;
2360   unsigned M1 = N->getMaskElt(8) / 8;
2361   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2362 
2363   // If both vector operands for the shuffle are the same vector, the mask will
2364   // contain only elements from the first one and the second one will be undef.
2365   if (N->getOperand(1).isUndef()) {
2366     if ((M0 | M1) < 2) {
2367       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2368       Swap = false;
2369       return true;
2370     } else
2371       return false;
2372   }
2373 
2374   if (IsLE) {
2375     if (M0 > 1 && M1 < 2) {
2376       Swap = false;
2377     } else if (M0 < 2 && M1 > 1) {
2378       M0 = (M0 + 2) % 4;
2379       M1 = (M1 + 2) % 4;
2380       Swap = true;
2381     } else
2382       return false;
2383 
2384     // Note: if control flow comes here that means Swap is already set above
2385     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2386     return true;
2387   } else { // BE
2388     if (M0 < 2 && M1 > 1) {
2389       Swap = false;
2390     } else if (M0 > 1 && M1 < 2) {
2391       M0 = (M0 + 2) % 4;
2392       M1 = (M1 + 2) % 4;
2393       Swap = true;
2394     } else
2395       return false;
2396 
2397     // Note: if control flow comes here that means Swap is already set above
2398     DM = (M0 << 1) + (M1 & 1);
2399     return true;
2400   }
2401 }
2402 
2403 
2404 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2405 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2406 /// elements are counted from the left of the vector register).
2407 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2408                                          SelectionDAG &DAG) {
2409   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2410   assert(isSplatShuffleMask(SVOp, EltSize));
2411   if (DAG.getDataLayout().isLittleEndian())
2412     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2413   else
2414     return SVOp->getMaskElt(0) / EltSize;
2415 }
2416 
2417 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2418 /// by using a vspltis[bhw] instruction of the specified element size, return
2419 /// the constant being splatted.  The ByteSize field indicates the number of
2420 /// bytes of each element [124] -> [bhw].
2421 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2422   SDValue OpVal(nullptr, 0);
2423 
2424   // If ByteSize of the splat is bigger than the element size of the
2425   // build_vector, then we have a case where we are checking for a splat where
2426   // multiple elements of the buildvector are folded together into a single
2427   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2428   unsigned EltSize = 16/N->getNumOperands();
2429   if (EltSize < ByteSize) {
2430     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2431     SDValue UniquedVals[4];
2432     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2433 
2434     // See if all of the elements in the buildvector agree across.
2435     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2436       if (N->getOperand(i).isUndef()) continue;
2437       // If the element isn't a constant, bail fully out.
2438       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2439 
2440       if (!UniquedVals[i&(Multiple-1)].getNode())
2441         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2442       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2443         return SDValue();  // no match.
2444     }
2445 
2446     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2447     // either constant or undef values that are identical for each chunk.  See
2448     // if these chunks can form into a larger vspltis*.
2449 
2450     // Check to see if all of the leading entries are either 0 or -1.  If
2451     // neither, then this won't fit into the immediate field.
2452     bool LeadingZero = true;
2453     bool LeadingOnes = true;
2454     for (unsigned i = 0; i != Multiple-1; ++i) {
2455       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2456 
2457       LeadingZero &= isNullConstant(UniquedVals[i]);
2458       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2459     }
2460     // Finally, check the least significant entry.
2461     if (LeadingZero) {
2462       if (!UniquedVals[Multiple-1].getNode())
2463         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2464       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2465       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2466         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2467     }
2468     if (LeadingOnes) {
2469       if (!UniquedVals[Multiple-1].getNode())
2470         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2471       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2472       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2473         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2474     }
2475 
2476     return SDValue();
2477   }
2478 
2479   // Check to see if this buildvec has a single non-undef value in its elements.
2480   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2481     if (N->getOperand(i).isUndef()) continue;
2482     if (!OpVal.getNode())
2483       OpVal = N->getOperand(i);
2484     else if (OpVal != N->getOperand(i))
2485       return SDValue();
2486   }
2487 
2488   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2489 
2490   unsigned ValSizeInBytes = EltSize;
2491   uint64_t Value = 0;
2492   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2493     Value = CN->getZExtValue();
2494   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2495     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2496     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2497   }
2498 
2499   // If the splat value is larger than the element value, then we can never do
2500   // this splat.  The only case that we could fit the replicated bits into our
2501   // immediate field for would be zero, and we prefer to use vxor for it.
2502   if (ValSizeInBytes < ByteSize) return SDValue();
2503 
2504   // If the element value is larger than the splat value, check if it consists
2505   // of a repeated bit pattern of size ByteSize.
2506   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2507     return SDValue();
2508 
2509   // Properly sign extend the value.
2510   int MaskVal = SignExtend32(Value, ByteSize * 8);
2511 
2512   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2513   if (MaskVal == 0) return SDValue();
2514 
2515   // Finally, if this value fits in a 5 bit sext field, return it
2516   if (SignExtend32<5>(MaskVal) == MaskVal)
2517     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2518   return SDValue();
2519 }
2520 
2521 //===----------------------------------------------------------------------===//
2522 //  Addressing Mode Selection
2523 //===----------------------------------------------------------------------===//
2524 
2525 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2526 /// or 64-bit immediate, and if the value can be accurately represented as a
2527 /// sign extension from a 16-bit value.  If so, this returns true and the
2528 /// immediate.
2529 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2530   if (!isa<ConstantSDNode>(N))
2531     return false;
2532 
2533   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2534   if (N->getValueType(0) == MVT::i32)
2535     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2536   else
2537     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2538 }
2539 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2540   return isIntS16Immediate(Op.getNode(), Imm);
2541 }
2542 
2543 /// Used when computing address flags for selecting loads and stores.
2544 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2545 /// An OR of two provably disjoint values is equivalent to an ADD.
2546 /// Most PPC load/store instructions compute the effective address as a sum,
2547 /// so doing this conversion is useful.
2548 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2549   if (N.getOpcode() != ISD::OR)
2550     return false;
2551   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2552   if (!LHSKnown.Zero.getBoolValue())
2553     return false;
2554   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2555   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2556 }
2557 
2558 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2559 /// be represented as an indexed [r+r] operation.
2560 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2561                                                SDValue &Index,
2562                                                SelectionDAG &DAG) const {
2563   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2564       UI != E; ++UI) {
2565     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2566       if (Memop->getMemoryVT() == MVT::f64) {
2567           Base = N.getOperand(0);
2568           Index = N.getOperand(1);
2569           return true;
2570       }
2571     }
2572   }
2573   return false;
2574 }
2575 
2576 /// isIntS34Immediate - This method tests if value of node given can be
2577 /// accurately represented as a sign extension from a 34-bit value.  If so,
2578 /// this returns true and the immediate.
2579 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2580   if (!isa<ConstantSDNode>(N))
2581     return false;
2582 
2583   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2584   return isInt<34>(Imm);
2585 }
2586 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2587   return isIntS34Immediate(Op.getNode(), Imm);
2588 }
2589 
2590 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2591 /// can be represented as an indexed [r+r] operation.  Returns false if it
2592 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2593 /// non-zero and N can be represented by a base register plus a signed 16-bit
2594 /// displacement, make a more precise judgement by checking (displacement % \p
2595 /// EncodingAlignment).
2596 bool PPCTargetLowering::SelectAddressRegReg(
2597     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2598     MaybeAlign EncodingAlignment) const {
2599   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2600   // a [pc+imm].
2601   if (SelectAddressPCRel(N, Base))
2602     return false;
2603 
2604   int16_t Imm = 0;
2605   if (N.getOpcode() == ISD::ADD) {
2606     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2607     // SPE load/store can only handle 8-bit offsets.
2608     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2609         return true;
2610     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2611         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2612       return false; // r+i
2613     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2614       return false;    // r+i
2615 
2616     Base = N.getOperand(0);
2617     Index = N.getOperand(1);
2618     return true;
2619   } else if (N.getOpcode() == ISD::OR) {
2620     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2621         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2622       return false; // r+i can fold it if we can.
2623 
2624     // If this is an or of disjoint bitfields, we can codegen this as an add
2625     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2626     // disjoint.
2627     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2628 
2629     if (LHSKnown.Zero.getBoolValue()) {
2630       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2631       // If all of the bits are known zero on the LHS or RHS, the add won't
2632       // carry.
2633       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2634         Base = N.getOperand(0);
2635         Index = N.getOperand(1);
2636         return true;
2637       }
2638     }
2639   }
2640 
2641   return false;
2642 }
2643 
2644 // If we happen to be doing an i64 load or store into a stack slot that has
2645 // less than a 4-byte alignment, then the frame-index elimination may need to
2646 // use an indexed load or store instruction (because the offset may not be a
2647 // multiple of 4). The extra register needed to hold the offset comes from the
2648 // register scavenger, and it is possible that the scavenger will need to use
2649 // an emergency spill slot. As a result, we need to make sure that a spill slot
2650 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2651 // stack slot.
2652 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2653   // FIXME: This does not handle the LWA case.
2654   if (VT != MVT::i64)
2655     return;
2656 
2657   // NOTE: We'll exclude negative FIs here, which come from argument
2658   // lowering, because there are no known test cases triggering this problem
2659   // using packed structures (or similar). We can remove this exclusion if
2660   // we find such a test case. The reason why this is so test-case driven is
2661   // because this entire 'fixup' is only to prevent crashes (from the
2662   // register scavenger) on not-really-valid inputs. For example, if we have:
2663   //   %a = alloca i1
2664   //   %b = bitcast i1* %a to i64*
2665   //   store i64* a, i64 b
2666   // then the store should really be marked as 'align 1', but is not. If it
2667   // were marked as 'align 1' then the indexed form would have been
2668   // instruction-selected initially, and the problem this 'fixup' is preventing
2669   // won't happen regardless.
2670   if (FrameIdx < 0)
2671     return;
2672 
2673   MachineFunction &MF = DAG.getMachineFunction();
2674   MachineFrameInfo &MFI = MF.getFrameInfo();
2675 
2676   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2677     return;
2678 
2679   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2680   FuncInfo->setHasNonRISpills();
2681 }
2682 
2683 /// Returns true if the address N can be represented by a base register plus
2684 /// a signed 16-bit displacement [r+imm], and if it is not better
2685 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2686 /// displacements that are multiples of that value.
2687 bool PPCTargetLowering::SelectAddressRegImm(
2688     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2689     MaybeAlign EncodingAlignment) const {
2690   // FIXME dl should come from parent load or store, not from address
2691   SDLoc dl(N);
2692 
2693   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2694   // a [pc+imm].
2695   if (SelectAddressPCRel(N, Base))
2696     return false;
2697 
2698   // If this can be more profitably realized as r+r, fail.
2699   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2700     return false;
2701 
2702   if (N.getOpcode() == ISD::ADD) {
2703     int16_t imm = 0;
2704     if (isIntS16Immediate(N.getOperand(1), imm) &&
2705         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2706       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2707       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2708         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2709         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2710       } else {
2711         Base = N.getOperand(0);
2712       }
2713       return true; // [r+i]
2714     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2715       // Match LOAD (ADD (X, Lo(G))).
2716       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2717              && "Cannot handle constant offsets yet!");
2718       Disp = N.getOperand(1).getOperand(0);  // The global address.
2719       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2720              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2721              Disp.getOpcode() == ISD::TargetConstantPool ||
2722              Disp.getOpcode() == ISD::TargetJumpTable);
2723       Base = N.getOperand(0);
2724       return true;  // [&g+r]
2725     }
2726   } else if (N.getOpcode() == ISD::OR) {
2727     int16_t imm = 0;
2728     if (isIntS16Immediate(N.getOperand(1), imm) &&
2729         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2730       // If this is an or of disjoint bitfields, we can codegen this as an add
2731       // (for better address arithmetic) if the LHS and RHS of the OR are
2732       // provably disjoint.
2733       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2734 
2735       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2736         // If all of the bits are known zero on the LHS or RHS, the add won't
2737         // carry.
2738         if (FrameIndexSDNode *FI =
2739               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2740           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2741           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2742         } else {
2743           Base = N.getOperand(0);
2744         }
2745         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2746         return true;
2747       }
2748     }
2749   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2750     // Loading from a constant address.
2751 
2752     // If this address fits entirely in a 16-bit sext immediate field, codegen
2753     // this as "d, 0"
2754     int16_t Imm;
2755     if (isIntS16Immediate(CN, Imm) &&
2756         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2757       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2758       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2759                              CN->getValueType(0));
2760       return true;
2761     }
2762 
2763     // Handle 32-bit sext immediates with LIS + addr mode.
2764     if ((CN->getValueType(0) == MVT::i32 ||
2765          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2766         (!EncodingAlignment ||
2767          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2768       int Addr = (int)CN->getZExtValue();
2769 
2770       // Otherwise, break this down into an LIS + disp.
2771       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2772 
2773       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2774                                    MVT::i32);
2775       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2776       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2777       return true;
2778     }
2779   }
2780 
2781   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2782   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2783     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2784     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2785   } else
2786     Base = N;
2787   return true;      // [r+0]
2788 }
2789 
2790 /// Similar to the 16-bit case but for instructions that take a 34-bit
2791 /// displacement field (prefixed loads/stores).
2792 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2793                                               SDValue &Base,
2794                                               SelectionDAG &DAG) const {
2795   // Only on 64-bit targets.
2796   if (N.getValueType() != MVT::i64)
2797     return false;
2798 
2799   SDLoc dl(N);
2800   int64_t Imm = 0;
2801 
2802   if (N.getOpcode() == ISD::ADD) {
2803     if (!isIntS34Immediate(N.getOperand(1), Imm))
2804       return false;
2805     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2806     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2807       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2808     else
2809       Base = N.getOperand(0);
2810     return true;
2811   }
2812 
2813   if (N.getOpcode() == ISD::OR) {
2814     if (!isIntS34Immediate(N.getOperand(1), Imm))
2815       return false;
2816     // If this is an or of disjoint bitfields, we can codegen this as an add
2817     // (for better address arithmetic) if the LHS and RHS of the OR are
2818     // provably disjoint.
2819     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2820     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2821       return false;
2822     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2823       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2824     else
2825       Base = N.getOperand(0);
2826     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2827     return true;
2828   }
2829 
2830   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2831     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2832     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2833     return true;
2834   }
2835 
2836   return false;
2837 }
2838 
2839 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2840 /// represented as an indexed [r+r] operation.
2841 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2842                                                 SDValue &Index,
2843                                                 SelectionDAG &DAG) const {
2844   // Check to see if we can easily represent this as an [r+r] address.  This
2845   // will fail if it thinks that the address is more profitably represented as
2846   // reg+imm, e.g. where imm = 0.
2847   if (SelectAddressRegReg(N, Base, Index, DAG))
2848     return true;
2849 
2850   // If the address is the result of an add, we will utilize the fact that the
2851   // address calculation includes an implicit add.  However, we can reduce
2852   // register pressure if we do not materialize a constant just for use as the
2853   // index register.  We only get rid of the add if it is not an add of a
2854   // value and a 16-bit signed constant and both have a single use.
2855   int16_t imm = 0;
2856   if (N.getOpcode() == ISD::ADD &&
2857       (!isIntS16Immediate(N.getOperand(1), imm) ||
2858        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2859     Base = N.getOperand(0);
2860     Index = N.getOperand(1);
2861     return true;
2862   }
2863 
2864   // Otherwise, do it the hard way, using R0 as the base register.
2865   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2866                          N.getValueType());
2867   Index = N;
2868   return true;
2869 }
2870 
2871 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2872   Ty *PCRelCand = dyn_cast<Ty>(N);
2873   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2874 }
2875 
2876 /// Returns true if this address is a PC Relative address.
2877 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2878 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2879 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2880   // This is a materialize PC Relative node. Always select this as PC Relative.
2881   Base = N;
2882   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2883     return true;
2884   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2885       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2886       isValidPCRelNode<JumpTableSDNode>(N) ||
2887       isValidPCRelNode<BlockAddressSDNode>(N))
2888     return true;
2889   return false;
2890 }
2891 
2892 /// Returns true if we should use a direct load into vector instruction
2893 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2894 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2895 
2896   // If there are any other uses other than scalar to vector, then we should
2897   // keep it as a scalar load -> direct move pattern to prevent multiple
2898   // loads.
2899   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2900   if (!LD)
2901     return false;
2902 
2903   EVT MemVT = LD->getMemoryVT();
2904   if (!MemVT.isSimple())
2905     return false;
2906   switch(MemVT.getSimpleVT().SimpleTy) {
2907   case MVT::i64:
2908     break;
2909   case MVT::i32:
2910     if (!ST.hasP8Vector())
2911       return false;
2912     break;
2913   case MVT::i16:
2914   case MVT::i8:
2915     if (!ST.hasP9Vector())
2916       return false;
2917     break;
2918   default:
2919     return false;
2920   }
2921 
2922   SDValue LoadedVal(N, 0);
2923   if (!LoadedVal.hasOneUse())
2924     return false;
2925 
2926   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2927        UI != UE; ++UI)
2928     if (UI.getUse().get().getResNo() == 0 &&
2929         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2930         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2931       return false;
2932 
2933   return true;
2934 }
2935 
2936 /// getPreIndexedAddressParts - returns true by value, base pointer and
2937 /// offset pointer and addressing mode by reference if the node's address
2938 /// can be legally represented as pre-indexed load / store address.
2939 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2940                                                   SDValue &Offset,
2941                                                   ISD::MemIndexedMode &AM,
2942                                                   SelectionDAG &DAG) const {
2943   if (DisablePPCPreinc) return false;
2944 
2945   bool isLoad = true;
2946   SDValue Ptr;
2947   EVT VT;
2948   unsigned Alignment;
2949   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2950     Ptr = LD->getBasePtr();
2951     VT = LD->getMemoryVT();
2952     Alignment = LD->getAlignment();
2953   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2954     Ptr = ST->getBasePtr();
2955     VT  = ST->getMemoryVT();
2956     Alignment = ST->getAlignment();
2957     isLoad = false;
2958   } else
2959     return false;
2960 
2961   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2962   // instructions because we can fold these into a more efficient instruction
2963   // instead, (such as LXSD).
2964   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2965     return false;
2966   }
2967 
2968   // PowerPC doesn't have preinc load/store instructions for vectors
2969   if (VT.isVector())
2970     return false;
2971 
2972   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2973     // Common code will reject creating a pre-inc form if the base pointer
2974     // is a frame index, or if N is a store and the base pointer is either
2975     // the same as or a predecessor of the value being stored.  Check for
2976     // those situations here, and try with swapped Base/Offset instead.
2977     bool Swap = false;
2978 
2979     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2980       Swap = true;
2981     else if (!isLoad) {
2982       SDValue Val = cast<StoreSDNode>(N)->getValue();
2983       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2984         Swap = true;
2985     }
2986 
2987     if (Swap)
2988       std::swap(Base, Offset);
2989 
2990     AM = ISD::PRE_INC;
2991     return true;
2992   }
2993 
2994   // LDU/STU can only handle immediates that are a multiple of 4.
2995   if (VT != MVT::i64) {
2996     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2997       return false;
2998   } else {
2999     // LDU/STU need an address with at least 4-byte alignment.
3000     if (Alignment < 4)
3001       return false;
3002 
3003     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3004       return false;
3005   }
3006 
3007   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3008     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3009     // sext i32 to i64 when addr mode is r+i.
3010     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3011         LD->getExtensionType() == ISD::SEXTLOAD &&
3012         isa<ConstantSDNode>(Offset))
3013       return false;
3014   }
3015 
3016   AM = ISD::PRE_INC;
3017   return true;
3018 }
3019 
3020 //===----------------------------------------------------------------------===//
3021 //  LowerOperation implementation
3022 //===----------------------------------------------------------------------===//
3023 
3024 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3025 /// and LoOpFlags to the target MO flags.
3026 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3027                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3028                                const GlobalValue *GV = nullptr) {
3029   HiOpFlags = PPCII::MO_HA;
3030   LoOpFlags = PPCII::MO_LO;
3031 
3032   // Don't use the pic base if not in PIC relocation model.
3033   if (IsPIC) {
3034     HiOpFlags |= PPCII::MO_PIC_FLAG;
3035     LoOpFlags |= PPCII::MO_PIC_FLAG;
3036   }
3037 }
3038 
3039 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3040                              SelectionDAG &DAG) {
3041   SDLoc DL(HiPart);
3042   EVT PtrVT = HiPart.getValueType();
3043   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3044 
3045   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3046   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3047 
3048   // With PIC, the first instruction is actually "GR+hi(&G)".
3049   if (isPIC)
3050     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3051                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3052 
3053   // Generate non-pic code that has direct accesses to the constant pool.
3054   // The address of the global is just (hi(&g)+lo(&g)).
3055   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3056 }
3057 
3058 static void setUsesTOCBasePtr(MachineFunction &MF) {
3059   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3060   FuncInfo->setUsesTOCBasePtr();
3061 }
3062 
3063 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3064   setUsesTOCBasePtr(DAG.getMachineFunction());
3065 }
3066 
3067 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3068                                        SDValue GA) const {
3069   const bool Is64Bit = Subtarget.isPPC64();
3070   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3071   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3072                         : Subtarget.isAIXABI()
3073                               ? DAG.getRegister(PPC::R2, VT)
3074                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3075   SDValue Ops[] = { GA, Reg };
3076   return DAG.getMemIntrinsicNode(
3077       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3078       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3079       MachineMemOperand::MOLoad);
3080 }
3081 
3082 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3083                                              SelectionDAG &DAG) const {
3084   EVT PtrVT = Op.getValueType();
3085   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3086   const Constant *C = CP->getConstVal();
3087 
3088   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3089   // The actual address of the GlobalValue is stored in the TOC.
3090   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3091     if (Subtarget.isUsingPCRelativeCalls()) {
3092       SDLoc DL(CP);
3093       EVT Ty = getPointerTy(DAG.getDataLayout());
3094       SDValue ConstPool = DAG.getTargetConstantPool(
3095           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3096       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3097     }
3098     setUsesTOCBasePtr(DAG);
3099     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3100     return getTOCEntry(DAG, SDLoc(CP), GA);
3101   }
3102 
3103   unsigned MOHiFlag, MOLoFlag;
3104   bool IsPIC = isPositionIndependent();
3105   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3106 
3107   if (IsPIC && Subtarget.isSVR4ABI()) {
3108     SDValue GA =
3109         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3110     return getTOCEntry(DAG, SDLoc(CP), GA);
3111   }
3112 
3113   SDValue CPIHi =
3114       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3115   SDValue CPILo =
3116       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3117   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3118 }
3119 
3120 // For 64-bit PowerPC, prefer the more compact relative encodings.
3121 // This trades 32 bits per jump table entry for one or two instructions
3122 // on the jump site.
3123 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3124   if (isJumpTableRelative())
3125     return MachineJumpTableInfo::EK_LabelDifference32;
3126 
3127   return TargetLowering::getJumpTableEncoding();
3128 }
3129 
3130 bool PPCTargetLowering::isJumpTableRelative() const {
3131   if (UseAbsoluteJumpTables)
3132     return false;
3133   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3134     return true;
3135   return TargetLowering::isJumpTableRelative();
3136 }
3137 
3138 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3139                                                     SelectionDAG &DAG) const {
3140   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3141     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3142 
3143   switch (getTargetMachine().getCodeModel()) {
3144   case CodeModel::Small:
3145   case CodeModel::Medium:
3146     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3147   default:
3148     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3149                        getPointerTy(DAG.getDataLayout()));
3150   }
3151 }
3152 
3153 const MCExpr *
3154 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3155                                                 unsigned JTI,
3156                                                 MCContext &Ctx) const {
3157   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3158     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3159 
3160   switch (getTargetMachine().getCodeModel()) {
3161   case CodeModel::Small:
3162   case CodeModel::Medium:
3163     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3164   default:
3165     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3166   }
3167 }
3168 
3169 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3170   EVT PtrVT = Op.getValueType();
3171   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3172 
3173   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3174   if (Subtarget.isUsingPCRelativeCalls()) {
3175     SDLoc DL(JT);
3176     EVT Ty = getPointerTy(DAG.getDataLayout());
3177     SDValue GA =
3178         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3179     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3180     return MatAddr;
3181   }
3182 
3183   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3184   // The actual address of the GlobalValue is stored in the TOC.
3185   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3186     setUsesTOCBasePtr(DAG);
3187     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3188     return getTOCEntry(DAG, SDLoc(JT), GA);
3189   }
3190 
3191   unsigned MOHiFlag, MOLoFlag;
3192   bool IsPIC = isPositionIndependent();
3193   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3194 
3195   if (IsPIC && Subtarget.isSVR4ABI()) {
3196     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3197                                         PPCII::MO_PIC_FLAG);
3198     return getTOCEntry(DAG, SDLoc(GA), GA);
3199   }
3200 
3201   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3202   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3203   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3204 }
3205 
3206 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3207                                              SelectionDAG &DAG) const {
3208   EVT PtrVT = Op.getValueType();
3209   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3210   const BlockAddress *BA = BASDN->getBlockAddress();
3211 
3212   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3213   if (Subtarget.isUsingPCRelativeCalls()) {
3214     SDLoc DL(BASDN);
3215     EVT Ty = getPointerTy(DAG.getDataLayout());
3216     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3217                                            PPCII::MO_PCREL_FLAG);
3218     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3219     return MatAddr;
3220   }
3221 
3222   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3223   // The actual BlockAddress is stored in the TOC.
3224   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3225     setUsesTOCBasePtr(DAG);
3226     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3227     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3228   }
3229 
3230   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3231   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3232     return getTOCEntry(
3233         DAG, SDLoc(BASDN),
3234         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3235 
3236   unsigned MOHiFlag, MOLoFlag;
3237   bool IsPIC = isPositionIndependent();
3238   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3239   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3240   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3241   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3242 }
3243 
3244 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3245                                               SelectionDAG &DAG) const {
3246   if (Subtarget.isAIXABI())
3247     return LowerGlobalTLSAddressAIX(Op, DAG);
3248 
3249   return LowerGlobalTLSAddressLinux(Op, DAG);
3250 }
3251 
3252 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3253                                                     SelectionDAG &DAG) const {
3254   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3255 
3256   if (DAG.getTarget().useEmulatedTLS())
3257     report_fatal_error("Emulated TLS is not yet supported on AIX");
3258 
3259   SDLoc dl(GA);
3260   const GlobalValue *GV = GA->getGlobal();
3261   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3262 
3263   // The general-dynamic model is the only access model supported for now, so
3264   // all the GlobalTLSAddress nodes are lowered with this model.
3265   // We need to generate two TOC entries, one for the variable offset, one for
3266   // the region handle. The global address for the TOC entry of the region
3267   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3268   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3269   SDValue VariableOffsetTGA =
3270       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3271   SDValue RegionHandleTGA =
3272       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3273   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3274   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3275   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3276                      RegionHandle);
3277 }
3278 
3279 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3280                                                       SelectionDAG &DAG) const {
3281   // FIXME: TLS addresses currently use medium model code sequences,
3282   // which is the most useful form.  Eventually support for small and
3283   // large models could be added if users need it, at the cost of
3284   // additional complexity.
3285   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3286   if (DAG.getTarget().useEmulatedTLS())
3287     return LowerToTLSEmulatedModel(GA, DAG);
3288 
3289   SDLoc dl(GA);
3290   const GlobalValue *GV = GA->getGlobal();
3291   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3292   bool is64bit = Subtarget.isPPC64();
3293   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3294   PICLevel::Level picLevel = M->getPICLevel();
3295 
3296   const TargetMachine &TM = getTargetMachine();
3297   TLSModel::Model Model = TM.getTLSModel(GV);
3298 
3299   if (Model == TLSModel::LocalExec) {
3300     if (Subtarget.isUsingPCRelativeCalls()) {
3301       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3302       SDValue TGA = DAG.getTargetGlobalAddress(
3303           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3304       SDValue MatAddr =
3305           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3306       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3307     }
3308 
3309     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3310                                                PPCII::MO_TPREL_HA);
3311     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3312                                                PPCII::MO_TPREL_LO);
3313     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3314                              : DAG.getRegister(PPC::R2, MVT::i32);
3315 
3316     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3317     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3318   }
3319 
3320   if (Model == TLSModel::InitialExec) {
3321     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3322     SDValue TGA = DAG.getTargetGlobalAddress(
3323         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3324     SDValue TGATLS = DAG.getTargetGlobalAddress(
3325         GV, dl, PtrVT, 0,
3326         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3327     SDValue TPOffset;
3328     if (IsPCRel) {
3329       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3330       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3331                              MachinePointerInfo());
3332     } else {
3333       SDValue GOTPtr;
3334       if (is64bit) {
3335         setUsesTOCBasePtr(DAG);
3336         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3337         GOTPtr =
3338             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3339       } else {
3340         if (!TM.isPositionIndependent())
3341           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3342         else if (picLevel == PICLevel::SmallPIC)
3343           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3344         else
3345           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3346       }
3347       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3348     }
3349     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3350   }
3351 
3352   if (Model == TLSModel::GeneralDynamic) {
3353     if (Subtarget.isUsingPCRelativeCalls()) {
3354       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3355                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3356       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3357     }
3358 
3359     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3360     SDValue GOTPtr;
3361     if (is64bit) {
3362       setUsesTOCBasePtr(DAG);
3363       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3364       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3365                                    GOTReg, TGA);
3366     } else {
3367       if (picLevel == PICLevel::SmallPIC)
3368         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3369       else
3370         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3371     }
3372     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3373                        GOTPtr, TGA, TGA);
3374   }
3375 
3376   if (Model == TLSModel::LocalDynamic) {
3377     if (Subtarget.isUsingPCRelativeCalls()) {
3378       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3379                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3380       SDValue MatPCRel =
3381           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3382       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3383     }
3384 
3385     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3386     SDValue GOTPtr;
3387     if (is64bit) {
3388       setUsesTOCBasePtr(DAG);
3389       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3390       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3391                            GOTReg, TGA);
3392     } else {
3393       if (picLevel == PICLevel::SmallPIC)
3394         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3395       else
3396         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3397     }
3398     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3399                                   PtrVT, GOTPtr, TGA, TGA);
3400     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3401                                       PtrVT, TLSAddr, TGA);
3402     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3403   }
3404 
3405   llvm_unreachable("Unknown TLS model!");
3406 }
3407 
3408 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3409                                               SelectionDAG &DAG) const {
3410   EVT PtrVT = Op.getValueType();
3411   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3412   SDLoc DL(GSDN);
3413   const GlobalValue *GV = GSDN->getGlobal();
3414 
3415   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3416   // The actual address of the GlobalValue is stored in the TOC.
3417   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3418     if (Subtarget.isUsingPCRelativeCalls()) {
3419       EVT Ty = getPointerTy(DAG.getDataLayout());
3420       if (isAccessedAsGotIndirect(Op)) {
3421         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3422                                                 PPCII::MO_PCREL_FLAG |
3423                                                     PPCII::MO_GOT_FLAG);
3424         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3425         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3426                                    MachinePointerInfo());
3427         return Load;
3428       } else {
3429         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3430                                                 PPCII::MO_PCREL_FLAG);
3431         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3432       }
3433     }
3434     setUsesTOCBasePtr(DAG);
3435     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3436     return getTOCEntry(DAG, DL, GA);
3437   }
3438 
3439   unsigned MOHiFlag, MOLoFlag;
3440   bool IsPIC = isPositionIndependent();
3441   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3442 
3443   if (IsPIC && Subtarget.isSVR4ABI()) {
3444     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3445                                             GSDN->getOffset(),
3446                                             PPCII::MO_PIC_FLAG);
3447     return getTOCEntry(DAG, DL, GA);
3448   }
3449 
3450   SDValue GAHi =
3451     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3452   SDValue GALo =
3453     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3454 
3455   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3456 }
3457 
3458 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3459   bool IsStrict = Op->isStrictFPOpcode();
3460   ISD::CondCode CC =
3461       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3462   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3463   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3464   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3465   EVT LHSVT = LHS.getValueType();
3466   SDLoc dl(Op);
3467 
3468   // Soften the setcc with libcall if it is fp128.
3469   if (LHSVT == MVT::f128) {
3470     assert(!Subtarget.hasP9Vector() &&
3471            "SETCC for f128 is already legal under Power9!");
3472     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3473                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3474     if (RHS.getNode())
3475       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3476                         DAG.getCondCode(CC));
3477     if (IsStrict)
3478       return DAG.getMergeValues({LHS, Chain}, dl);
3479     return LHS;
3480   }
3481 
3482   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3483 
3484   if (Op.getValueType() == MVT::v2i64) {
3485     // When the operands themselves are v2i64 values, we need to do something
3486     // special because VSX has no underlying comparison operations for these.
3487     if (LHS.getValueType() == MVT::v2i64) {
3488       // Equality can be handled by casting to the legal type for Altivec
3489       // comparisons, everything else needs to be expanded.
3490       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3491         return DAG.getNode(
3492             ISD::BITCAST, dl, MVT::v2i64,
3493             DAG.getSetCC(dl, MVT::v4i32,
3494                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3495                          DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC));
3496       }
3497 
3498       return SDValue();
3499     }
3500 
3501     // We handle most of these in the usual way.
3502     return Op;
3503   }
3504 
3505   // If we're comparing for equality to zero, expose the fact that this is
3506   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3507   // fold the new nodes.
3508   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3509     return V;
3510 
3511   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3512     // Leave comparisons against 0 and -1 alone for now, since they're usually
3513     // optimized.  FIXME: revisit this when we can custom lower all setcc
3514     // optimizations.
3515     if (C->isAllOnes() || C->isZero())
3516       return SDValue();
3517   }
3518 
3519   // If we have an integer seteq/setne, turn it into a compare against zero
3520   // by xor'ing the rhs with the lhs, which is faster than setting a
3521   // condition register, reading it back out, and masking the correct bit.  The
3522   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3523   // the result to other bit-twiddling opportunities.
3524   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3525     EVT VT = Op.getValueType();
3526     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3527     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3528   }
3529   return SDValue();
3530 }
3531 
3532 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3533   SDNode *Node = Op.getNode();
3534   EVT VT = Node->getValueType(0);
3535   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3536   SDValue InChain = Node->getOperand(0);
3537   SDValue VAListPtr = Node->getOperand(1);
3538   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3539   SDLoc dl(Node);
3540 
3541   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3542 
3543   // gpr_index
3544   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3545                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3546   InChain = GprIndex.getValue(1);
3547 
3548   if (VT == MVT::i64) {
3549     // Check if GprIndex is even
3550     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3551                                  DAG.getConstant(1, dl, MVT::i32));
3552     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3553                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3554     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3555                                           DAG.getConstant(1, dl, MVT::i32));
3556     // Align GprIndex to be even if it isn't
3557     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3558                            GprIndex);
3559   }
3560 
3561   // fpr index is 1 byte after gpr
3562   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3563                                DAG.getConstant(1, dl, MVT::i32));
3564 
3565   // fpr
3566   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3567                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3568   InChain = FprIndex.getValue(1);
3569 
3570   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3571                                        DAG.getConstant(8, dl, MVT::i32));
3572 
3573   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3574                                         DAG.getConstant(4, dl, MVT::i32));
3575 
3576   // areas
3577   SDValue OverflowArea =
3578       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3579   InChain = OverflowArea.getValue(1);
3580 
3581   SDValue RegSaveArea =
3582       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3583   InChain = RegSaveArea.getValue(1);
3584 
3585   // select overflow_area if index > 8
3586   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3587                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3588 
3589   // adjustment constant gpr_index * 4/8
3590   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3591                                     VT.isInteger() ? GprIndex : FprIndex,
3592                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3593                                                     MVT::i32));
3594 
3595   // OurReg = RegSaveArea + RegConstant
3596   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3597                                RegConstant);
3598 
3599   // Floating types are 32 bytes into RegSaveArea
3600   if (VT.isFloatingPoint())
3601     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3602                          DAG.getConstant(32, dl, MVT::i32));
3603 
3604   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3605   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3606                                    VT.isInteger() ? GprIndex : FprIndex,
3607                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3608                                                    MVT::i32));
3609 
3610   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3611                               VT.isInteger() ? VAListPtr : FprPtr,
3612                               MachinePointerInfo(SV), MVT::i8);
3613 
3614   // determine if we should load from reg_save_area or overflow_area
3615   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3616 
3617   // increase overflow_area by 4/8 if gpr/fpr > 8
3618   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3619                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3620                                           dl, MVT::i32));
3621 
3622   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3623                              OverflowAreaPlusN);
3624 
3625   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3626                               MachinePointerInfo(), MVT::i32);
3627 
3628   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3629 }
3630 
3631 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3632   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3633 
3634   // We have to copy the entire va_list struct:
3635   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3636   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3637                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3638                        false, true, false, MachinePointerInfo(),
3639                        MachinePointerInfo());
3640 }
3641 
3642 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3643                                                   SelectionDAG &DAG) const {
3644   if (Subtarget.isAIXABI())
3645     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3646 
3647   return Op.getOperand(0);
3648 }
3649 
3650 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3651   MachineFunction &MF = DAG.getMachineFunction();
3652   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3653 
3654   assert((Op.getOpcode() == ISD::INLINEASM ||
3655           Op.getOpcode() == ISD::INLINEASM_BR) &&
3656          "Expecting Inline ASM node.");
3657 
3658   // If an LR store is already known to be required then there is not point in
3659   // checking this ASM as well.
3660   if (MFI.isLRStoreRequired())
3661     return Op;
3662 
3663   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3664   // type MVT::Glue. We want to ignore this last operand if that is the case.
3665   unsigned NumOps = Op.getNumOperands();
3666   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3667     --NumOps;
3668 
3669   // Check all operands that may contain the LR.
3670   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3671     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3672     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3673     ++i; // Skip the ID value.
3674 
3675     switch (InlineAsm::getKind(Flags)) {
3676     default:
3677       llvm_unreachable("Bad flags!");
3678     case InlineAsm::Kind_RegUse:
3679     case InlineAsm::Kind_Imm:
3680     case InlineAsm::Kind_Mem:
3681       i += NumVals;
3682       break;
3683     case InlineAsm::Kind_Clobber:
3684     case InlineAsm::Kind_RegDef:
3685     case InlineAsm::Kind_RegDefEarlyClobber: {
3686       for (; NumVals; --NumVals, ++i) {
3687         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3688         if (Reg != PPC::LR && Reg != PPC::LR8)
3689           continue;
3690         MFI.setLRStoreRequired();
3691         return Op;
3692       }
3693       break;
3694     }
3695     }
3696   }
3697 
3698   return Op;
3699 }
3700 
3701 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3702                                                 SelectionDAG &DAG) const {
3703   if (Subtarget.isAIXABI())
3704     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3705 
3706   SDValue Chain = Op.getOperand(0);
3707   SDValue Trmp = Op.getOperand(1); // trampoline
3708   SDValue FPtr = Op.getOperand(2); // nested function
3709   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3710   SDLoc dl(Op);
3711 
3712   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3713   bool isPPC64 = (PtrVT == MVT::i64);
3714   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3715 
3716   TargetLowering::ArgListTy Args;
3717   TargetLowering::ArgListEntry Entry;
3718 
3719   Entry.Ty = IntPtrTy;
3720   Entry.Node = Trmp; Args.push_back(Entry);
3721 
3722   // TrampSize == (isPPC64 ? 48 : 40);
3723   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3724                                isPPC64 ? MVT::i64 : MVT::i32);
3725   Args.push_back(Entry);
3726 
3727   Entry.Node = FPtr; Args.push_back(Entry);
3728   Entry.Node = Nest; Args.push_back(Entry);
3729 
3730   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3731   TargetLowering::CallLoweringInfo CLI(DAG);
3732   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3733       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3734       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3735 
3736   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3737   return CallResult.second;
3738 }
3739 
3740 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3741   MachineFunction &MF = DAG.getMachineFunction();
3742   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3743   EVT PtrVT = getPointerTy(MF.getDataLayout());
3744 
3745   SDLoc dl(Op);
3746 
3747   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3748     // vastart just stores the address of the VarArgsFrameIndex slot into the
3749     // memory location argument.
3750     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3751     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3752     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3753                         MachinePointerInfo(SV));
3754   }
3755 
3756   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3757   // We suppose the given va_list is already allocated.
3758   //
3759   // typedef struct {
3760   //  char gpr;     /* index into the array of 8 GPRs
3761   //                 * stored in the register save area
3762   //                 * gpr=0 corresponds to r3,
3763   //                 * gpr=1 to r4, etc.
3764   //                 */
3765   //  char fpr;     /* index into the array of 8 FPRs
3766   //                 * stored in the register save area
3767   //                 * fpr=0 corresponds to f1,
3768   //                 * fpr=1 to f2, etc.
3769   //                 */
3770   //  char *overflow_arg_area;
3771   //                /* location on stack that holds
3772   //                 * the next overflow argument
3773   //                 */
3774   //  char *reg_save_area;
3775   //               /* where r3:r10 and f1:f8 (if saved)
3776   //                * are stored
3777   //                */
3778   // } va_list[1];
3779 
3780   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3781   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3782   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3783                                             PtrVT);
3784   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3785                                  PtrVT);
3786 
3787   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3788   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3789 
3790   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3791   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3792 
3793   uint64_t FPROffset = 1;
3794   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3795 
3796   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3797 
3798   // Store first byte : number of int regs
3799   SDValue firstStore =
3800       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3801                         MachinePointerInfo(SV), MVT::i8);
3802   uint64_t nextOffset = FPROffset;
3803   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3804                                   ConstFPROffset);
3805 
3806   // Store second byte : number of float regs
3807   SDValue secondStore =
3808       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3809                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3810   nextOffset += StackOffset;
3811   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3812 
3813   // Store second word : arguments given on stack
3814   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3815                                     MachinePointerInfo(SV, nextOffset));
3816   nextOffset += FrameOffset;
3817   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3818 
3819   // Store third word : arguments given in registers
3820   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3821                       MachinePointerInfo(SV, nextOffset));
3822 }
3823 
3824 /// FPR - The set of FP registers that should be allocated for arguments
3825 /// on Darwin and AIX.
3826 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3827                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3828                                 PPC::F11, PPC::F12, PPC::F13};
3829 
3830 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3831 /// the stack.
3832 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3833                                        unsigned PtrByteSize) {
3834   unsigned ArgSize = ArgVT.getStoreSize();
3835   if (Flags.isByVal())
3836     ArgSize = Flags.getByValSize();
3837 
3838   // Round up to multiples of the pointer size, except for array members,
3839   // which are always packed.
3840   if (!Flags.isInConsecutiveRegs())
3841     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3842 
3843   return ArgSize;
3844 }
3845 
3846 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3847 /// on the stack.
3848 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3849                                          ISD::ArgFlagsTy Flags,
3850                                          unsigned PtrByteSize) {
3851   Align Alignment(PtrByteSize);
3852 
3853   // Altivec parameters are padded to a 16 byte boundary.
3854   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3855       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3856       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3857       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3858     Alignment = Align(16);
3859 
3860   // ByVal parameters are aligned as requested.
3861   if (Flags.isByVal()) {
3862     auto BVAlign = Flags.getNonZeroByValAlign();
3863     if (BVAlign > PtrByteSize) {
3864       if (BVAlign.value() % PtrByteSize != 0)
3865         llvm_unreachable(
3866             "ByVal alignment is not a multiple of the pointer size");
3867 
3868       Alignment = BVAlign;
3869     }
3870   }
3871 
3872   // Array members are always packed to their original alignment.
3873   if (Flags.isInConsecutiveRegs()) {
3874     // If the array member was split into multiple registers, the first
3875     // needs to be aligned to the size of the full type.  (Except for
3876     // ppcf128, which is only aligned as its f64 components.)
3877     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3878       Alignment = Align(OrigVT.getStoreSize());
3879     else
3880       Alignment = Align(ArgVT.getStoreSize());
3881   }
3882 
3883   return Alignment;
3884 }
3885 
3886 /// CalculateStackSlotUsed - Return whether this argument will use its
3887 /// stack slot (instead of being passed in registers).  ArgOffset,
3888 /// AvailableFPRs, and AvailableVRs must hold the current argument
3889 /// position, and will be updated to account for this argument.
3890 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3891                                    unsigned PtrByteSize, unsigned LinkageSize,
3892                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3893                                    unsigned &AvailableFPRs,
3894                                    unsigned &AvailableVRs) {
3895   bool UseMemory = false;
3896 
3897   // Respect alignment of argument on the stack.
3898   Align Alignment =
3899       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3900   ArgOffset = alignTo(ArgOffset, Alignment);
3901   // If there's no space left in the argument save area, we must
3902   // use memory (this check also catches zero-sized arguments).
3903   if (ArgOffset >= LinkageSize + ParamAreaSize)
3904     UseMemory = true;
3905 
3906   // Allocate argument on the stack.
3907   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3908   if (Flags.isInConsecutiveRegsLast())
3909     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3910   // If we overran the argument save area, we must use memory
3911   // (this check catches arguments passed partially in memory)
3912   if (ArgOffset > LinkageSize + ParamAreaSize)
3913     UseMemory = true;
3914 
3915   // However, if the argument is actually passed in an FPR or a VR,
3916   // we don't use memory after all.
3917   if (!Flags.isByVal()) {
3918     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3919       if (AvailableFPRs > 0) {
3920         --AvailableFPRs;
3921         return false;
3922       }
3923     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3924         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3925         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3926         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3927       if (AvailableVRs > 0) {
3928         --AvailableVRs;
3929         return false;
3930       }
3931   }
3932 
3933   return UseMemory;
3934 }
3935 
3936 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3937 /// ensure minimum alignment required for target.
3938 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3939                                      unsigned NumBytes) {
3940   return alignTo(NumBytes, Lowering->getStackAlign());
3941 }
3942 
3943 SDValue PPCTargetLowering::LowerFormalArguments(
3944     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3945     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3946     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3947   if (Subtarget.isAIXABI())
3948     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3949                                     InVals);
3950   if (Subtarget.is64BitELFABI())
3951     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3952                                        InVals);
3953   assert(Subtarget.is32BitELFABI());
3954   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3955                                      InVals);
3956 }
3957 
3958 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3959     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3960     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3961     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3962 
3963   // 32-bit SVR4 ABI Stack Frame Layout:
3964   //              +-----------------------------------+
3965   //        +-->  |            Back chain             |
3966   //        |     +-----------------------------------+
3967   //        |     | Floating-point register save area |
3968   //        |     +-----------------------------------+
3969   //        |     |    General register save area     |
3970   //        |     +-----------------------------------+
3971   //        |     |          CR save word             |
3972   //        |     +-----------------------------------+
3973   //        |     |         VRSAVE save word          |
3974   //        |     +-----------------------------------+
3975   //        |     |         Alignment padding         |
3976   //        |     +-----------------------------------+
3977   //        |     |     Vector register save area     |
3978   //        |     +-----------------------------------+
3979   //        |     |       Local variable space        |
3980   //        |     +-----------------------------------+
3981   //        |     |        Parameter list area        |
3982   //        |     +-----------------------------------+
3983   //        |     |           LR save word            |
3984   //        |     +-----------------------------------+
3985   // SP-->  +---  |            Back chain             |
3986   //              +-----------------------------------+
3987   //
3988   // Specifications:
3989   //   System V Application Binary Interface PowerPC Processor Supplement
3990   //   AltiVec Technology Programming Interface Manual
3991 
3992   MachineFunction &MF = DAG.getMachineFunction();
3993   MachineFrameInfo &MFI = MF.getFrameInfo();
3994   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3995 
3996   EVT PtrVT = getPointerTy(MF.getDataLayout());
3997   // Potential tail calls could cause overwriting of argument stack slots.
3998   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3999                        (CallConv == CallingConv::Fast));
4000   const Align PtrAlign(4);
4001 
4002   // Assign locations to all of the incoming arguments.
4003   SmallVector<CCValAssign, 16> ArgLocs;
4004   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4005                  *DAG.getContext());
4006 
4007   // Reserve space for the linkage area on the stack.
4008   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4009   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4010   if (useSoftFloat())
4011     CCInfo.PreAnalyzeFormalArguments(Ins);
4012 
4013   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4014   CCInfo.clearWasPPCF128();
4015 
4016   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4017     CCValAssign &VA = ArgLocs[i];
4018 
4019     // Arguments stored in registers.
4020     if (VA.isRegLoc()) {
4021       const TargetRegisterClass *RC;
4022       EVT ValVT = VA.getValVT();
4023 
4024       switch (ValVT.getSimpleVT().SimpleTy) {
4025         default:
4026           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4027         case MVT::i1:
4028         case MVT::i32:
4029           RC = &PPC::GPRCRegClass;
4030           break;
4031         case MVT::f32:
4032           if (Subtarget.hasP8Vector())
4033             RC = &PPC::VSSRCRegClass;
4034           else if (Subtarget.hasSPE())
4035             RC = &PPC::GPRCRegClass;
4036           else
4037             RC = &PPC::F4RCRegClass;
4038           break;
4039         case MVT::f64:
4040           if (Subtarget.hasVSX())
4041             RC = &PPC::VSFRCRegClass;
4042           else if (Subtarget.hasSPE())
4043             // SPE passes doubles in GPR pairs.
4044             RC = &PPC::GPRCRegClass;
4045           else
4046             RC = &PPC::F8RCRegClass;
4047           break;
4048         case MVT::v16i8:
4049         case MVT::v8i16:
4050         case MVT::v4i32:
4051           RC = &PPC::VRRCRegClass;
4052           break;
4053         case MVT::v4f32:
4054           RC = &PPC::VRRCRegClass;
4055           break;
4056         case MVT::v2f64:
4057         case MVT::v2i64:
4058           RC = &PPC::VRRCRegClass;
4059           break;
4060       }
4061 
4062       SDValue ArgValue;
4063       // Transform the arguments stored in physical registers into
4064       // virtual ones.
4065       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4066         assert(i + 1 < e && "No second half of double precision argument");
4067         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4068         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4069         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4070         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4071         if (!Subtarget.isLittleEndian())
4072           std::swap (ArgValueLo, ArgValueHi);
4073         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4074                                ArgValueHi);
4075       } else {
4076         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4077         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4078                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4079         if (ValVT == MVT::i1)
4080           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4081       }
4082 
4083       InVals.push_back(ArgValue);
4084     } else {
4085       // Argument stored in memory.
4086       assert(VA.isMemLoc());
4087 
4088       // Get the extended size of the argument type in stack
4089       unsigned ArgSize = VA.getLocVT().getStoreSize();
4090       // Get the actual size of the argument type
4091       unsigned ObjSize = VA.getValVT().getStoreSize();
4092       unsigned ArgOffset = VA.getLocMemOffset();
4093       // Stack objects in PPC32 are right justified.
4094       ArgOffset += ArgSize - ObjSize;
4095       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4096 
4097       // Create load nodes to retrieve arguments from the stack.
4098       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4099       InVals.push_back(
4100           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4101     }
4102   }
4103 
4104   // Assign locations to all of the incoming aggregate by value arguments.
4105   // Aggregates passed by value are stored in the local variable space of the
4106   // caller's stack frame, right above the parameter list area.
4107   SmallVector<CCValAssign, 16> ByValArgLocs;
4108   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4109                       ByValArgLocs, *DAG.getContext());
4110 
4111   // Reserve stack space for the allocations in CCInfo.
4112   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4113 
4114   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4115 
4116   // Area that is at least reserved in the caller of this function.
4117   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4118   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4119 
4120   // Set the size that is at least reserved in caller of this function.  Tail
4121   // call optimized function's reserved stack space needs to be aligned so that
4122   // taking the difference between two stack areas will result in an aligned
4123   // stack.
4124   MinReservedArea =
4125       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4126   FuncInfo->setMinReservedArea(MinReservedArea);
4127 
4128   SmallVector<SDValue, 8> MemOps;
4129 
4130   // If the function takes variable number of arguments, make a frame index for
4131   // the start of the first vararg value... for expansion of llvm.va_start.
4132   if (isVarArg) {
4133     static const MCPhysReg GPArgRegs[] = {
4134       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4135       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4136     };
4137     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4138 
4139     static const MCPhysReg FPArgRegs[] = {
4140       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4141       PPC::F8
4142     };
4143     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4144 
4145     if (useSoftFloat() || hasSPE())
4146        NumFPArgRegs = 0;
4147 
4148     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4149     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4150 
4151     // Make room for NumGPArgRegs and NumFPArgRegs.
4152     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4153                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4154 
4155     FuncInfo->setVarArgsStackOffset(
4156       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4157                             CCInfo.getNextStackOffset(), true));
4158 
4159     FuncInfo->setVarArgsFrameIndex(
4160         MFI.CreateStackObject(Depth, Align(8), false));
4161     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4162 
4163     // The fixed integer arguments of a variadic function are stored to the
4164     // VarArgsFrameIndex on the stack so that they may be loaded by
4165     // dereferencing the result of va_next.
4166     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4167       // Get an existing live-in vreg, or add a new one.
4168       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4169       if (!VReg)
4170         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4171 
4172       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4173       SDValue Store =
4174           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4175       MemOps.push_back(Store);
4176       // Increment the address by four for the next argument to store
4177       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4178       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4179     }
4180 
4181     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4182     // is set.
4183     // The double arguments are stored to the VarArgsFrameIndex
4184     // on the stack.
4185     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4186       // Get an existing live-in vreg, or add a new one.
4187       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4188       if (!VReg)
4189         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4190 
4191       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4192       SDValue Store =
4193           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4194       MemOps.push_back(Store);
4195       // Increment the address by eight for the next argument to store
4196       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4197                                          PtrVT);
4198       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4199     }
4200   }
4201 
4202   if (!MemOps.empty())
4203     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4204 
4205   return Chain;
4206 }
4207 
4208 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4209 // value to MVT::i64 and then truncate to the correct register size.
4210 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4211                                              EVT ObjectVT, SelectionDAG &DAG,
4212                                              SDValue ArgVal,
4213                                              const SDLoc &dl) const {
4214   if (Flags.isSExt())
4215     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4216                          DAG.getValueType(ObjectVT));
4217   else if (Flags.isZExt())
4218     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4219                          DAG.getValueType(ObjectVT));
4220 
4221   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4222 }
4223 
4224 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4225     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4226     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4227     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4228   // TODO: add description of PPC stack frame format, or at least some docs.
4229   //
4230   bool isELFv2ABI = Subtarget.isELFv2ABI();
4231   bool isLittleEndian = Subtarget.isLittleEndian();
4232   MachineFunction &MF = DAG.getMachineFunction();
4233   MachineFrameInfo &MFI = MF.getFrameInfo();
4234   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4235 
4236   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4237          "fastcc not supported on varargs functions");
4238 
4239   EVT PtrVT = getPointerTy(MF.getDataLayout());
4240   // Potential tail calls could cause overwriting of argument stack slots.
4241   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4242                        (CallConv == CallingConv::Fast));
4243   unsigned PtrByteSize = 8;
4244   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4245 
4246   static const MCPhysReg GPR[] = {
4247     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4248     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4249   };
4250   static const MCPhysReg VR[] = {
4251     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4252     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4253   };
4254 
4255   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4256   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4257   const unsigned Num_VR_Regs  = array_lengthof(VR);
4258 
4259   // Do a first pass over the arguments to determine whether the ABI
4260   // guarantees that our caller has allocated the parameter save area
4261   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4262   // in the ELFv2 ABI, it is true if this is a vararg function or if
4263   // any parameter is located in a stack slot.
4264 
4265   bool HasParameterArea = !isELFv2ABI || isVarArg;
4266   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4267   unsigned NumBytes = LinkageSize;
4268   unsigned AvailableFPRs = Num_FPR_Regs;
4269   unsigned AvailableVRs = Num_VR_Regs;
4270   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4271     if (Ins[i].Flags.isNest())
4272       continue;
4273 
4274     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4275                                PtrByteSize, LinkageSize, ParamAreaSize,
4276                                NumBytes, AvailableFPRs, AvailableVRs))
4277       HasParameterArea = true;
4278   }
4279 
4280   // Add DAG nodes to load the arguments or copy them out of registers.  On
4281   // entry to a function on PPC, the arguments start after the linkage area,
4282   // although the first ones are often in registers.
4283 
4284   unsigned ArgOffset = LinkageSize;
4285   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4286   SmallVector<SDValue, 8> MemOps;
4287   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4288   unsigned CurArgIdx = 0;
4289   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4290     SDValue ArgVal;
4291     bool needsLoad = false;
4292     EVT ObjectVT = Ins[ArgNo].VT;
4293     EVT OrigVT = Ins[ArgNo].ArgVT;
4294     unsigned ObjSize = ObjectVT.getStoreSize();
4295     unsigned ArgSize = ObjSize;
4296     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4297     if (Ins[ArgNo].isOrigArg()) {
4298       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4299       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4300     }
4301     // We re-align the argument offset for each argument, except when using the
4302     // fast calling convention, when we need to make sure we do that only when
4303     // we'll actually use a stack slot.
4304     unsigned CurArgOffset;
4305     Align Alignment;
4306     auto ComputeArgOffset = [&]() {
4307       /* Respect alignment of argument on the stack.  */
4308       Alignment =
4309           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4310       ArgOffset = alignTo(ArgOffset, Alignment);
4311       CurArgOffset = ArgOffset;
4312     };
4313 
4314     if (CallConv != CallingConv::Fast) {
4315       ComputeArgOffset();
4316 
4317       /* Compute GPR index associated with argument offset.  */
4318       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4319       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4320     }
4321 
4322     // FIXME the codegen can be much improved in some cases.
4323     // We do not have to keep everything in memory.
4324     if (Flags.isByVal()) {
4325       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4326 
4327       if (CallConv == CallingConv::Fast)
4328         ComputeArgOffset();
4329 
4330       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4331       ObjSize = Flags.getByValSize();
4332       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4333       // Empty aggregate parameters do not take up registers.  Examples:
4334       //   struct { } a;
4335       //   union  { } b;
4336       //   int c[0];
4337       // etc.  However, we have to provide a place-holder in InVals, so
4338       // pretend we have an 8-byte item at the current address for that
4339       // purpose.
4340       if (!ObjSize) {
4341         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4342         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4343         InVals.push_back(FIN);
4344         continue;
4345       }
4346 
4347       // Create a stack object covering all stack doublewords occupied
4348       // by the argument.  If the argument is (fully or partially) on
4349       // the stack, or if the argument is fully in registers but the
4350       // caller has allocated the parameter save anyway, we can refer
4351       // directly to the caller's stack frame.  Otherwise, create a
4352       // local copy in our own frame.
4353       int FI;
4354       if (HasParameterArea ||
4355           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4356         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4357       else
4358         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4359       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4360 
4361       // Handle aggregates smaller than 8 bytes.
4362       if (ObjSize < PtrByteSize) {
4363         // The value of the object is its address, which differs from the
4364         // address of the enclosing doubleword on big-endian systems.
4365         SDValue Arg = FIN;
4366         if (!isLittleEndian) {
4367           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4368           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4369         }
4370         InVals.push_back(Arg);
4371 
4372         if (GPR_idx != Num_GPR_Regs) {
4373           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4374           FuncInfo->addLiveInAttr(VReg, Flags);
4375           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4376           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4377           SDValue Store =
4378               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4379                                 MachinePointerInfo(&*FuncArg), ObjType);
4380           MemOps.push_back(Store);
4381         }
4382         // Whether we copied from a register or not, advance the offset
4383         // into the parameter save area by a full doubleword.
4384         ArgOffset += PtrByteSize;
4385         continue;
4386       }
4387 
4388       // The value of the object is its address, which is the address of
4389       // its first stack doubleword.
4390       InVals.push_back(FIN);
4391 
4392       // Store whatever pieces of the object are in registers to memory.
4393       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4394         if (GPR_idx == Num_GPR_Regs)
4395           break;
4396 
4397         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4398         FuncInfo->addLiveInAttr(VReg, Flags);
4399         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4400         SDValue Addr = FIN;
4401         if (j) {
4402           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4403           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4404         }
4405         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4406                                      MachinePointerInfo(&*FuncArg, j));
4407         MemOps.push_back(Store);
4408         ++GPR_idx;
4409       }
4410       ArgOffset += ArgSize;
4411       continue;
4412     }
4413 
4414     switch (ObjectVT.getSimpleVT().SimpleTy) {
4415     default: llvm_unreachable("Unhandled argument type!");
4416     case MVT::i1:
4417     case MVT::i32:
4418     case MVT::i64:
4419       if (Flags.isNest()) {
4420         // The 'nest' parameter, if any, is passed in R11.
4421         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4422         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4423 
4424         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4425           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4426 
4427         break;
4428       }
4429 
4430       // These can be scalar arguments or elements of an integer array type
4431       // passed directly.  Clang may use those instead of "byval" aggregate
4432       // types to avoid forcing arguments to memory unnecessarily.
4433       if (GPR_idx != Num_GPR_Regs) {
4434         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4435         FuncInfo->addLiveInAttr(VReg, Flags);
4436         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4437 
4438         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4439           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4440           // value to MVT::i64 and then truncate to the correct register size.
4441           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4442       } else {
4443         if (CallConv == CallingConv::Fast)
4444           ComputeArgOffset();
4445 
4446         needsLoad = true;
4447         ArgSize = PtrByteSize;
4448       }
4449       if (CallConv != CallingConv::Fast || needsLoad)
4450         ArgOffset += 8;
4451       break;
4452 
4453     case MVT::f32:
4454     case MVT::f64:
4455       // These can be scalar arguments or elements of a float array type
4456       // passed directly.  The latter are used to implement ELFv2 homogenous
4457       // float aggregates.
4458       if (FPR_idx != Num_FPR_Regs) {
4459         unsigned VReg;
4460 
4461         if (ObjectVT == MVT::f32)
4462           VReg = MF.addLiveIn(FPR[FPR_idx],
4463                               Subtarget.hasP8Vector()
4464                                   ? &PPC::VSSRCRegClass
4465                                   : &PPC::F4RCRegClass);
4466         else
4467           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4468                                                 ? &PPC::VSFRCRegClass
4469                                                 : &PPC::F8RCRegClass);
4470 
4471         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4472         ++FPR_idx;
4473       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4474         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4475         // once we support fp <-> gpr moves.
4476 
4477         // This can only ever happen in the presence of f32 array types,
4478         // since otherwise we never run out of FPRs before running out
4479         // of GPRs.
4480         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4481         FuncInfo->addLiveInAttr(VReg, Flags);
4482         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4483 
4484         if (ObjectVT == MVT::f32) {
4485           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4486             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4487                                  DAG.getConstant(32, dl, MVT::i32));
4488           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4489         }
4490 
4491         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4492       } else {
4493         if (CallConv == CallingConv::Fast)
4494           ComputeArgOffset();
4495 
4496         needsLoad = true;
4497       }
4498 
4499       // When passing an array of floats, the array occupies consecutive
4500       // space in the argument area; only round up to the next doubleword
4501       // at the end of the array.  Otherwise, each float takes 8 bytes.
4502       if (CallConv != CallingConv::Fast || needsLoad) {
4503         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4504         ArgOffset += ArgSize;
4505         if (Flags.isInConsecutiveRegsLast())
4506           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4507       }
4508       break;
4509     case MVT::v4f32:
4510     case MVT::v4i32:
4511     case MVT::v8i16:
4512     case MVT::v16i8:
4513     case MVT::v2f64:
4514     case MVT::v2i64:
4515     case MVT::v1i128:
4516     case MVT::f128:
4517       // These can be scalar arguments or elements of a vector array type
4518       // passed directly.  The latter are used to implement ELFv2 homogenous
4519       // vector aggregates.
4520       if (VR_idx != Num_VR_Regs) {
4521         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4522         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4523         ++VR_idx;
4524       } else {
4525         if (CallConv == CallingConv::Fast)
4526           ComputeArgOffset();
4527         needsLoad = true;
4528       }
4529       if (CallConv != CallingConv::Fast || needsLoad)
4530         ArgOffset += 16;
4531       break;
4532     }
4533 
4534     // We need to load the argument to a virtual register if we determined
4535     // above that we ran out of physical registers of the appropriate type.
4536     if (needsLoad) {
4537       if (ObjSize < ArgSize && !isLittleEndian)
4538         CurArgOffset += ArgSize - ObjSize;
4539       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4540       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4541       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4542     }
4543 
4544     InVals.push_back(ArgVal);
4545   }
4546 
4547   // Area that is at least reserved in the caller of this function.
4548   unsigned MinReservedArea;
4549   if (HasParameterArea)
4550     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4551   else
4552     MinReservedArea = LinkageSize;
4553 
4554   // Set the size that is at least reserved in caller of this function.  Tail
4555   // call optimized functions' reserved stack space needs to be aligned so that
4556   // taking the difference between two stack areas will result in an aligned
4557   // stack.
4558   MinReservedArea =
4559       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4560   FuncInfo->setMinReservedArea(MinReservedArea);
4561 
4562   // If the function takes variable number of arguments, make a frame index for
4563   // the start of the first vararg value... for expansion of llvm.va_start.
4564   // On ELFv2ABI spec, it writes:
4565   // C programs that are intended to be *portable* across different compilers
4566   // and architectures must use the header file <stdarg.h> to deal with variable
4567   // argument lists.
4568   if (isVarArg && MFI.hasVAStart()) {
4569     int Depth = ArgOffset;
4570 
4571     FuncInfo->setVarArgsFrameIndex(
4572       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4573     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4574 
4575     // If this function is vararg, store any remaining integer argument regs
4576     // to their spots on the stack so that they may be loaded by dereferencing
4577     // the result of va_next.
4578     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4579          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4580       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4581       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4582       SDValue Store =
4583           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4584       MemOps.push_back(Store);
4585       // Increment the address by four for the next argument to store
4586       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4587       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4588     }
4589   }
4590 
4591   if (!MemOps.empty())
4592     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4593 
4594   return Chain;
4595 }
4596 
4597 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4598 /// adjusted to accommodate the arguments for the tailcall.
4599 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4600                                    unsigned ParamSize) {
4601 
4602   if (!isTailCall) return 0;
4603 
4604   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4605   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4606   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4607   // Remember only if the new adjustment is bigger.
4608   if (SPDiff < FI->getTailCallSPDelta())
4609     FI->setTailCallSPDelta(SPDiff);
4610 
4611   return SPDiff;
4612 }
4613 
4614 static bool isFunctionGlobalAddress(SDValue Callee);
4615 
4616 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4617                               const TargetMachine &TM) {
4618   // It does not make sense to call callsShareTOCBase() with a caller that
4619   // is PC Relative since PC Relative callers do not have a TOC.
4620 #ifndef NDEBUG
4621   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4622   assert(!STICaller->isUsingPCRelativeCalls() &&
4623          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4624 #endif
4625 
4626   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4627   // don't have enough information to determine if the caller and callee share
4628   // the same  TOC base, so we have to pessimistically assume they don't for
4629   // correctness.
4630   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4631   if (!G)
4632     return false;
4633 
4634   const GlobalValue *GV = G->getGlobal();
4635 
4636   // If the callee is preemptable, then the static linker will use a plt-stub
4637   // which saves the toc to the stack, and needs a nop after the call
4638   // instruction to convert to a toc-restore.
4639   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4640     return false;
4641 
4642   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4643   // We may need a TOC restore in the situation where the caller requires a
4644   // valid TOC but the callee is PC Relative and does not.
4645   const Function *F = dyn_cast<Function>(GV);
4646   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4647 
4648   // If we have an Alias we can try to get the function from there.
4649   if (Alias) {
4650     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4651     F = dyn_cast<Function>(GlobalObj);
4652   }
4653 
4654   // If we still have no valid function pointer we do not have enough
4655   // information to determine if the callee uses PC Relative calls so we must
4656   // assume that it does.
4657   if (!F)
4658     return false;
4659 
4660   // If the callee uses PC Relative we cannot guarantee that the callee won't
4661   // clobber the TOC of the caller and so we must assume that the two
4662   // functions do not share a TOC base.
4663   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4664   if (STICallee->isUsingPCRelativeCalls())
4665     return false;
4666 
4667   // If the GV is not a strong definition then we need to assume it can be
4668   // replaced by another function at link time. The function that replaces
4669   // it may not share the same TOC as the caller since the callee may be
4670   // replaced by a PC Relative version of the same function.
4671   if (!GV->isStrongDefinitionForLinker())
4672     return false;
4673 
4674   // The medium and large code models are expected to provide a sufficiently
4675   // large TOC to provide all data addressing needs of a module with a
4676   // single TOC.
4677   if (CodeModel::Medium == TM.getCodeModel() ||
4678       CodeModel::Large == TM.getCodeModel())
4679     return true;
4680 
4681   // Any explicitly-specified sections and section prefixes must also match.
4682   // Also, if we're using -ffunction-sections, then each function is always in
4683   // a different section (the same is true for COMDAT functions).
4684   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4685       GV->getSection() != Caller->getSection())
4686     return false;
4687   if (const auto *F = dyn_cast<Function>(GV)) {
4688     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4689       return false;
4690   }
4691 
4692   return true;
4693 }
4694 
4695 static bool
4696 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4697                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4698   assert(Subtarget.is64BitELFABI());
4699 
4700   const unsigned PtrByteSize = 8;
4701   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4702 
4703   static const MCPhysReg GPR[] = {
4704     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4705     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4706   };
4707   static const MCPhysReg VR[] = {
4708     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4709     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4710   };
4711 
4712   const unsigned NumGPRs = array_lengthof(GPR);
4713   const unsigned NumFPRs = 13;
4714   const unsigned NumVRs = array_lengthof(VR);
4715   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4716 
4717   unsigned NumBytes = LinkageSize;
4718   unsigned AvailableFPRs = NumFPRs;
4719   unsigned AvailableVRs = NumVRs;
4720 
4721   for (const ISD::OutputArg& Param : Outs) {
4722     if (Param.Flags.isNest()) continue;
4723 
4724     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4725                                LinkageSize, ParamAreaSize, NumBytes,
4726                                AvailableFPRs, AvailableVRs))
4727       return true;
4728   }
4729   return false;
4730 }
4731 
4732 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4733   if (CB.arg_size() != CallerFn->arg_size())
4734     return false;
4735 
4736   auto CalleeArgIter = CB.arg_begin();
4737   auto CalleeArgEnd = CB.arg_end();
4738   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4739 
4740   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4741     const Value* CalleeArg = *CalleeArgIter;
4742     const Value* CallerArg = &(*CallerArgIter);
4743     if (CalleeArg == CallerArg)
4744       continue;
4745 
4746     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4747     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4748     //      }
4749     // 1st argument of callee is undef and has the same type as caller.
4750     if (CalleeArg->getType() == CallerArg->getType() &&
4751         isa<UndefValue>(CalleeArg))
4752       continue;
4753 
4754     return false;
4755   }
4756 
4757   return true;
4758 }
4759 
4760 // Returns true if TCO is possible between the callers and callees
4761 // calling conventions.
4762 static bool
4763 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4764                                     CallingConv::ID CalleeCC) {
4765   // Tail calls are possible with fastcc and ccc.
4766   auto isTailCallableCC  = [] (CallingConv::ID CC){
4767       return  CC == CallingConv::C || CC == CallingConv::Fast;
4768   };
4769   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4770     return false;
4771 
4772   // We can safely tail call both fastcc and ccc callees from a c calling
4773   // convention caller. If the caller is fastcc, we may have less stack space
4774   // than a non-fastcc caller with the same signature so disable tail-calls in
4775   // that case.
4776   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4777 }
4778 
4779 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4780     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4781     const SmallVectorImpl<ISD::OutputArg> &Outs,
4782     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4783   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4784 
4785   if (DisableSCO && !TailCallOpt) return false;
4786 
4787   // Variadic argument functions are not supported.
4788   if (isVarArg) return false;
4789 
4790   auto &Caller = DAG.getMachineFunction().getFunction();
4791   // Check that the calling conventions are compatible for tco.
4792   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4793     return false;
4794 
4795   // Caller contains any byval parameter is not supported.
4796   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4797     return false;
4798 
4799   // Callee contains any byval parameter is not supported, too.
4800   // Note: This is a quick work around, because in some cases, e.g.
4801   // caller's stack size > callee's stack size, we are still able to apply
4802   // sibling call optimization. For example, gcc is able to do SCO for caller1
4803   // in the following example, but not for caller2.
4804   //   struct test {
4805   //     long int a;
4806   //     char ary[56];
4807   //   } gTest;
4808   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4809   //     b->a = v.a;
4810   //     return 0;
4811   //   }
4812   //   void caller1(struct test a, struct test c, struct test *b) {
4813   //     callee(gTest, b); }
4814   //   void caller2(struct test *b) { callee(gTest, b); }
4815   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4816     return false;
4817 
4818   // If callee and caller use different calling conventions, we cannot pass
4819   // parameters on stack since offsets for the parameter area may be different.
4820   if (Caller.getCallingConv() != CalleeCC &&
4821       needStackSlotPassParameters(Subtarget, Outs))
4822     return false;
4823 
4824   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4825   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4826   // callee potentially have different TOC bases then we cannot tail call since
4827   // we need to restore the TOC pointer after the call.
4828   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4829   // We cannot guarantee this for indirect calls or calls to external functions.
4830   // When PC-Relative addressing is used, the concept of the TOC is no longer
4831   // applicable so this check is not required.
4832   // Check first for indirect calls.
4833   if (!Subtarget.isUsingPCRelativeCalls() &&
4834       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4835     return false;
4836 
4837   // Check if we share the TOC base.
4838   if (!Subtarget.isUsingPCRelativeCalls() &&
4839       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4840     return false;
4841 
4842   // TCO allows altering callee ABI, so we don't have to check further.
4843   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4844     return true;
4845 
4846   if (DisableSCO) return false;
4847 
4848   // If callee use the same argument list that caller is using, then we can
4849   // apply SCO on this case. If it is not, then we need to check if callee needs
4850   // stack for passing arguments.
4851   // PC Relative tail calls may not have a CallBase.
4852   // If there is no CallBase we cannot verify if we have the same argument
4853   // list so assume that we don't have the same argument list.
4854   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4855       needStackSlotPassParameters(Subtarget, Outs))
4856     return false;
4857   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4858     return false;
4859 
4860   return true;
4861 }
4862 
4863 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4864 /// for tail call optimization. Targets which want to do tail call
4865 /// optimization should implement this function.
4866 bool
4867 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4868                                                      CallingConv::ID CalleeCC,
4869                                                      bool isVarArg,
4870                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4871                                                      SelectionDAG& DAG) const {
4872   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4873     return false;
4874 
4875   // Variable argument functions are not supported.
4876   if (isVarArg)
4877     return false;
4878 
4879   MachineFunction &MF = DAG.getMachineFunction();
4880   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4881   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4882     // Functions containing by val parameters are not supported.
4883     for (unsigned i = 0; i != Ins.size(); i++) {
4884        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4885        if (Flags.isByVal()) return false;
4886     }
4887 
4888     // Non-PIC/GOT tail calls are supported.
4889     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4890       return true;
4891 
4892     // At the moment we can only do local tail calls (in same module, hidden
4893     // or protected) if we are generating PIC.
4894     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4895       return G->getGlobal()->hasHiddenVisibility()
4896           || G->getGlobal()->hasProtectedVisibility();
4897   }
4898 
4899   return false;
4900 }
4901 
4902 /// isCallCompatibleAddress - Return the immediate to use if the specified
4903 /// 32-bit value is representable in the immediate field of a BxA instruction.
4904 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4905   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4906   if (!C) return nullptr;
4907 
4908   int Addr = C->getZExtValue();
4909   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4910       SignExtend32<26>(Addr) != Addr)
4911     return nullptr;  // Top 6 bits have to be sext of immediate.
4912 
4913   return DAG
4914       .getConstant(
4915           (int)C->getZExtValue() >> 2, SDLoc(Op),
4916           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4917       .getNode();
4918 }
4919 
4920 namespace {
4921 
4922 struct TailCallArgumentInfo {
4923   SDValue Arg;
4924   SDValue FrameIdxOp;
4925   int FrameIdx = 0;
4926 
4927   TailCallArgumentInfo() = default;
4928 };
4929 
4930 } // end anonymous namespace
4931 
4932 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4933 static void StoreTailCallArgumentsToStackSlot(
4934     SelectionDAG &DAG, SDValue Chain,
4935     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4936     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4937   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4938     SDValue Arg = TailCallArgs[i].Arg;
4939     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4940     int FI = TailCallArgs[i].FrameIdx;
4941     // Store relative to framepointer.
4942     MemOpChains.push_back(DAG.getStore(
4943         Chain, dl, Arg, FIN,
4944         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4945   }
4946 }
4947 
4948 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4949 /// the appropriate stack slot for the tail call optimized function call.
4950 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4951                                              SDValue OldRetAddr, SDValue OldFP,
4952                                              int SPDiff, const SDLoc &dl) {
4953   if (SPDiff) {
4954     // Calculate the new stack slot for the return address.
4955     MachineFunction &MF = DAG.getMachineFunction();
4956     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4957     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4958     bool isPPC64 = Subtarget.isPPC64();
4959     int SlotSize = isPPC64 ? 8 : 4;
4960     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4961     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4962                                                          NewRetAddrLoc, true);
4963     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4964     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4965     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4966                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4967   }
4968   return Chain;
4969 }
4970 
4971 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4972 /// the position of the argument.
4973 static void
4974 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4975                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4976                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4977   int Offset = ArgOffset + SPDiff;
4978   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4979   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4980   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4981   SDValue FIN = DAG.getFrameIndex(FI, VT);
4982   TailCallArgumentInfo Info;
4983   Info.Arg = Arg;
4984   Info.FrameIdxOp = FIN;
4985   Info.FrameIdx = FI;
4986   TailCallArguments.push_back(Info);
4987 }
4988 
4989 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4990 /// stack slot. Returns the chain as result and the loaded frame pointers in
4991 /// LROpOut/FPOpout. Used when tail calling.
4992 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4993     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4994     SDValue &FPOpOut, const SDLoc &dl) const {
4995   if (SPDiff) {
4996     // Load the LR and FP stack slot for later adjusting.
4997     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4998     LROpOut = getReturnAddrFrameIndex(DAG);
4999     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5000     Chain = SDValue(LROpOut.getNode(), 1);
5001   }
5002   return Chain;
5003 }
5004 
5005 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5006 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5007 /// specified by the specific parameter attribute. The copy will be passed as
5008 /// a byval function parameter.
5009 /// Sometimes what we are copying is the end of a larger object, the part that
5010 /// does not fit in registers.
5011 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5012                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5013                                          SelectionDAG &DAG, const SDLoc &dl) {
5014   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5015   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5016                        Flags.getNonZeroByValAlign(), false, false, false,
5017                        MachinePointerInfo(), MachinePointerInfo());
5018 }
5019 
5020 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5021 /// tail calls.
5022 static void LowerMemOpCallTo(
5023     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5024     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5025     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5026     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5027   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5028   if (!isTailCall) {
5029     if (isVector) {
5030       SDValue StackPtr;
5031       if (isPPC64)
5032         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5033       else
5034         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5035       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5036                            DAG.getConstant(ArgOffset, dl, PtrVT));
5037     }
5038     MemOpChains.push_back(
5039         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5040     // Calculate and remember argument location.
5041   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5042                                   TailCallArguments);
5043 }
5044 
5045 static void
5046 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5047                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5048                 SDValue FPOp,
5049                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5050   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5051   // might overwrite each other in case of tail call optimization.
5052   SmallVector<SDValue, 8> MemOpChains2;
5053   // Do not flag preceding copytoreg stuff together with the following stuff.
5054   InFlag = SDValue();
5055   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5056                                     MemOpChains2, dl);
5057   if (!MemOpChains2.empty())
5058     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5059 
5060   // Store the return address to the appropriate stack slot.
5061   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5062 
5063   // Emit callseq_end just before tailcall node.
5064   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5065                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5066   InFlag = Chain.getValue(1);
5067 }
5068 
5069 // Is this global address that of a function that can be called by name? (as
5070 // opposed to something that must hold a descriptor for an indirect call).
5071 static bool isFunctionGlobalAddress(SDValue Callee) {
5072   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5073     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5074         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5075       return false;
5076 
5077     return G->getGlobal()->getValueType()->isFunctionTy();
5078   }
5079 
5080   return false;
5081 }
5082 
5083 SDValue PPCTargetLowering::LowerCallResult(
5084     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5085     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5086     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5087   SmallVector<CCValAssign, 16> RVLocs;
5088   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5089                     *DAG.getContext());
5090 
5091   CCRetInfo.AnalyzeCallResult(
5092       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5093                ? RetCC_PPC_Cold
5094                : RetCC_PPC);
5095 
5096   // Copy all of the result registers out of their specified physreg.
5097   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5098     CCValAssign &VA = RVLocs[i];
5099     assert(VA.isRegLoc() && "Can only return in registers!");
5100 
5101     SDValue Val;
5102 
5103     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5104       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5105                                       InFlag);
5106       Chain = Lo.getValue(1);
5107       InFlag = Lo.getValue(2);
5108       VA = RVLocs[++i]; // skip ahead to next loc
5109       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5110                                       InFlag);
5111       Chain = Hi.getValue(1);
5112       InFlag = Hi.getValue(2);
5113       if (!Subtarget.isLittleEndian())
5114         std::swap (Lo, Hi);
5115       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5116     } else {
5117       Val = DAG.getCopyFromReg(Chain, dl,
5118                                VA.getLocReg(), VA.getLocVT(), InFlag);
5119       Chain = Val.getValue(1);
5120       InFlag = Val.getValue(2);
5121     }
5122 
5123     switch (VA.getLocInfo()) {
5124     default: llvm_unreachable("Unknown loc info!");
5125     case CCValAssign::Full: break;
5126     case CCValAssign::AExt:
5127       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5128       break;
5129     case CCValAssign::ZExt:
5130       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5131                         DAG.getValueType(VA.getValVT()));
5132       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5133       break;
5134     case CCValAssign::SExt:
5135       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5136                         DAG.getValueType(VA.getValVT()));
5137       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5138       break;
5139     }
5140 
5141     InVals.push_back(Val);
5142   }
5143 
5144   return Chain;
5145 }
5146 
5147 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5148                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5149   // PatchPoint calls are not indirect.
5150   if (isPatchPoint)
5151     return false;
5152 
5153   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5154     return false;
5155 
5156   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5157   // becuase the immediate function pointer points to a descriptor instead of
5158   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5159   // pointer immediate points to the global entry point, while the BLA would
5160   // need to jump to the local entry point (see rL211174).
5161   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5162       isBLACompatibleAddress(Callee, DAG))
5163     return false;
5164 
5165   return true;
5166 }
5167 
5168 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5169 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5170   return Subtarget.isAIXABI() ||
5171          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5172 }
5173 
5174 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5175                               const Function &Caller,
5176                               const SDValue &Callee,
5177                               const PPCSubtarget &Subtarget,
5178                               const TargetMachine &TM) {
5179   if (CFlags.IsTailCall)
5180     return PPCISD::TC_RETURN;
5181 
5182   // This is a call through a function pointer.
5183   if (CFlags.IsIndirect) {
5184     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5185     // indirect calls. The save of the caller's TOC pointer to the stack will be
5186     // inserted into the DAG as part of call lowering. The restore of the TOC
5187     // pointer is modeled by using a pseudo instruction for the call opcode that
5188     // represents the 2 instruction sequence of an indirect branch and link,
5189     // immediately followed by a load of the TOC pointer from the the stack save
5190     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5191     // as it is not saved or used.
5192     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5193                                                : PPCISD::BCTRL;
5194   }
5195 
5196   if (Subtarget.isUsingPCRelativeCalls()) {
5197     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5198     return PPCISD::CALL_NOTOC;
5199   }
5200 
5201   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5202   // immediately following the call instruction if the caller and callee may
5203   // have different TOC bases. At link time if the linker determines the calls
5204   // may not share a TOC base, the call is redirected to a trampoline inserted
5205   // by the linker. The trampoline will (among other things) save the callers
5206   // TOC pointer at an ABI designated offset in the linkage area and the linker
5207   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5208   // into gpr2.
5209   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5210     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5211                                                   : PPCISD::CALL_NOP;
5212 
5213   return PPCISD::CALL;
5214 }
5215 
5216 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5217                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5218   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5219     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5220       return SDValue(Dest, 0);
5221 
5222   // Returns true if the callee is local, and false otherwise.
5223   auto isLocalCallee = [&]() {
5224     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5225     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5226     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5227 
5228     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5229            !dyn_cast_or_null<GlobalIFunc>(GV);
5230   };
5231 
5232   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5233   // a static relocation model causes some versions of GNU LD (2.17.50, at
5234   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5235   // built with secure-PLT.
5236   bool UsePlt =
5237       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5238       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5239 
5240   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5241     const TargetMachine &TM = Subtarget.getTargetMachine();
5242     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5243     MCSymbolXCOFF *S =
5244         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5245 
5246     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5247     return DAG.getMCSymbol(S, PtrVT);
5248   };
5249 
5250   if (isFunctionGlobalAddress(Callee)) {
5251     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5252 
5253     if (Subtarget.isAIXABI()) {
5254       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5255       return getAIXFuncEntryPointSymbolSDNode(GV);
5256     }
5257     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5258                                       UsePlt ? PPCII::MO_PLT : 0);
5259   }
5260 
5261   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5262     const char *SymName = S->getSymbol();
5263     if (Subtarget.isAIXABI()) {
5264       // If there exists a user-declared function whose name is the same as the
5265       // ExternalSymbol's, then we pick up the user-declared version.
5266       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5267       if (const Function *F =
5268               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5269         return getAIXFuncEntryPointSymbolSDNode(F);
5270 
5271       // On AIX, direct function calls reference the symbol for the function's
5272       // entry point, which is named by prepending a "." before the function's
5273       // C-linkage name. A Qualname is returned here because an external
5274       // function entry point is a csect with XTY_ER property.
5275       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5276         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5277         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5278             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5279             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5280         return Sec->getQualNameSymbol();
5281       };
5282 
5283       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5284     }
5285     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5286                                        UsePlt ? PPCII::MO_PLT : 0);
5287   }
5288 
5289   // No transformation needed.
5290   assert(Callee.getNode() && "What no callee?");
5291   return Callee;
5292 }
5293 
5294 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5295   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5296          "Expected a CALLSEQ_STARTSDNode.");
5297 
5298   // The last operand is the chain, except when the node has glue. If the node
5299   // has glue, then the last operand is the glue, and the chain is the second
5300   // last operand.
5301   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5302   if (LastValue.getValueType() != MVT::Glue)
5303     return LastValue;
5304 
5305   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5306 }
5307 
5308 // Creates the node that moves a functions address into the count register
5309 // to prepare for an indirect call instruction.
5310 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5311                                 SDValue &Glue, SDValue &Chain,
5312                                 const SDLoc &dl) {
5313   SDValue MTCTROps[] = {Chain, Callee, Glue};
5314   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5315   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5316                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5317   // The glue is the second value produced.
5318   Glue = Chain.getValue(1);
5319 }
5320 
5321 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5322                                           SDValue &Glue, SDValue &Chain,
5323                                           SDValue CallSeqStart,
5324                                           const CallBase *CB, const SDLoc &dl,
5325                                           bool hasNest,
5326                                           const PPCSubtarget &Subtarget) {
5327   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5328   // entry point, but to the function descriptor (the function entry point
5329   // address is part of the function descriptor though).
5330   // The function descriptor is a three doubleword structure with the
5331   // following fields: function entry point, TOC base address and
5332   // environment pointer.
5333   // Thus for a call through a function pointer, the following actions need
5334   // to be performed:
5335   //   1. Save the TOC of the caller in the TOC save area of its stack
5336   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5337   //   2. Load the address of the function entry point from the function
5338   //      descriptor.
5339   //   3. Load the TOC of the callee from the function descriptor into r2.
5340   //   4. Load the environment pointer from the function descriptor into
5341   //      r11.
5342   //   5. Branch to the function entry point address.
5343   //   6. On return of the callee, the TOC of the caller needs to be
5344   //      restored (this is done in FinishCall()).
5345   //
5346   // The loads are scheduled at the beginning of the call sequence, and the
5347   // register copies are flagged together to ensure that no other
5348   // operations can be scheduled in between. E.g. without flagging the
5349   // copies together, a TOC access in the caller could be scheduled between
5350   // the assignment of the callee TOC and the branch to the callee, which leads
5351   // to incorrect code.
5352 
5353   // Start by loading the function address from the descriptor.
5354   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5355   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5356                       ? (MachineMemOperand::MODereferenceable |
5357                          MachineMemOperand::MOInvariant)
5358                       : MachineMemOperand::MONone;
5359 
5360   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5361 
5362   // Registers used in building the DAG.
5363   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5364   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5365 
5366   // Offsets of descriptor members.
5367   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5368   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5369 
5370   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5371   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5372 
5373   // One load for the functions entry point address.
5374   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5375                                     Alignment, MMOFlags);
5376 
5377   // One for loading the TOC anchor for the module that contains the called
5378   // function.
5379   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5380   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5381   SDValue TOCPtr =
5382       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5383                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5384 
5385   // One for loading the environment pointer.
5386   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5387   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5388   SDValue LoadEnvPtr =
5389       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5390                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5391 
5392 
5393   // Then copy the newly loaded TOC anchor to the TOC pointer.
5394   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5395   Chain = TOCVal.getValue(0);
5396   Glue = TOCVal.getValue(1);
5397 
5398   // If the function call has an explicit 'nest' parameter, it takes the
5399   // place of the environment pointer.
5400   assert((!hasNest || !Subtarget.isAIXABI()) &&
5401          "Nest parameter is not supported on AIX.");
5402   if (!hasNest) {
5403     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5404     Chain = EnvVal.getValue(0);
5405     Glue = EnvVal.getValue(1);
5406   }
5407 
5408   // The rest of the indirect call sequence is the same as the non-descriptor
5409   // DAG.
5410   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5411 }
5412 
5413 static void
5414 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5415                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5416                   SelectionDAG &DAG,
5417                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5418                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5419                   const PPCSubtarget &Subtarget) {
5420   const bool IsPPC64 = Subtarget.isPPC64();
5421   // MVT for a general purpose register.
5422   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5423 
5424   // First operand is always the chain.
5425   Ops.push_back(Chain);
5426 
5427   // If it's a direct call pass the callee as the second operand.
5428   if (!CFlags.IsIndirect)
5429     Ops.push_back(Callee);
5430   else {
5431     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5432 
5433     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5434     // on the stack (this would have been done in `LowerCall_64SVR4` or
5435     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5436     // represents both the indirect branch and a load that restores the TOC
5437     // pointer from the linkage area. The operand for the TOC restore is an add
5438     // of the TOC save offset to the stack pointer. This must be the second
5439     // operand: after the chain input but before any other variadic arguments.
5440     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5441     // saved or used.
5442     if (isTOCSaveRestoreRequired(Subtarget)) {
5443       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5444 
5445       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5446       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5447       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5448       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5449       Ops.push_back(AddTOC);
5450     }
5451 
5452     // Add the register used for the environment pointer.
5453     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5454       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5455                                     RegVT));
5456 
5457 
5458     // Add CTR register as callee so a bctr can be emitted later.
5459     if (CFlags.IsTailCall)
5460       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5461   }
5462 
5463   // If this is a tail call add stack pointer delta.
5464   if (CFlags.IsTailCall)
5465     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5466 
5467   // Add argument registers to the end of the list so that they are known live
5468   // into the call.
5469   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5470     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5471                                   RegsToPass[i].second.getValueType()));
5472 
5473   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5474   // no way to mark dependencies as implicit here.
5475   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5476   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5477        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5478     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5479 
5480   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5481   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5482     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5483 
5484   // Add a register mask operand representing the call-preserved registers.
5485   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5486   const uint32_t *Mask =
5487       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5488   assert(Mask && "Missing call preserved mask for calling convention");
5489   Ops.push_back(DAG.getRegisterMask(Mask));
5490 
5491   // If the glue is valid, it is the last operand.
5492   if (Glue.getNode())
5493     Ops.push_back(Glue);
5494 }
5495 
5496 SDValue PPCTargetLowering::FinishCall(
5497     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5498     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5499     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5500     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5501     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5502 
5503   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5504       Subtarget.isAIXABI())
5505     setUsesTOCBasePtr(DAG);
5506 
5507   unsigned CallOpc =
5508       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5509                     Subtarget, DAG.getTarget());
5510 
5511   if (!CFlags.IsIndirect)
5512     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5513   else if (Subtarget.usesFunctionDescriptors())
5514     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5515                                   dl, CFlags.HasNest, Subtarget);
5516   else
5517     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5518 
5519   // Build the operand list for the call instruction.
5520   SmallVector<SDValue, 8> Ops;
5521   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5522                     SPDiff, Subtarget);
5523 
5524   // Emit tail call.
5525   if (CFlags.IsTailCall) {
5526     // Indirect tail call when using PC Relative calls do not have the same
5527     // constraints.
5528     assert(((Callee.getOpcode() == ISD::Register &&
5529              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5530             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5531             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5532             isa<ConstantSDNode>(Callee) ||
5533             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5534            "Expecting a global address, external symbol, absolute value, "
5535            "register or an indirect tail call when PC Relative calls are "
5536            "used.");
5537     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5538     assert(CallOpc == PPCISD::TC_RETURN &&
5539            "Unexpected call opcode for a tail call.");
5540     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5541     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5542   }
5543 
5544   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5545   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5546   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5547   Glue = Chain.getValue(1);
5548 
5549   // When performing tail call optimization the callee pops its arguments off
5550   // the stack. Account for this here so these bytes can be pushed back on in
5551   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5552   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5553                          getTargetMachine().Options.GuaranteedTailCallOpt)
5554                             ? NumBytes
5555                             : 0;
5556 
5557   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5558                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5559                              Glue, dl);
5560   Glue = Chain.getValue(1);
5561 
5562   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5563                          DAG, InVals);
5564 }
5565 
5566 SDValue
5567 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5568                              SmallVectorImpl<SDValue> &InVals) const {
5569   SelectionDAG &DAG                     = CLI.DAG;
5570   SDLoc &dl                             = CLI.DL;
5571   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5572   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5573   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5574   SDValue Chain                         = CLI.Chain;
5575   SDValue Callee                        = CLI.Callee;
5576   bool &isTailCall                      = CLI.IsTailCall;
5577   CallingConv::ID CallConv              = CLI.CallConv;
5578   bool isVarArg                         = CLI.IsVarArg;
5579   bool isPatchPoint                     = CLI.IsPatchPoint;
5580   const CallBase *CB                    = CLI.CB;
5581 
5582   if (isTailCall) {
5583     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5584       isTailCall = false;
5585     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5586       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5587           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5588     else
5589       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5590                                                      Ins, DAG);
5591     if (isTailCall) {
5592       ++NumTailCalls;
5593       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5594         ++NumSiblingCalls;
5595 
5596       // PC Relative calls no longer guarantee that the callee is a Global
5597       // Address Node. The callee could be an indirect tail call in which
5598       // case the SDValue for the callee could be a load (to load the address
5599       // of a function pointer) or it may be a register copy (to move the
5600       // address of the callee from a function parameter into a virtual
5601       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5602       assert((Subtarget.isUsingPCRelativeCalls() ||
5603               isa<GlobalAddressSDNode>(Callee)) &&
5604              "Callee should be an llvm::Function object.");
5605 
5606       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5607                         << "\nTCO callee: ");
5608       LLVM_DEBUG(Callee.dump());
5609     }
5610   }
5611 
5612   if (!isTailCall && CB && CB->isMustTailCall())
5613     report_fatal_error("failed to perform tail call elimination on a call "
5614                        "site marked musttail");
5615 
5616   // When long calls (i.e. indirect calls) are always used, calls are always
5617   // made via function pointer. If we have a function name, first translate it
5618   // into a pointer.
5619   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5620       !isTailCall)
5621     Callee = LowerGlobalAddress(Callee, DAG);
5622 
5623   CallFlags CFlags(
5624       CallConv, isTailCall, isVarArg, isPatchPoint,
5625       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5626       // hasNest
5627       Subtarget.is64BitELFABI() &&
5628           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5629       CLI.NoMerge);
5630 
5631   if (Subtarget.isAIXABI())
5632     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5633                          InVals, CB);
5634 
5635   assert(Subtarget.isSVR4ABI());
5636   if (Subtarget.isPPC64())
5637     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5638                             InVals, CB);
5639   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5640                           InVals, CB);
5641 }
5642 
5643 SDValue PPCTargetLowering::LowerCall_32SVR4(
5644     SDValue Chain, SDValue Callee, CallFlags CFlags,
5645     const SmallVectorImpl<ISD::OutputArg> &Outs,
5646     const SmallVectorImpl<SDValue> &OutVals,
5647     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5648     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5649     const CallBase *CB) const {
5650   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5651   // of the 32-bit SVR4 ABI stack frame layout.
5652 
5653   const CallingConv::ID CallConv = CFlags.CallConv;
5654   const bool IsVarArg = CFlags.IsVarArg;
5655   const bool IsTailCall = CFlags.IsTailCall;
5656 
5657   assert((CallConv == CallingConv::C ||
5658           CallConv == CallingConv::Cold ||
5659           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5660 
5661   const Align PtrAlign(4);
5662 
5663   MachineFunction &MF = DAG.getMachineFunction();
5664 
5665   // Mark this function as potentially containing a function that contains a
5666   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5667   // and restoring the callers stack pointer in this functions epilog. This is
5668   // done because by tail calling the called function might overwrite the value
5669   // in this function's (MF) stack pointer stack slot 0(SP).
5670   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5671       CallConv == CallingConv::Fast)
5672     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5673 
5674   // Count how many bytes are to be pushed on the stack, including the linkage
5675   // area, parameter list area and the part of the local variable space which
5676   // contains copies of aggregates which are passed by value.
5677 
5678   // Assign locations to all of the outgoing arguments.
5679   SmallVector<CCValAssign, 16> ArgLocs;
5680   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5681 
5682   // Reserve space for the linkage area on the stack.
5683   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5684                        PtrAlign);
5685   if (useSoftFloat())
5686     CCInfo.PreAnalyzeCallOperands(Outs);
5687 
5688   if (IsVarArg) {
5689     // Handle fixed and variable vector arguments differently.
5690     // Fixed vector arguments go into registers as long as registers are
5691     // available. Variable vector arguments always go into memory.
5692     unsigned NumArgs = Outs.size();
5693 
5694     for (unsigned i = 0; i != NumArgs; ++i) {
5695       MVT ArgVT = Outs[i].VT;
5696       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5697       bool Result;
5698 
5699       if (Outs[i].IsFixed) {
5700         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5701                                CCInfo);
5702       } else {
5703         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5704                                       ArgFlags, CCInfo);
5705       }
5706 
5707       if (Result) {
5708 #ifndef NDEBUG
5709         errs() << "Call operand #" << i << " has unhandled type "
5710              << EVT(ArgVT).getEVTString() << "\n";
5711 #endif
5712         llvm_unreachable(nullptr);
5713       }
5714     }
5715   } else {
5716     // All arguments are treated the same.
5717     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5718   }
5719   CCInfo.clearWasPPCF128();
5720 
5721   // Assign locations to all of the outgoing aggregate by value arguments.
5722   SmallVector<CCValAssign, 16> ByValArgLocs;
5723   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5724 
5725   // Reserve stack space for the allocations in CCInfo.
5726   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5727 
5728   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5729 
5730   // Size of the linkage area, parameter list area and the part of the local
5731   // space variable where copies of aggregates which are passed by value are
5732   // stored.
5733   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5734 
5735   // Calculate by how many bytes the stack has to be adjusted in case of tail
5736   // call optimization.
5737   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5738 
5739   // Adjust the stack pointer for the new arguments...
5740   // These operations are automatically eliminated by the prolog/epilog pass
5741   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5742   SDValue CallSeqStart = Chain;
5743 
5744   // Load the return address and frame pointer so it can be moved somewhere else
5745   // later.
5746   SDValue LROp, FPOp;
5747   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5748 
5749   // Set up a copy of the stack pointer for use loading and storing any
5750   // arguments that may not fit in the registers available for argument
5751   // passing.
5752   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5753 
5754   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5755   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5756   SmallVector<SDValue, 8> MemOpChains;
5757 
5758   bool seenFloatArg = false;
5759   // Walk the register/memloc assignments, inserting copies/loads.
5760   // i - Tracks the index into the list of registers allocated for the call
5761   // RealArgIdx - Tracks the index into the list of actual function arguments
5762   // j - Tracks the index into the list of byval arguments
5763   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5764        i != e;
5765        ++i, ++RealArgIdx) {
5766     CCValAssign &VA = ArgLocs[i];
5767     SDValue Arg = OutVals[RealArgIdx];
5768     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5769 
5770     if (Flags.isByVal()) {
5771       // Argument is an aggregate which is passed by value, thus we need to
5772       // create a copy of it in the local variable space of the current stack
5773       // frame (which is the stack frame of the caller) and pass the address of
5774       // this copy to the callee.
5775       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5776       CCValAssign &ByValVA = ByValArgLocs[j++];
5777       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5778 
5779       // Memory reserved in the local variable space of the callers stack frame.
5780       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5781 
5782       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5783       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5784                            StackPtr, PtrOff);
5785 
5786       // Create a copy of the argument in the local area of the current
5787       // stack frame.
5788       SDValue MemcpyCall =
5789         CreateCopyOfByValArgument(Arg, PtrOff,
5790                                   CallSeqStart.getNode()->getOperand(0),
5791                                   Flags, DAG, dl);
5792 
5793       // This must go outside the CALLSEQ_START..END.
5794       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5795                                                      SDLoc(MemcpyCall));
5796       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5797                              NewCallSeqStart.getNode());
5798       Chain = CallSeqStart = NewCallSeqStart;
5799 
5800       // Pass the address of the aggregate copy on the stack either in a
5801       // physical register or in the parameter list area of the current stack
5802       // frame to the callee.
5803       Arg = PtrOff;
5804     }
5805 
5806     // When useCRBits() is true, there can be i1 arguments.
5807     // It is because getRegisterType(MVT::i1) => MVT::i1,
5808     // and for other integer types getRegisterType() => MVT::i32.
5809     // Extend i1 and ensure callee will get i32.
5810     if (Arg.getValueType() == MVT::i1)
5811       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5812                         dl, MVT::i32, Arg);
5813 
5814     if (VA.isRegLoc()) {
5815       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5816       // Put argument in a physical register.
5817       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5818         bool IsLE = Subtarget.isLittleEndian();
5819         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5820                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5821         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5822         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5823                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5824         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5825                              SVal.getValue(0)));
5826       } else
5827         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5828     } else {
5829       // Put argument in the parameter list area of the current stack frame.
5830       assert(VA.isMemLoc());
5831       unsigned LocMemOffset = VA.getLocMemOffset();
5832 
5833       if (!IsTailCall) {
5834         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5835         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5836                              StackPtr, PtrOff);
5837 
5838         MemOpChains.push_back(
5839             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5840       } else {
5841         // Calculate and remember argument location.
5842         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5843                                  TailCallArguments);
5844       }
5845     }
5846   }
5847 
5848   if (!MemOpChains.empty())
5849     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5850 
5851   // Build a sequence of copy-to-reg nodes chained together with token chain
5852   // and flag operands which copy the outgoing args into the appropriate regs.
5853   SDValue InFlag;
5854   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5855     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5856                              RegsToPass[i].second, InFlag);
5857     InFlag = Chain.getValue(1);
5858   }
5859 
5860   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5861   // registers.
5862   if (IsVarArg) {
5863     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5864     SDValue Ops[] = { Chain, InFlag };
5865 
5866     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5867                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5868 
5869     InFlag = Chain.getValue(1);
5870   }
5871 
5872   if (IsTailCall)
5873     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5874                     TailCallArguments);
5875 
5876   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5877                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5878 }
5879 
5880 // Copy an argument into memory, being careful to do this outside the
5881 // call sequence for the call to which the argument belongs.
5882 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5883     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5884     SelectionDAG &DAG, const SDLoc &dl) const {
5885   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5886                         CallSeqStart.getNode()->getOperand(0),
5887                         Flags, DAG, dl);
5888   // The MEMCPY must go outside the CALLSEQ_START..END.
5889   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5890   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5891                                                  SDLoc(MemcpyCall));
5892   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5893                          NewCallSeqStart.getNode());
5894   return NewCallSeqStart;
5895 }
5896 
5897 SDValue PPCTargetLowering::LowerCall_64SVR4(
5898     SDValue Chain, SDValue Callee, CallFlags CFlags,
5899     const SmallVectorImpl<ISD::OutputArg> &Outs,
5900     const SmallVectorImpl<SDValue> &OutVals,
5901     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5902     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5903     const CallBase *CB) const {
5904   bool isELFv2ABI = Subtarget.isELFv2ABI();
5905   bool isLittleEndian = Subtarget.isLittleEndian();
5906   unsigned NumOps = Outs.size();
5907   bool IsSibCall = false;
5908   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5909 
5910   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5911   unsigned PtrByteSize = 8;
5912 
5913   MachineFunction &MF = DAG.getMachineFunction();
5914 
5915   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5916     IsSibCall = true;
5917 
5918   // Mark this function as potentially containing a function that contains a
5919   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5920   // and restoring the callers stack pointer in this functions epilog. This is
5921   // done because by tail calling the called function might overwrite the value
5922   // in this function's (MF) stack pointer stack slot 0(SP).
5923   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5924     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5925 
5926   assert(!(IsFastCall && CFlags.IsVarArg) &&
5927          "fastcc not supported on varargs functions");
5928 
5929   // Count how many bytes are to be pushed on the stack, including the linkage
5930   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5931   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5932   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5933   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5934   unsigned NumBytes = LinkageSize;
5935   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5936 
5937   static const MCPhysReg GPR[] = {
5938     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5939     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5940   };
5941   static const MCPhysReg VR[] = {
5942     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5943     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5944   };
5945 
5946   const unsigned NumGPRs = array_lengthof(GPR);
5947   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5948   const unsigned NumVRs  = array_lengthof(VR);
5949 
5950   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5951   // can be passed to the callee in registers.
5952   // For the fast calling convention, there is another check below.
5953   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5954   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5955   if (!HasParameterArea) {
5956     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5957     unsigned AvailableFPRs = NumFPRs;
5958     unsigned AvailableVRs = NumVRs;
5959     unsigned NumBytesTmp = NumBytes;
5960     for (unsigned i = 0; i != NumOps; ++i) {
5961       if (Outs[i].Flags.isNest()) continue;
5962       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5963                                  PtrByteSize, LinkageSize, ParamAreaSize,
5964                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5965         HasParameterArea = true;
5966     }
5967   }
5968 
5969   // When using the fast calling convention, we don't provide backing for
5970   // arguments that will be in registers.
5971   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5972 
5973   // Avoid allocating parameter area for fastcc functions if all the arguments
5974   // can be passed in the registers.
5975   if (IsFastCall)
5976     HasParameterArea = false;
5977 
5978   // Add up all the space actually used.
5979   for (unsigned i = 0; i != NumOps; ++i) {
5980     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5981     EVT ArgVT = Outs[i].VT;
5982     EVT OrigVT = Outs[i].ArgVT;
5983 
5984     if (Flags.isNest())
5985       continue;
5986 
5987     if (IsFastCall) {
5988       if (Flags.isByVal()) {
5989         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5990         if (NumGPRsUsed > NumGPRs)
5991           HasParameterArea = true;
5992       } else {
5993         switch (ArgVT.getSimpleVT().SimpleTy) {
5994         default: llvm_unreachable("Unexpected ValueType for argument!");
5995         case MVT::i1:
5996         case MVT::i32:
5997         case MVT::i64:
5998           if (++NumGPRsUsed <= NumGPRs)
5999             continue;
6000           break;
6001         case MVT::v4i32:
6002         case MVT::v8i16:
6003         case MVT::v16i8:
6004         case MVT::v2f64:
6005         case MVT::v2i64:
6006         case MVT::v1i128:
6007         case MVT::f128:
6008           if (++NumVRsUsed <= NumVRs)
6009             continue;
6010           break;
6011         case MVT::v4f32:
6012           if (++NumVRsUsed <= NumVRs)
6013             continue;
6014           break;
6015         case MVT::f32:
6016         case MVT::f64:
6017           if (++NumFPRsUsed <= NumFPRs)
6018             continue;
6019           break;
6020         }
6021         HasParameterArea = true;
6022       }
6023     }
6024 
6025     /* Respect alignment of argument on the stack.  */
6026     auto Alignement =
6027         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6028     NumBytes = alignTo(NumBytes, Alignement);
6029 
6030     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6031     if (Flags.isInConsecutiveRegsLast())
6032       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6033   }
6034 
6035   unsigned NumBytesActuallyUsed = NumBytes;
6036 
6037   // In the old ELFv1 ABI,
6038   // the prolog code of the callee may store up to 8 GPR argument registers to
6039   // the stack, allowing va_start to index over them in memory if its varargs.
6040   // Because we cannot tell if this is needed on the caller side, we have to
6041   // conservatively assume that it is needed.  As such, make sure we have at
6042   // least enough stack space for the caller to store the 8 GPRs.
6043   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6044   // really requires memory operands, e.g. a vararg function.
6045   if (HasParameterArea)
6046     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6047   else
6048     NumBytes = LinkageSize;
6049 
6050   // Tail call needs the stack to be aligned.
6051   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6052     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6053 
6054   int SPDiff = 0;
6055 
6056   // Calculate by how many bytes the stack has to be adjusted in case of tail
6057   // call optimization.
6058   if (!IsSibCall)
6059     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6060 
6061   // To protect arguments on the stack from being clobbered in a tail call,
6062   // force all the loads to happen before doing any other lowering.
6063   if (CFlags.IsTailCall)
6064     Chain = DAG.getStackArgumentTokenFactor(Chain);
6065 
6066   // Adjust the stack pointer for the new arguments...
6067   // These operations are automatically eliminated by the prolog/epilog pass
6068   if (!IsSibCall)
6069     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6070   SDValue CallSeqStart = Chain;
6071 
6072   // Load the return address and frame pointer so it can be move somewhere else
6073   // later.
6074   SDValue LROp, FPOp;
6075   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6076 
6077   // Set up a copy of the stack pointer for use loading and storing any
6078   // arguments that may not fit in the registers available for argument
6079   // passing.
6080   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6081 
6082   // Figure out which arguments are going to go in registers, and which in
6083   // memory.  Also, if this is a vararg function, floating point operations
6084   // must be stored to our stack, and loaded into integer regs as well, if
6085   // any integer regs are available for argument passing.
6086   unsigned ArgOffset = LinkageSize;
6087 
6088   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6089   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6090 
6091   SmallVector<SDValue, 8> MemOpChains;
6092   for (unsigned i = 0; i != NumOps; ++i) {
6093     SDValue Arg = OutVals[i];
6094     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6095     EVT ArgVT = Outs[i].VT;
6096     EVT OrigVT = Outs[i].ArgVT;
6097 
6098     // PtrOff will be used to store the current argument to the stack if a
6099     // register cannot be found for it.
6100     SDValue PtrOff;
6101 
6102     // We re-align the argument offset for each argument, except when using the
6103     // fast calling convention, when we need to make sure we do that only when
6104     // we'll actually use a stack slot.
6105     auto ComputePtrOff = [&]() {
6106       /* Respect alignment of argument on the stack.  */
6107       auto Alignment =
6108           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6109       ArgOffset = alignTo(ArgOffset, Alignment);
6110 
6111       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6112 
6113       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6114     };
6115 
6116     if (!IsFastCall) {
6117       ComputePtrOff();
6118 
6119       /* Compute GPR index associated with argument offset.  */
6120       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6121       GPR_idx = std::min(GPR_idx, NumGPRs);
6122     }
6123 
6124     // Promote integers to 64-bit values.
6125     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6126       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6127       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6128       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6129     }
6130 
6131     // FIXME memcpy is used way more than necessary.  Correctness first.
6132     // Note: "by value" is code for passing a structure by value, not
6133     // basic types.
6134     if (Flags.isByVal()) {
6135       // Note: Size includes alignment padding, so
6136       //   struct x { short a; char b; }
6137       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6138       // These are the proper values we need for right-justifying the
6139       // aggregate in a parameter register.
6140       unsigned Size = Flags.getByValSize();
6141 
6142       // An empty aggregate parameter takes up no storage and no
6143       // registers.
6144       if (Size == 0)
6145         continue;
6146 
6147       if (IsFastCall)
6148         ComputePtrOff();
6149 
6150       // All aggregates smaller than 8 bytes must be passed right-justified.
6151       if (Size==1 || Size==2 || Size==4) {
6152         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6153         if (GPR_idx != NumGPRs) {
6154           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6155                                         MachinePointerInfo(), VT);
6156           MemOpChains.push_back(Load.getValue(1));
6157           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6158 
6159           ArgOffset += PtrByteSize;
6160           continue;
6161         }
6162       }
6163 
6164       if (GPR_idx == NumGPRs && Size < 8) {
6165         SDValue AddPtr = PtrOff;
6166         if (!isLittleEndian) {
6167           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6168                                           PtrOff.getValueType());
6169           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6170         }
6171         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6172                                                           CallSeqStart,
6173                                                           Flags, DAG, dl);
6174         ArgOffset += PtrByteSize;
6175         continue;
6176       }
6177       // Copy entire object into memory.  There are cases where gcc-generated
6178       // code assumes it is there, even if it could be put entirely into
6179       // registers.  (This is not what the doc says.)
6180 
6181       // FIXME: The above statement is likely due to a misunderstanding of the
6182       // documents.  All arguments must be copied into the parameter area BY
6183       // THE CALLEE in the event that the callee takes the address of any
6184       // formal argument.  That has not yet been implemented.  However, it is
6185       // reasonable to use the stack area as a staging area for the register
6186       // load.
6187 
6188       // Skip this for small aggregates, as we will use the same slot for a
6189       // right-justified copy, below.
6190       if (Size >= 8)
6191         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6192                                                           CallSeqStart,
6193                                                           Flags, DAG, dl);
6194 
6195       // When a register is available, pass a small aggregate right-justified.
6196       if (Size < 8 && GPR_idx != NumGPRs) {
6197         // The easiest way to get this right-justified in a register
6198         // is to copy the structure into the rightmost portion of a
6199         // local variable slot, then load the whole slot into the
6200         // register.
6201         // FIXME: The memcpy seems to produce pretty awful code for
6202         // small aggregates, particularly for packed ones.
6203         // FIXME: It would be preferable to use the slot in the
6204         // parameter save area instead of a new local variable.
6205         SDValue AddPtr = PtrOff;
6206         if (!isLittleEndian) {
6207           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6208           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6209         }
6210         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6211                                                           CallSeqStart,
6212                                                           Flags, DAG, dl);
6213 
6214         // Load the slot into the register.
6215         SDValue Load =
6216             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6217         MemOpChains.push_back(Load.getValue(1));
6218         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6219 
6220         // Done with this argument.
6221         ArgOffset += PtrByteSize;
6222         continue;
6223       }
6224 
6225       // For aggregates larger than PtrByteSize, copy the pieces of the
6226       // object that fit into registers from the parameter save area.
6227       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6228         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6229         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6230         if (GPR_idx != NumGPRs) {
6231           SDValue Load =
6232               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6233           MemOpChains.push_back(Load.getValue(1));
6234           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6235           ArgOffset += PtrByteSize;
6236         } else {
6237           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6238           break;
6239         }
6240       }
6241       continue;
6242     }
6243 
6244     switch (Arg.getSimpleValueType().SimpleTy) {
6245     default: llvm_unreachable("Unexpected ValueType for argument!");
6246     case MVT::i1:
6247     case MVT::i32:
6248     case MVT::i64:
6249       if (Flags.isNest()) {
6250         // The 'nest' parameter, if any, is passed in R11.
6251         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6252         break;
6253       }
6254 
6255       // These can be scalar arguments or elements of an integer array type
6256       // passed directly.  Clang may use those instead of "byval" aggregate
6257       // types to avoid forcing arguments to memory unnecessarily.
6258       if (GPR_idx != NumGPRs) {
6259         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6260       } else {
6261         if (IsFastCall)
6262           ComputePtrOff();
6263 
6264         assert(HasParameterArea &&
6265                "Parameter area must exist to pass an argument in memory.");
6266         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6267                          true, CFlags.IsTailCall, false, MemOpChains,
6268                          TailCallArguments, dl);
6269         if (IsFastCall)
6270           ArgOffset += PtrByteSize;
6271       }
6272       if (!IsFastCall)
6273         ArgOffset += PtrByteSize;
6274       break;
6275     case MVT::f32:
6276     case MVT::f64: {
6277       // These can be scalar arguments or elements of a float array type
6278       // passed directly.  The latter are used to implement ELFv2 homogenous
6279       // float aggregates.
6280 
6281       // Named arguments go into FPRs first, and once they overflow, the
6282       // remaining arguments go into GPRs and then the parameter save area.
6283       // Unnamed arguments for vararg functions always go to GPRs and
6284       // then the parameter save area.  For now, put all arguments to vararg
6285       // routines always in both locations (FPR *and* GPR or stack slot).
6286       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6287       bool NeededLoad = false;
6288 
6289       // First load the argument into the next available FPR.
6290       if (FPR_idx != NumFPRs)
6291         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6292 
6293       // Next, load the argument into GPR or stack slot if needed.
6294       if (!NeedGPROrStack)
6295         ;
6296       else if (GPR_idx != NumGPRs && !IsFastCall) {
6297         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6298         // once we support fp <-> gpr moves.
6299 
6300         // In the non-vararg case, this can only ever happen in the
6301         // presence of f32 array types, since otherwise we never run
6302         // out of FPRs before running out of GPRs.
6303         SDValue ArgVal;
6304 
6305         // Double values are always passed in a single GPR.
6306         if (Arg.getValueType() != MVT::f32) {
6307           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6308 
6309         // Non-array float values are extended and passed in a GPR.
6310         } else if (!Flags.isInConsecutiveRegs()) {
6311           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6312           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6313 
6314         // If we have an array of floats, we collect every odd element
6315         // together with its predecessor into one GPR.
6316         } else if (ArgOffset % PtrByteSize != 0) {
6317           SDValue Lo, Hi;
6318           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6319           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6320           if (!isLittleEndian)
6321             std::swap(Lo, Hi);
6322           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6323 
6324         // The final element, if even, goes into the first half of a GPR.
6325         } else if (Flags.isInConsecutiveRegsLast()) {
6326           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6327           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6328           if (!isLittleEndian)
6329             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6330                                  DAG.getConstant(32, dl, MVT::i32));
6331 
6332         // Non-final even elements are skipped; they will be handled
6333         // together the with subsequent argument on the next go-around.
6334         } else
6335           ArgVal = SDValue();
6336 
6337         if (ArgVal.getNode())
6338           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6339       } else {
6340         if (IsFastCall)
6341           ComputePtrOff();
6342 
6343         // Single-precision floating-point values are mapped to the
6344         // second (rightmost) word of the stack doubleword.
6345         if (Arg.getValueType() == MVT::f32 &&
6346             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6347           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6348           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6349         }
6350 
6351         assert(HasParameterArea &&
6352                "Parameter area must exist to pass an argument in memory.");
6353         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6354                          true, CFlags.IsTailCall, false, MemOpChains,
6355                          TailCallArguments, dl);
6356 
6357         NeededLoad = true;
6358       }
6359       // When passing an array of floats, the array occupies consecutive
6360       // space in the argument area; only round up to the next doubleword
6361       // at the end of the array.  Otherwise, each float takes 8 bytes.
6362       if (!IsFastCall || NeededLoad) {
6363         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6364                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6365         if (Flags.isInConsecutiveRegsLast())
6366           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6367       }
6368       break;
6369     }
6370     case MVT::v4f32:
6371     case MVT::v4i32:
6372     case MVT::v8i16:
6373     case MVT::v16i8:
6374     case MVT::v2f64:
6375     case MVT::v2i64:
6376     case MVT::v1i128:
6377     case MVT::f128:
6378       // These can be scalar arguments or elements of a vector array type
6379       // passed directly.  The latter are used to implement ELFv2 homogenous
6380       // vector aggregates.
6381 
6382       // For a varargs call, named arguments go into VRs or on the stack as
6383       // usual; unnamed arguments always go to the stack or the corresponding
6384       // GPRs when within range.  For now, we always put the value in both
6385       // locations (or even all three).
6386       if (CFlags.IsVarArg) {
6387         assert(HasParameterArea &&
6388                "Parameter area must exist if we have a varargs call.");
6389         // We could elide this store in the case where the object fits
6390         // entirely in R registers.  Maybe later.
6391         SDValue Store =
6392             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6393         MemOpChains.push_back(Store);
6394         if (VR_idx != NumVRs) {
6395           SDValue Load =
6396               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6397           MemOpChains.push_back(Load.getValue(1));
6398           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6399         }
6400         ArgOffset += 16;
6401         for (unsigned i=0; i<16; i+=PtrByteSize) {
6402           if (GPR_idx == NumGPRs)
6403             break;
6404           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6405                                    DAG.getConstant(i, dl, PtrVT));
6406           SDValue Load =
6407               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6408           MemOpChains.push_back(Load.getValue(1));
6409           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6410         }
6411         break;
6412       }
6413 
6414       // Non-varargs Altivec params go into VRs or on the stack.
6415       if (VR_idx != NumVRs) {
6416         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6417       } else {
6418         if (IsFastCall)
6419           ComputePtrOff();
6420 
6421         assert(HasParameterArea &&
6422                "Parameter area must exist to pass an argument in memory.");
6423         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6424                          true, CFlags.IsTailCall, true, MemOpChains,
6425                          TailCallArguments, dl);
6426         if (IsFastCall)
6427           ArgOffset += 16;
6428       }
6429 
6430       if (!IsFastCall)
6431         ArgOffset += 16;
6432       break;
6433     }
6434   }
6435 
6436   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6437          "mismatch in size of parameter area");
6438   (void)NumBytesActuallyUsed;
6439 
6440   if (!MemOpChains.empty())
6441     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6442 
6443   // Check if this is an indirect call (MTCTR/BCTRL).
6444   // See prepareDescriptorIndirectCall and buildCallOperands for more
6445   // information about calls through function pointers in the 64-bit SVR4 ABI.
6446   if (CFlags.IsIndirect) {
6447     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6448     // caller in the TOC save area.
6449     if (isTOCSaveRestoreRequired(Subtarget)) {
6450       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6451       // Load r2 into a virtual register and store it to the TOC save area.
6452       setUsesTOCBasePtr(DAG);
6453       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6454       // TOC save area offset.
6455       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6456       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6457       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6458       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6459                            MachinePointerInfo::getStack(
6460                                DAG.getMachineFunction(), TOCSaveOffset));
6461     }
6462     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6463     // This does not mean the MTCTR instruction must use R12; it's easier
6464     // to model this as an extra parameter, so do that.
6465     if (isELFv2ABI && !CFlags.IsPatchPoint)
6466       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6467   }
6468 
6469   // Build a sequence of copy-to-reg nodes chained together with token chain
6470   // and flag operands which copy the outgoing args into the appropriate regs.
6471   SDValue InFlag;
6472   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6473     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6474                              RegsToPass[i].second, InFlag);
6475     InFlag = Chain.getValue(1);
6476   }
6477 
6478   if (CFlags.IsTailCall && !IsSibCall)
6479     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6480                     TailCallArguments);
6481 
6482   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6483                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6484 }
6485 
6486 // Returns true when the shadow of a general purpose argument register
6487 // in the parameter save area is aligned to at least 'RequiredAlign'.
6488 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6489   assert(RequiredAlign.value() <= 16 &&
6490          "Required alignment greater than stack alignment.");
6491   switch (Reg) {
6492   default:
6493     report_fatal_error("called on invalid register.");
6494   case PPC::R5:
6495   case PPC::R9:
6496   case PPC::X3:
6497   case PPC::X5:
6498   case PPC::X7:
6499   case PPC::X9:
6500     // These registers are 16 byte aligned which is the most strict aligment
6501     // we can support.
6502     return true;
6503   case PPC::R3:
6504   case PPC::R7:
6505   case PPC::X4:
6506   case PPC::X6:
6507   case PPC::X8:
6508   case PPC::X10:
6509     // The shadow of these registers in the PSA is 8 byte aligned.
6510     return RequiredAlign <= 8;
6511   case PPC::R4:
6512   case PPC::R6:
6513   case PPC::R8:
6514   case PPC::R10:
6515     return RequiredAlign <= 4;
6516   }
6517 }
6518 
6519 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6520                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6521                    CCState &S) {
6522   AIXCCState &State = static_cast<AIXCCState &>(S);
6523   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6524       State.getMachineFunction().getSubtarget());
6525   const bool IsPPC64 = Subtarget.isPPC64();
6526   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6527   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6528 
6529   if (ValVT == MVT::f128)
6530     report_fatal_error("f128 is unimplemented on AIX.");
6531 
6532   if (ArgFlags.isNest())
6533     report_fatal_error("Nest arguments are unimplemented.");
6534 
6535   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6536                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6537                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6538   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6539                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6540                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6541 
6542   static const MCPhysReg VR[] = {// Vector registers.
6543                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6544                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6545                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6546 
6547   if (ArgFlags.isByVal()) {
6548     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6549       report_fatal_error("Pass-by-value arguments with alignment greater than "
6550                          "register width are not supported.");
6551 
6552     const unsigned ByValSize = ArgFlags.getByValSize();
6553 
6554     // An empty aggregate parameter takes up no storage and no registers,
6555     // but needs a MemLoc for a stack slot for the formal arguments side.
6556     if (ByValSize == 0) {
6557       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6558                                        State.getNextStackOffset(), RegVT,
6559                                        LocInfo));
6560       return false;
6561     }
6562 
6563     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6564     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6565     for (const unsigned E = Offset + StackSize; Offset < E;
6566          Offset += PtrAlign.value()) {
6567       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6568         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6569       else {
6570         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6571                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6572                                          LocInfo));
6573         break;
6574       }
6575     }
6576     return false;
6577   }
6578 
6579   // Arguments always reserve parameter save area.
6580   switch (ValVT.SimpleTy) {
6581   default:
6582     report_fatal_error("Unhandled value type for argument.");
6583   case MVT::i64:
6584     // i64 arguments should have been split to i32 for PPC32.
6585     assert(IsPPC64 && "PPC32 should have split i64 values.");
6586     LLVM_FALLTHROUGH;
6587   case MVT::i1:
6588   case MVT::i32: {
6589     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6590     // AIX integer arguments are always passed in register width.
6591     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6592       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6593                                   : CCValAssign::LocInfo::ZExt;
6594     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6595       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6596     else
6597       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6598 
6599     return false;
6600   }
6601   case MVT::f32:
6602   case MVT::f64: {
6603     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6604     const unsigned StoreSize = LocVT.getStoreSize();
6605     // Floats are always 4-byte aligned in the PSA on AIX.
6606     // This includes f64 in 64-bit mode for ABI compatibility.
6607     const unsigned Offset =
6608         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6609     unsigned FReg = State.AllocateReg(FPR);
6610     if (FReg)
6611       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6612 
6613     // Reserve and initialize GPRs or initialize the PSA as required.
6614     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6615       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6616         assert(FReg && "An FPR should be available when a GPR is reserved.");
6617         if (State.isVarArg()) {
6618           // Successfully reserved GPRs are only initialized for vararg calls.
6619           // Custom handling is required for:
6620           //   f64 in PPC32 needs to be split into 2 GPRs.
6621           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6622           State.addLoc(
6623               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6624         }
6625       } else {
6626         // If there are insufficient GPRs, the PSA needs to be initialized.
6627         // Initialization occurs even if an FPR was initialized for
6628         // compatibility with the AIX XL compiler. The full memory for the
6629         // argument will be initialized even if a prior word is saved in GPR.
6630         // A custom memLoc is used when the argument also passes in FPR so
6631         // that the callee handling can skip over it easily.
6632         State.addLoc(
6633             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6634                                              LocInfo)
6635                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6636         break;
6637       }
6638     }
6639 
6640     return false;
6641   }
6642   case MVT::v4f32:
6643   case MVT::v4i32:
6644   case MVT::v8i16:
6645   case MVT::v16i8:
6646   case MVT::v2i64:
6647   case MVT::v2f64:
6648   case MVT::v1i128: {
6649     const unsigned VecSize = 16;
6650     const Align VecAlign(VecSize);
6651 
6652     if (!State.isVarArg()) {
6653       // If there are vector registers remaining we don't consume any stack
6654       // space.
6655       if (unsigned VReg = State.AllocateReg(VR)) {
6656         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6657         return false;
6658       }
6659       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6660       // might be allocated in the portion of the PSA that is shadowed by the
6661       // GPRs.
6662       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6663       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6664       return false;
6665     }
6666 
6667     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6668     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6669 
6670     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6671     // Burn any underaligned registers and their shadowed stack space until
6672     // we reach the required alignment.
6673     while (NextRegIndex != GPRs.size() &&
6674            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6675       // Shadow allocate register and its stack shadow.
6676       unsigned Reg = State.AllocateReg(GPRs);
6677       State.AllocateStack(PtrSize, PtrAlign);
6678       assert(Reg && "Allocating register unexpectedly failed.");
6679       (void)Reg;
6680       NextRegIndex = State.getFirstUnallocated(GPRs);
6681     }
6682 
6683     // Vectors that are passed as fixed arguments are handled differently.
6684     // They are passed in VRs if any are available (unlike arguments passed
6685     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6686     // functions)
6687     if (State.isFixed(ValNo)) {
6688       if (unsigned VReg = State.AllocateReg(VR)) {
6689         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6690         // Shadow allocate GPRs and stack space even though we pass in a VR.
6691         for (unsigned I = 0; I != VecSize; I += PtrSize)
6692           State.AllocateReg(GPRs);
6693         State.AllocateStack(VecSize, VecAlign);
6694         return false;
6695       }
6696       // No vector registers remain so pass on the stack.
6697       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6698       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6699       return false;
6700     }
6701 
6702     // If all GPRS are consumed then we pass the argument fully on the stack.
6703     if (NextRegIndex == GPRs.size()) {
6704       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6705       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6706       return false;
6707     }
6708 
6709     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6710     // half of the argument, and then need to pass the remaining half on the
6711     // stack.
6712     if (GPRs[NextRegIndex] == PPC::R9) {
6713       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6714       State.addLoc(
6715           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6716 
6717       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6718       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6719       assert(FirstReg && SecondReg &&
6720              "Allocating R9 or R10 unexpectedly failed.");
6721       State.addLoc(
6722           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6723       State.addLoc(
6724           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6725       return false;
6726     }
6727 
6728     // We have enough GPRs to fully pass the vector argument, and we have
6729     // already consumed any underaligned registers. Start with the custom
6730     // MemLoc and then the custom RegLocs.
6731     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6732     State.addLoc(
6733         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6734     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6735       const unsigned Reg = State.AllocateReg(GPRs);
6736       assert(Reg && "Failed to allocated register for vararg vector argument");
6737       State.addLoc(
6738           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6739     }
6740     return false;
6741   }
6742   }
6743   return true;
6744 }
6745 
6746 // So far, this function is only used by LowerFormalArguments_AIX()
6747 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6748                                                     bool IsPPC64,
6749                                                     bool HasP8Vector,
6750                                                     bool HasVSX) {
6751   assert((IsPPC64 || SVT != MVT::i64) &&
6752          "i64 should have been split for 32-bit codegen.");
6753 
6754   switch (SVT) {
6755   default:
6756     report_fatal_error("Unexpected value type for formal argument");
6757   case MVT::i1:
6758   case MVT::i32:
6759   case MVT::i64:
6760     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6761   case MVT::f32:
6762     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6763   case MVT::f64:
6764     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6765   case MVT::v4f32:
6766   case MVT::v4i32:
6767   case MVT::v8i16:
6768   case MVT::v16i8:
6769   case MVT::v2i64:
6770   case MVT::v2f64:
6771   case MVT::v1i128:
6772     return &PPC::VRRCRegClass;
6773   }
6774 }
6775 
6776 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6777                                         SelectionDAG &DAG, SDValue ArgValue,
6778                                         MVT LocVT, const SDLoc &dl) {
6779   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6780   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6781 
6782   if (Flags.isSExt())
6783     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6784                            DAG.getValueType(ValVT));
6785   else if (Flags.isZExt())
6786     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6787                            DAG.getValueType(ValVT));
6788 
6789   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6790 }
6791 
6792 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6793   const unsigned LASize = FL->getLinkageSize();
6794 
6795   if (PPC::GPRCRegClass.contains(Reg)) {
6796     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6797            "Reg must be a valid argument register!");
6798     return LASize + 4 * (Reg - PPC::R3);
6799   }
6800 
6801   if (PPC::G8RCRegClass.contains(Reg)) {
6802     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6803            "Reg must be a valid argument register!");
6804     return LASize + 8 * (Reg - PPC::X3);
6805   }
6806 
6807   llvm_unreachable("Only general purpose registers expected.");
6808 }
6809 
6810 //   AIX ABI Stack Frame Layout:
6811 //
6812 //   Low Memory +--------------------------------------------+
6813 //   SP   +---> | Back chain                                 | ---+
6814 //        |     +--------------------------------------------+    |
6815 //        |     | Saved Condition Register                   |    |
6816 //        |     +--------------------------------------------+    |
6817 //        |     | Saved Linkage Register                     |    |
6818 //        |     +--------------------------------------------+    | Linkage Area
6819 //        |     | Reserved for compilers                     |    |
6820 //        |     +--------------------------------------------+    |
6821 //        |     | Reserved for binders                       |    |
6822 //        |     +--------------------------------------------+    |
6823 //        |     | Saved TOC pointer                          | ---+
6824 //        |     +--------------------------------------------+
6825 //        |     | Parameter save area                        |
6826 //        |     +--------------------------------------------+
6827 //        |     | Alloca space                               |
6828 //        |     +--------------------------------------------+
6829 //        |     | Local variable space                       |
6830 //        |     +--------------------------------------------+
6831 //        |     | Float/int conversion temporary             |
6832 //        |     +--------------------------------------------+
6833 //        |     | Save area for AltiVec registers            |
6834 //        |     +--------------------------------------------+
6835 //        |     | AltiVec alignment padding                  |
6836 //        |     +--------------------------------------------+
6837 //        |     | Save area for VRSAVE register              |
6838 //        |     +--------------------------------------------+
6839 //        |     | Save area for General Purpose registers    |
6840 //        |     +--------------------------------------------+
6841 //        |     | Save area for Floating Point registers     |
6842 //        |     +--------------------------------------------+
6843 //        +---- | Back chain                                 |
6844 // High Memory  +--------------------------------------------+
6845 //
6846 //  Specifications:
6847 //  AIX 7.2 Assembler Language Reference
6848 //  Subroutine linkage convention
6849 
6850 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6851     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6852     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6853     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6854 
6855   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6856           CallConv == CallingConv::Fast) &&
6857          "Unexpected calling convention!");
6858 
6859   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6860     report_fatal_error("Tail call support is unimplemented on AIX.");
6861 
6862   if (useSoftFloat())
6863     report_fatal_error("Soft float support is unimplemented on AIX.");
6864 
6865   const PPCSubtarget &Subtarget =
6866       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6867 
6868   const bool IsPPC64 = Subtarget.isPPC64();
6869   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6870 
6871   // Assign locations to all of the incoming arguments.
6872   SmallVector<CCValAssign, 16> ArgLocs;
6873   MachineFunction &MF = DAG.getMachineFunction();
6874   MachineFrameInfo &MFI = MF.getFrameInfo();
6875   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6876   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6877 
6878   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6879   // Reserve space for the linkage area on the stack.
6880   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6881   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6882   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6883 
6884   SmallVector<SDValue, 8> MemOps;
6885 
6886   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6887     CCValAssign &VA = ArgLocs[I++];
6888     MVT LocVT = VA.getLocVT();
6889     MVT ValVT = VA.getValVT();
6890     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6891     // For compatibility with the AIX XL compiler, the float args in the
6892     // parameter save area are initialized even if the argument is available
6893     // in register.  The caller is required to initialize both the register
6894     // and memory, however, the callee can choose to expect it in either.
6895     // The memloc is dismissed here because the argument is retrieved from
6896     // the register.
6897     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6898       continue;
6899 
6900     auto HandleMemLoc = [&]() {
6901       const unsigned LocSize = LocVT.getStoreSize();
6902       const unsigned ValSize = ValVT.getStoreSize();
6903       assert((ValSize <= LocSize) &&
6904              "Object size is larger than size of MemLoc");
6905       int CurArgOffset = VA.getLocMemOffset();
6906       // Objects are right-justified because AIX is big-endian.
6907       if (LocSize > ValSize)
6908         CurArgOffset += LocSize - ValSize;
6909       // Potential tail calls could cause overwriting of argument stack slots.
6910       const bool IsImmutable =
6911           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6912             (CallConv == CallingConv::Fast));
6913       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6914       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6915       SDValue ArgValue =
6916           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6917       InVals.push_back(ArgValue);
6918     };
6919 
6920     // Vector arguments to VaArg functions are passed both on the stack, and
6921     // in any available GPRs. Load the value from the stack and add the GPRs
6922     // as live ins.
6923     if (VA.isMemLoc() && VA.needsCustom()) {
6924       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6925       assert(isVarArg && "Only use custom memloc for vararg.");
6926       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6927       // matching custom RegLocs.
6928       const unsigned OriginalValNo = VA.getValNo();
6929       (void)OriginalValNo;
6930 
6931       auto HandleCustomVecRegLoc = [&]() {
6932         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6933                "Missing custom RegLoc.");
6934         VA = ArgLocs[I++];
6935         assert(VA.getValVT().isVector() &&
6936                "Unexpected Val type for custom RegLoc.");
6937         assert(VA.getValNo() == OriginalValNo &&
6938                "ValNo mismatch between custom MemLoc and RegLoc.");
6939         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6940         MF.addLiveIn(VA.getLocReg(),
6941                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6942                                        Subtarget.hasVSX()));
6943       };
6944 
6945       HandleMemLoc();
6946       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6947       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6948       // R10.
6949       HandleCustomVecRegLoc();
6950       HandleCustomVecRegLoc();
6951 
6952       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
6953       // we passed the vector in R5, R6, R7 and R8.
6954       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
6955         assert(!IsPPC64 &&
6956                "Only 2 custom RegLocs expected for 64-bit codegen.");
6957         HandleCustomVecRegLoc();
6958         HandleCustomVecRegLoc();
6959       }
6960 
6961       continue;
6962     }
6963 
6964     if (VA.isRegLoc()) {
6965       if (VA.getValVT().isScalarInteger())
6966         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6967       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
6968         switch (VA.getValVT().SimpleTy) {
6969         default:
6970           report_fatal_error("Unhandled value type for argument.");
6971         case MVT::f32:
6972           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
6973           break;
6974         case MVT::f64:
6975           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
6976           break;
6977         }
6978       } else if (VA.getValVT().isVector()) {
6979         switch (VA.getValVT().SimpleTy) {
6980         default:
6981           report_fatal_error("Unhandled value type for argument.");
6982         case MVT::v16i8:
6983           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
6984           break;
6985         case MVT::v8i16:
6986           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
6987           break;
6988         case MVT::v4i32:
6989         case MVT::v2i64:
6990         case MVT::v1i128:
6991           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
6992           break;
6993         case MVT::v4f32:
6994         case MVT::v2f64:
6995           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
6996           break;
6997         }
6998       }
6999     }
7000 
7001     if (Flags.isByVal() && VA.isMemLoc()) {
7002       const unsigned Size =
7003           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7004                   PtrByteSize);
7005       const int FI = MF.getFrameInfo().CreateFixedObject(
7006           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7007           /* IsAliased */ true);
7008       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7009       InVals.push_back(FIN);
7010 
7011       continue;
7012     }
7013 
7014     if (Flags.isByVal()) {
7015       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7016 
7017       const MCPhysReg ArgReg = VA.getLocReg();
7018       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7019 
7020       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7021         report_fatal_error("Over aligned byvals not supported yet.");
7022 
7023       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7024       const int FI = MF.getFrameInfo().CreateFixedObject(
7025           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7026           /* IsAliased */ true);
7027       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7028       InVals.push_back(FIN);
7029 
7030       // Add live ins for all the RegLocs for the same ByVal.
7031       const TargetRegisterClass *RegClass =
7032           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7033 
7034       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7035                                                unsigned Offset) {
7036         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7037         // Since the callers side has left justified the aggregate in the
7038         // register, we can simply store the entire register into the stack
7039         // slot.
7040         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7041         // The store to the fixedstack object is needed becuase accessing a
7042         // field of the ByVal will use a gep and load. Ideally we will optimize
7043         // to extracting the value from the register directly, and elide the
7044         // stores when the arguments address is not taken, but that will need to
7045         // be future work.
7046         SDValue Store = DAG.getStore(
7047             CopyFrom.getValue(1), dl, CopyFrom,
7048             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7049             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7050 
7051         MemOps.push_back(Store);
7052       };
7053 
7054       unsigned Offset = 0;
7055       HandleRegLoc(VA.getLocReg(), Offset);
7056       Offset += PtrByteSize;
7057       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7058            Offset += PtrByteSize) {
7059         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7060                "RegLocs should be for ByVal argument.");
7061 
7062         const CCValAssign RL = ArgLocs[I++];
7063         HandleRegLoc(RL.getLocReg(), Offset);
7064         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7065       }
7066 
7067       if (Offset != StackSize) {
7068         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7069                "Expected MemLoc for remaining bytes.");
7070         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7071         // Consume the MemLoc.The InVal has already been emitted, so nothing
7072         // more needs to be done.
7073         ++I;
7074       }
7075 
7076       continue;
7077     }
7078 
7079     if (VA.isRegLoc() && !VA.needsCustom()) {
7080       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7081       Register VReg =
7082           MF.addLiveIn(VA.getLocReg(),
7083                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7084                                          Subtarget.hasVSX()));
7085       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7086       if (ValVT.isScalarInteger() &&
7087           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7088         ArgValue =
7089             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7090       }
7091       InVals.push_back(ArgValue);
7092       continue;
7093     }
7094     if (VA.isMemLoc()) {
7095       HandleMemLoc();
7096       continue;
7097     }
7098   }
7099 
7100   // On AIX a minimum of 8 words is saved to the parameter save area.
7101   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7102   // Area that is at least reserved in the caller of this function.
7103   unsigned CallerReservedArea =
7104       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7105 
7106   // Set the size that is at least reserved in caller of this function. Tail
7107   // call optimized function's reserved stack space needs to be aligned so
7108   // that taking the difference between two stack areas will result in an
7109   // aligned stack.
7110   CallerReservedArea =
7111       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7112   FuncInfo->setMinReservedArea(CallerReservedArea);
7113 
7114   if (isVarArg) {
7115     FuncInfo->setVarArgsFrameIndex(
7116         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7117     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7118 
7119     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7120                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7121 
7122     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7123                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7124     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7125 
7126     // The fixed integer arguments of a variadic function are stored to the
7127     // VarArgsFrameIndex on the stack so that they may be loaded by
7128     // dereferencing the result of va_next.
7129     for (unsigned GPRIndex =
7130              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7131          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7132 
7133       const unsigned VReg =
7134           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7135                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7136 
7137       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7138       SDValue Store =
7139           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7140       MemOps.push_back(Store);
7141       // Increment the address for the next argument to store.
7142       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7143       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7144     }
7145   }
7146 
7147   if (!MemOps.empty())
7148     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7149 
7150   return Chain;
7151 }
7152 
7153 SDValue PPCTargetLowering::LowerCall_AIX(
7154     SDValue Chain, SDValue Callee, CallFlags CFlags,
7155     const SmallVectorImpl<ISD::OutputArg> &Outs,
7156     const SmallVectorImpl<SDValue> &OutVals,
7157     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7158     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7159     const CallBase *CB) const {
7160   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7161   // AIX ABI stack frame layout.
7162 
7163   assert((CFlags.CallConv == CallingConv::C ||
7164           CFlags.CallConv == CallingConv::Cold ||
7165           CFlags.CallConv == CallingConv::Fast) &&
7166          "Unexpected calling convention!");
7167 
7168   if (CFlags.IsPatchPoint)
7169     report_fatal_error("This call type is unimplemented on AIX.");
7170 
7171   const PPCSubtarget& Subtarget =
7172       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7173 
7174   MachineFunction &MF = DAG.getMachineFunction();
7175   SmallVector<CCValAssign, 16> ArgLocs;
7176   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7177                     *DAG.getContext());
7178 
7179   // Reserve space for the linkage save area (LSA) on the stack.
7180   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7181   //   [SP][CR][LR][2 x reserved][TOC].
7182   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7183   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7184   const bool IsPPC64 = Subtarget.isPPC64();
7185   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7186   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7187   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7188   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7189 
7190   // The prolog code of the callee may store up to 8 GPR argument registers to
7191   // the stack, allowing va_start to index over them in memory if the callee
7192   // is variadic.
7193   // Because we cannot tell if this is needed on the caller side, we have to
7194   // conservatively assume that it is needed.  As such, make sure we have at
7195   // least enough stack space for the caller to store the 8 GPRs.
7196   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7197   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7198                                      CCInfo.getNextStackOffset());
7199 
7200   // Adjust the stack pointer for the new arguments...
7201   // These operations are automatically eliminated by the prolog/epilog pass.
7202   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7203   SDValue CallSeqStart = Chain;
7204 
7205   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7206   SmallVector<SDValue, 8> MemOpChains;
7207 
7208   // Set up a copy of the stack pointer for loading and storing any
7209   // arguments that may not fit in the registers available for argument
7210   // passing.
7211   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7212                                    : DAG.getRegister(PPC::R1, MVT::i32);
7213 
7214   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7215     const unsigned ValNo = ArgLocs[I].getValNo();
7216     SDValue Arg = OutVals[ValNo];
7217     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7218 
7219     if (Flags.isByVal()) {
7220       const unsigned ByValSize = Flags.getByValSize();
7221 
7222       // Nothing to do for zero-sized ByVals on the caller side.
7223       if (!ByValSize) {
7224         ++I;
7225         continue;
7226       }
7227 
7228       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7229         return DAG.getExtLoad(
7230             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7231             (LoadOffset != 0)
7232                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7233                 : Arg,
7234             MachinePointerInfo(), VT);
7235       };
7236 
7237       unsigned LoadOffset = 0;
7238 
7239       // Initialize registers, which are fully occupied by the by-val argument.
7240       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7241         SDValue Load = GetLoad(PtrVT, LoadOffset);
7242         MemOpChains.push_back(Load.getValue(1));
7243         LoadOffset += PtrByteSize;
7244         const CCValAssign &ByValVA = ArgLocs[I++];
7245         assert(ByValVA.getValNo() == ValNo &&
7246                "Unexpected location for pass-by-value argument.");
7247         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7248       }
7249 
7250       if (LoadOffset == ByValSize)
7251         continue;
7252 
7253       // There must be one more loc to handle the remainder.
7254       assert(ArgLocs[I].getValNo() == ValNo &&
7255              "Expected additional location for by-value argument.");
7256 
7257       if (ArgLocs[I].isMemLoc()) {
7258         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7259         const CCValAssign &ByValVA = ArgLocs[I++];
7260         ISD::ArgFlagsTy MemcpyFlags = Flags;
7261         // Only memcpy the bytes that don't pass in register.
7262         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7263         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7264             (LoadOffset != 0)
7265                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7266                 : Arg,
7267             DAG.getObjectPtrOffset(dl, StackPtr,
7268                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7269             CallSeqStart, MemcpyFlags, DAG, dl);
7270         continue;
7271       }
7272 
7273       // Initialize the final register residue.
7274       // Any residue that occupies the final by-val arg register must be
7275       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7276       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7277       // 2 and 1 byte loads.
7278       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7279       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7280              "Unexpected register residue for by-value argument.");
7281       SDValue ResidueVal;
7282       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7283         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7284         const MVT VT =
7285             N == 1 ? MVT::i8
7286                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7287         SDValue Load = GetLoad(VT, LoadOffset);
7288         MemOpChains.push_back(Load.getValue(1));
7289         LoadOffset += N;
7290         Bytes += N;
7291 
7292         // By-val arguments are passed left-justfied in register.
7293         // Every load here needs to be shifted, otherwise a full register load
7294         // should have been used.
7295         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7296                "Unexpected load emitted during handling of pass-by-value "
7297                "argument.");
7298         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7299         EVT ShiftAmountTy =
7300             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7301         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7302         SDValue ShiftedLoad =
7303             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7304         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7305                                               ShiftedLoad)
7306                                 : ShiftedLoad;
7307       }
7308 
7309       const CCValAssign &ByValVA = ArgLocs[I++];
7310       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7311       continue;
7312     }
7313 
7314     CCValAssign &VA = ArgLocs[I++];
7315     const MVT LocVT = VA.getLocVT();
7316     const MVT ValVT = VA.getValVT();
7317 
7318     switch (VA.getLocInfo()) {
7319     default:
7320       report_fatal_error("Unexpected argument extension type.");
7321     case CCValAssign::Full:
7322       break;
7323     case CCValAssign::ZExt:
7324       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7325       break;
7326     case CCValAssign::SExt:
7327       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7328       break;
7329     }
7330 
7331     if (VA.isRegLoc() && !VA.needsCustom()) {
7332       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7333       continue;
7334     }
7335 
7336     // Vector arguments passed to VarArg functions need custom handling when
7337     // they are passed (at least partially) in GPRs.
7338     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7339       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7340       // Store value to its stack slot.
7341       SDValue PtrOff =
7342           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7343       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7344       SDValue Store =
7345           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7346       MemOpChains.push_back(Store);
7347       const unsigned OriginalValNo = VA.getValNo();
7348       // Then load the GPRs from the stack
7349       unsigned LoadOffset = 0;
7350       auto HandleCustomVecRegLoc = [&]() {
7351         assert(I != E && "Unexpected end of CCvalAssigns.");
7352         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7353                "Expected custom RegLoc.");
7354         CCValAssign RegVA = ArgLocs[I++];
7355         assert(RegVA.getValNo() == OriginalValNo &&
7356                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7357         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7358                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7359         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7360         MemOpChains.push_back(Load.getValue(1));
7361         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7362         LoadOffset += PtrByteSize;
7363       };
7364 
7365       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7366       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7367       // R10.
7368       HandleCustomVecRegLoc();
7369       HandleCustomVecRegLoc();
7370 
7371       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7372           ArgLocs[I].getValNo() == OriginalValNo) {
7373         assert(!IsPPC64 &&
7374                "Only 2 custom RegLocs expected for 64-bit codegen.");
7375         HandleCustomVecRegLoc();
7376         HandleCustomVecRegLoc();
7377       }
7378 
7379       continue;
7380     }
7381 
7382     if (VA.isMemLoc()) {
7383       SDValue PtrOff =
7384           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7385       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7386       MemOpChains.push_back(
7387           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7388 
7389       continue;
7390     }
7391 
7392     if (!ValVT.isFloatingPoint())
7393       report_fatal_error(
7394           "Unexpected register handling for calling convention.");
7395 
7396     // Custom handling is used for GPR initializations for vararg float
7397     // arguments.
7398     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7399            LocVT.isInteger() &&
7400            "Custom register handling only expected for VarArg.");
7401 
7402     SDValue ArgAsInt =
7403         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7404 
7405     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7406       // f32 in 32-bit GPR
7407       // f64 in 64-bit GPR
7408       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7409     else if (Arg.getValueType().getFixedSizeInBits() <
7410              LocVT.getFixedSizeInBits())
7411       // f32 in 64-bit GPR.
7412       RegsToPass.push_back(std::make_pair(
7413           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7414     else {
7415       // f64 in two 32-bit GPRs
7416       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7417       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7418              "Unexpected custom register for argument!");
7419       CCValAssign &GPR1 = VA;
7420       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7421                                      DAG.getConstant(32, dl, MVT::i8));
7422       RegsToPass.push_back(std::make_pair(
7423           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7424 
7425       if (I != E) {
7426         // If only 1 GPR was available, there will only be one custom GPR and
7427         // the argument will also pass in memory.
7428         CCValAssign &PeekArg = ArgLocs[I];
7429         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7430           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7431           CCValAssign &GPR2 = ArgLocs[I++];
7432           RegsToPass.push_back(std::make_pair(
7433               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7434         }
7435       }
7436     }
7437   }
7438 
7439   if (!MemOpChains.empty())
7440     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7441 
7442   // For indirect calls, we need to save the TOC base to the stack for
7443   // restoration after the call.
7444   if (CFlags.IsIndirect) {
7445     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7446     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7447     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7448     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7449     const unsigned TOCSaveOffset =
7450         Subtarget.getFrameLowering()->getTOCSaveOffset();
7451 
7452     setUsesTOCBasePtr(DAG);
7453     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7454     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7455     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7456     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7457     Chain = DAG.getStore(
7458         Val.getValue(1), dl, Val, AddPtr,
7459         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7460   }
7461 
7462   // Build a sequence of copy-to-reg nodes chained together with token chain
7463   // and flag operands which copy the outgoing args into the appropriate regs.
7464   SDValue InFlag;
7465   for (auto Reg : RegsToPass) {
7466     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7467     InFlag = Chain.getValue(1);
7468   }
7469 
7470   const int SPDiff = 0;
7471   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7472                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7473 }
7474 
7475 bool
7476 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7477                                   MachineFunction &MF, bool isVarArg,
7478                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7479                                   LLVMContext &Context) const {
7480   SmallVector<CCValAssign, 16> RVLocs;
7481   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7482   return CCInfo.CheckReturn(
7483       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7484                 ? RetCC_PPC_Cold
7485                 : RetCC_PPC);
7486 }
7487 
7488 SDValue
7489 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7490                                bool isVarArg,
7491                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7492                                const SmallVectorImpl<SDValue> &OutVals,
7493                                const SDLoc &dl, SelectionDAG &DAG) const {
7494   SmallVector<CCValAssign, 16> RVLocs;
7495   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7496                  *DAG.getContext());
7497   CCInfo.AnalyzeReturn(Outs,
7498                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7499                            ? RetCC_PPC_Cold
7500                            : RetCC_PPC);
7501 
7502   SDValue Flag;
7503   SmallVector<SDValue, 4> RetOps(1, Chain);
7504 
7505   // Copy the result values into the output registers.
7506   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7507     CCValAssign &VA = RVLocs[i];
7508     assert(VA.isRegLoc() && "Can only return in registers!");
7509 
7510     SDValue Arg = OutVals[RealResIdx];
7511 
7512     switch (VA.getLocInfo()) {
7513     default: llvm_unreachable("Unknown loc info!");
7514     case CCValAssign::Full: break;
7515     case CCValAssign::AExt:
7516       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7517       break;
7518     case CCValAssign::ZExt:
7519       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7520       break;
7521     case CCValAssign::SExt:
7522       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7523       break;
7524     }
7525     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7526       bool isLittleEndian = Subtarget.isLittleEndian();
7527       // Legalize ret f64 -> ret 2 x i32.
7528       SDValue SVal =
7529           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7530                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7531       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7532       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7533       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7534                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7535       Flag = Chain.getValue(1);
7536       VA = RVLocs[++i]; // skip ahead to next loc
7537       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7538     } else
7539       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7540     Flag = Chain.getValue(1);
7541     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7542   }
7543 
7544   RetOps[0] = Chain;  // Update chain.
7545 
7546   // Add the flag if we have it.
7547   if (Flag.getNode())
7548     RetOps.push_back(Flag);
7549 
7550   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7551 }
7552 
7553 SDValue
7554 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7555                                                 SelectionDAG &DAG) const {
7556   SDLoc dl(Op);
7557 
7558   // Get the correct type for integers.
7559   EVT IntVT = Op.getValueType();
7560 
7561   // Get the inputs.
7562   SDValue Chain = Op.getOperand(0);
7563   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7564   // Build a DYNAREAOFFSET node.
7565   SDValue Ops[2] = {Chain, FPSIdx};
7566   SDVTList VTs = DAG.getVTList(IntVT);
7567   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7568 }
7569 
7570 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7571                                              SelectionDAG &DAG) const {
7572   // When we pop the dynamic allocation we need to restore the SP link.
7573   SDLoc dl(Op);
7574 
7575   // Get the correct type for pointers.
7576   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7577 
7578   // Construct the stack pointer operand.
7579   bool isPPC64 = Subtarget.isPPC64();
7580   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7581   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7582 
7583   // Get the operands for the STACKRESTORE.
7584   SDValue Chain = Op.getOperand(0);
7585   SDValue SaveSP = Op.getOperand(1);
7586 
7587   // Load the old link SP.
7588   SDValue LoadLinkSP =
7589       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7590 
7591   // Restore the stack pointer.
7592   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7593 
7594   // Store the old link SP.
7595   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7596 }
7597 
7598 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7599   MachineFunction &MF = DAG.getMachineFunction();
7600   bool isPPC64 = Subtarget.isPPC64();
7601   EVT PtrVT = getPointerTy(MF.getDataLayout());
7602 
7603   // Get current frame pointer save index.  The users of this index will be
7604   // primarily DYNALLOC instructions.
7605   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7606   int RASI = FI->getReturnAddrSaveIndex();
7607 
7608   // If the frame pointer save index hasn't been defined yet.
7609   if (!RASI) {
7610     // Find out what the fix offset of the frame pointer save area.
7611     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7612     // Allocate the frame index for frame pointer save area.
7613     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7614     // Save the result.
7615     FI->setReturnAddrSaveIndex(RASI);
7616   }
7617   return DAG.getFrameIndex(RASI, PtrVT);
7618 }
7619 
7620 SDValue
7621 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7622   MachineFunction &MF = DAG.getMachineFunction();
7623   bool isPPC64 = Subtarget.isPPC64();
7624   EVT PtrVT = getPointerTy(MF.getDataLayout());
7625 
7626   // Get current frame pointer save index.  The users of this index will be
7627   // primarily DYNALLOC instructions.
7628   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7629   int FPSI = FI->getFramePointerSaveIndex();
7630 
7631   // If the frame pointer save index hasn't been defined yet.
7632   if (!FPSI) {
7633     // Find out what the fix offset of the frame pointer save area.
7634     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7635     // Allocate the frame index for frame pointer save area.
7636     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7637     // Save the result.
7638     FI->setFramePointerSaveIndex(FPSI);
7639   }
7640   return DAG.getFrameIndex(FPSI, PtrVT);
7641 }
7642 
7643 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7644                                                    SelectionDAG &DAG) const {
7645   MachineFunction &MF = DAG.getMachineFunction();
7646   // Get the inputs.
7647   SDValue Chain = Op.getOperand(0);
7648   SDValue Size  = Op.getOperand(1);
7649   SDLoc dl(Op);
7650 
7651   // Get the correct type for pointers.
7652   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7653   // Negate the size.
7654   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7655                                 DAG.getConstant(0, dl, PtrVT), Size);
7656   // Construct a node for the frame pointer save index.
7657   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7658   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7659   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7660   if (hasInlineStackProbe(MF))
7661     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7662   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7663 }
7664 
7665 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7666                                                      SelectionDAG &DAG) const {
7667   MachineFunction &MF = DAG.getMachineFunction();
7668 
7669   bool isPPC64 = Subtarget.isPPC64();
7670   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7671 
7672   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7673   return DAG.getFrameIndex(FI, PtrVT);
7674 }
7675 
7676 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7677                                                SelectionDAG &DAG) const {
7678   SDLoc DL(Op);
7679   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7680                      DAG.getVTList(MVT::i32, MVT::Other),
7681                      Op.getOperand(0), Op.getOperand(1));
7682 }
7683 
7684 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7685                                                 SelectionDAG &DAG) const {
7686   SDLoc DL(Op);
7687   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7688                      Op.getOperand(0), Op.getOperand(1));
7689 }
7690 
7691 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7692   if (Op.getValueType().isVector())
7693     return LowerVectorLoad(Op, DAG);
7694 
7695   assert(Op.getValueType() == MVT::i1 &&
7696          "Custom lowering only for i1 loads");
7697 
7698   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7699 
7700   SDLoc dl(Op);
7701   LoadSDNode *LD = cast<LoadSDNode>(Op);
7702 
7703   SDValue Chain = LD->getChain();
7704   SDValue BasePtr = LD->getBasePtr();
7705   MachineMemOperand *MMO = LD->getMemOperand();
7706 
7707   SDValue NewLD =
7708       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7709                      BasePtr, MVT::i8, MMO);
7710   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7711 
7712   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7713   return DAG.getMergeValues(Ops, dl);
7714 }
7715 
7716 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7717   if (Op.getOperand(1).getValueType().isVector())
7718     return LowerVectorStore(Op, DAG);
7719 
7720   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7721          "Custom lowering only for i1 stores");
7722 
7723   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7724 
7725   SDLoc dl(Op);
7726   StoreSDNode *ST = cast<StoreSDNode>(Op);
7727 
7728   SDValue Chain = ST->getChain();
7729   SDValue BasePtr = ST->getBasePtr();
7730   SDValue Value = ST->getValue();
7731   MachineMemOperand *MMO = ST->getMemOperand();
7732 
7733   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7734                       Value);
7735   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7736 }
7737 
7738 // FIXME: Remove this once the ANDI glue bug is fixed:
7739 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7740   assert(Op.getValueType() == MVT::i1 &&
7741          "Custom lowering only for i1 results");
7742 
7743   SDLoc DL(Op);
7744   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7745 }
7746 
7747 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7748                                                SelectionDAG &DAG) const {
7749 
7750   // Implements a vector truncate that fits in a vector register as a shuffle.
7751   // We want to legalize vector truncates down to where the source fits in
7752   // a vector register (and target is therefore smaller than vector register
7753   // size).  At that point legalization will try to custom lower the sub-legal
7754   // result and get here - where we can contain the truncate as a single target
7755   // operation.
7756 
7757   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7758   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7759   //
7760   // We will implement it for big-endian ordering as this (where x denotes
7761   // undefined):
7762   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7763   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7764   //
7765   // The same operation in little-endian ordering will be:
7766   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7767   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7768 
7769   EVT TrgVT = Op.getValueType();
7770   assert(TrgVT.isVector() && "Vector type expected.");
7771   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7772   EVT EltVT = TrgVT.getVectorElementType();
7773   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7774       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7775       !isPowerOf2_32(EltVT.getSizeInBits()))
7776     return SDValue();
7777 
7778   SDValue N1 = Op.getOperand(0);
7779   EVT SrcVT = N1.getValueType();
7780   unsigned SrcSize = SrcVT.getSizeInBits();
7781   if (SrcSize > 256 ||
7782       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7783       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7784     return SDValue();
7785   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7786     return SDValue();
7787 
7788   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7789   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7790 
7791   SDLoc DL(Op);
7792   SDValue Op1, Op2;
7793   if (SrcSize == 256) {
7794     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7795     EVT SplitVT =
7796         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7797     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7798     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7799                       DAG.getConstant(0, DL, VecIdxTy));
7800     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7801                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7802   }
7803   else {
7804     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7805     Op2 = DAG.getUNDEF(WideVT);
7806   }
7807 
7808   // First list the elements we want to keep.
7809   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7810   SmallVector<int, 16> ShuffV;
7811   if (Subtarget.isLittleEndian())
7812     for (unsigned i = 0; i < TrgNumElts; ++i)
7813       ShuffV.push_back(i * SizeMult);
7814   else
7815     for (unsigned i = 1; i <= TrgNumElts; ++i)
7816       ShuffV.push_back(i * SizeMult - 1);
7817 
7818   // Populate the remaining elements with undefs.
7819   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7820     // ShuffV.push_back(i + WideNumElts);
7821     ShuffV.push_back(WideNumElts + 1);
7822 
7823   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7824   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7825   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7826 }
7827 
7828 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7829 /// possible.
7830 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7831   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7832   EVT ResVT = Op.getValueType();
7833   EVT CmpVT = Op.getOperand(0).getValueType();
7834   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7835   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7836   SDLoc dl(Op);
7837 
7838   // Without power9-vector, we don't have native instruction for f128 comparison.
7839   // Following transformation to libcall is needed for setcc:
7840   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7841   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7842     SDValue Z = DAG.getSetCC(
7843         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7844         LHS, RHS, CC);
7845     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7846     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7847   }
7848 
7849   // Not FP, or using SPE? Not a fsel.
7850   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7851       Subtarget.hasSPE())
7852     return Op;
7853 
7854   SDNodeFlags Flags = Op.getNode()->getFlags();
7855 
7856   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7857   // presence of infinities.
7858   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7859     switch (CC) {
7860     default:
7861       break;
7862     case ISD::SETOGT:
7863     case ISD::SETGT:
7864       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7865     case ISD::SETOLT:
7866     case ISD::SETLT:
7867       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7868     }
7869   }
7870 
7871   // We might be able to do better than this under some circumstances, but in
7872   // general, fsel-based lowering of select is a finite-math-only optimization.
7873   // For more information, see section F.3 of the 2.06 ISA specification.
7874   // With ISA 3.0
7875   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7876       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7877     return Op;
7878 
7879   // If the RHS of the comparison is a 0.0, we don't need to do the
7880   // subtraction at all.
7881   SDValue Sel1;
7882   if (isFloatingPointZero(RHS))
7883     switch (CC) {
7884     default: break;       // SETUO etc aren't handled by fsel.
7885     case ISD::SETNE:
7886       std::swap(TV, FV);
7887       LLVM_FALLTHROUGH;
7888     case ISD::SETEQ:
7889       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7890         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7891       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7892       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7893         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7894       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7895                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7896     case ISD::SETULT:
7897     case ISD::SETLT:
7898       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7899       LLVM_FALLTHROUGH;
7900     case ISD::SETOGE:
7901     case ISD::SETGE:
7902       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7903         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7904       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7905     case ISD::SETUGT:
7906     case ISD::SETGT:
7907       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7908       LLVM_FALLTHROUGH;
7909     case ISD::SETOLE:
7910     case ISD::SETLE:
7911       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7912         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7913       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7914                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7915     }
7916 
7917   SDValue Cmp;
7918   switch (CC) {
7919   default: break;       // SETUO etc aren't handled by fsel.
7920   case ISD::SETNE:
7921     std::swap(TV, FV);
7922     LLVM_FALLTHROUGH;
7923   case ISD::SETEQ:
7924     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7925     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7926       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7927     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7928     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7929       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7930     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7931                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7932   case ISD::SETULT:
7933   case ISD::SETLT:
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, FV, TV);
7938   case ISD::SETOGE:
7939   case ISD::SETGE:
7940     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, 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, TV, FV);
7944   case ISD::SETUGT:
7945   case ISD::SETGT:
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, FV, TV);
7950   case ISD::SETOLE:
7951   case ISD::SETLE:
7952     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7953     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7954       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7955     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7956   }
7957   return Op;
7958 }
7959 
7960 static unsigned getPPCStrictOpcode(unsigned Opc) {
7961   switch (Opc) {
7962   default:
7963     llvm_unreachable("No strict version of this opcode!");
7964   case PPCISD::FCTIDZ:
7965     return PPCISD::STRICT_FCTIDZ;
7966   case PPCISD::FCTIWZ:
7967     return PPCISD::STRICT_FCTIWZ;
7968   case PPCISD::FCTIDUZ:
7969     return PPCISD::STRICT_FCTIDUZ;
7970   case PPCISD::FCTIWUZ:
7971     return PPCISD::STRICT_FCTIWUZ;
7972   case PPCISD::FCFID:
7973     return PPCISD::STRICT_FCFID;
7974   case PPCISD::FCFIDU:
7975     return PPCISD::STRICT_FCFIDU;
7976   case PPCISD::FCFIDS:
7977     return PPCISD::STRICT_FCFIDS;
7978   case PPCISD::FCFIDUS:
7979     return PPCISD::STRICT_FCFIDUS;
7980   }
7981 }
7982 
7983 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7984                               const PPCSubtarget &Subtarget) {
7985   SDLoc dl(Op);
7986   bool IsStrict = Op->isStrictFPOpcode();
7987   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7988                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7989 
7990   // TODO: Any other flags to propagate?
7991   SDNodeFlags Flags;
7992   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7993 
7994   // For strict nodes, source is the second operand.
7995   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7996   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
7997   assert(Src.getValueType().isFloatingPoint());
7998   if (Src.getValueType() == MVT::f32) {
7999     if (IsStrict) {
8000       Src =
8001           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8002                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8003       Chain = Src.getValue(1);
8004     } else
8005       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8006   }
8007   SDValue Conv;
8008   unsigned Opc = ISD::DELETED_NODE;
8009   switch (Op.getSimpleValueType().SimpleTy) {
8010   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8011   case MVT::i32:
8012     Opc = IsSigned ? PPCISD::FCTIWZ
8013                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8014     break;
8015   case MVT::i64:
8016     assert((IsSigned || Subtarget.hasFPCVT()) &&
8017            "i64 FP_TO_UINT is supported only with FPCVT");
8018     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8019   }
8020   if (IsStrict) {
8021     Opc = getPPCStrictOpcode(Opc);
8022     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8023                        {Chain, Src}, Flags);
8024   } else {
8025     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8026   }
8027   return Conv;
8028 }
8029 
8030 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8031                                                SelectionDAG &DAG,
8032                                                const SDLoc &dl) const {
8033   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8034   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8035                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8036   bool IsStrict = Op->isStrictFPOpcode();
8037 
8038   // Convert the FP value to an int value through memory.
8039   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8040                   (IsSigned || Subtarget.hasFPCVT());
8041   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8042   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8043   MachinePointerInfo MPI =
8044       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8045 
8046   // Emit a store to the stack slot.
8047   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8048   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8049   if (i32Stack) {
8050     MachineFunction &MF = DAG.getMachineFunction();
8051     Alignment = Align(4);
8052     MachineMemOperand *MMO =
8053         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8054     SDValue Ops[] = { Chain, Tmp, FIPtr };
8055     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8056               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8057   } else
8058     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8059 
8060   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8061   // add in a bias on big endian.
8062   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8063     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8064                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8065     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8066   }
8067 
8068   RLI.Chain = Chain;
8069   RLI.Ptr = FIPtr;
8070   RLI.MPI = MPI;
8071   RLI.Alignment = Alignment;
8072 }
8073 
8074 /// Custom lowers floating point to integer conversions to use
8075 /// the direct move instructions available in ISA 2.07 to avoid the
8076 /// need for load/store combinations.
8077 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8078                                                     SelectionDAG &DAG,
8079                                                     const SDLoc &dl) const {
8080   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8081   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8082   if (Op->isStrictFPOpcode())
8083     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8084   else
8085     return Mov;
8086 }
8087 
8088 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8089                                           const SDLoc &dl) const {
8090   bool IsStrict = Op->isStrictFPOpcode();
8091   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8092                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8093   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8094   EVT SrcVT = Src.getValueType();
8095   EVT DstVT = Op.getValueType();
8096 
8097   // FP to INT conversions are legal for f128.
8098   if (SrcVT == MVT::f128)
8099     return Subtarget.hasP9Vector() ? Op : SDValue();
8100 
8101   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8102   // PPC (the libcall is not available).
8103   if (SrcVT == MVT::ppcf128) {
8104     if (DstVT == MVT::i32) {
8105       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8106       // set other fast-math flags to FP operations in both strict and
8107       // non-strict cases. (FP_TO_SINT, FSUB)
8108       SDNodeFlags Flags;
8109       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8110 
8111       if (IsSigned) {
8112         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8113                                  DAG.getIntPtrConstant(0, dl));
8114         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8115                                  DAG.getIntPtrConstant(1, dl));
8116 
8117         // Add the two halves of the long double in round-to-zero mode, and use
8118         // a smaller FP_TO_SINT.
8119         if (IsStrict) {
8120           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8121                                     DAG.getVTList(MVT::f64, MVT::Other),
8122                                     {Op.getOperand(0), Lo, Hi}, Flags);
8123           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8124                              DAG.getVTList(MVT::i32, MVT::Other),
8125                              {Res.getValue(1), Res}, Flags);
8126         } else {
8127           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8128           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8129         }
8130       } else {
8131         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8132         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8133         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8134         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8135         if (IsStrict) {
8136           // Sel = Src < 0x80000000
8137           // FltOfs = select Sel, 0.0, 0x80000000
8138           // IntOfs = select Sel, 0, 0x80000000
8139           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8140           SDValue Chain = Op.getOperand(0);
8141           EVT SetCCVT =
8142               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8143           EVT DstSetCCVT =
8144               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8145           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8146                                      Chain, true);
8147           Chain = Sel.getValue(1);
8148 
8149           SDValue FltOfs = DAG.getSelect(
8150               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8151           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8152 
8153           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8154                                     DAG.getVTList(SrcVT, MVT::Other),
8155                                     {Chain, Src, FltOfs}, Flags);
8156           Chain = Val.getValue(1);
8157           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8158                                      DAG.getVTList(DstVT, MVT::Other),
8159                                      {Chain, Val}, Flags);
8160           Chain = SInt.getValue(1);
8161           SDValue IntOfs = DAG.getSelect(
8162               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8163           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8164           return DAG.getMergeValues({Result, Chain}, dl);
8165         } else {
8166           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8167           // FIXME: generated code sucks.
8168           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8169           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8170           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8171           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8172           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8173         }
8174       }
8175     }
8176 
8177     return SDValue();
8178   }
8179 
8180   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8181     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8182 
8183   ReuseLoadInfo RLI;
8184   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8185 
8186   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8187                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8188 }
8189 
8190 // We're trying to insert a regular store, S, and then a load, L. If the
8191 // incoming value, O, is a load, we might just be able to have our load use the
8192 // address used by O. However, we don't know if anything else will store to
8193 // that address before we can load from it. To prevent this situation, we need
8194 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8195 // the same chain operand as O, we create a token factor from the chain results
8196 // of O and L, and we replace all uses of O's chain result with that token
8197 // factor (see spliceIntoChain below for this last part).
8198 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8199                                             ReuseLoadInfo &RLI,
8200                                             SelectionDAG &DAG,
8201                                             ISD::LoadExtType ET) const {
8202   // Conservatively skip reusing for constrained FP nodes.
8203   if (Op->isStrictFPOpcode())
8204     return false;
8205 
8206   SDLoc dl(Op);
8207   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8208                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8209   if (ET == ISD::NON_EXTLOAD &&
8210       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8211       isOperationLegalOrCustom(Op.getOpcode(),
8212                                Op.getOperand(0).getValueType())) {
8213 
8214     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8215     return true;
8216   }
8217 
8218   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8219   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8220       LD->isNonTemporal())
8221     return false;
8222   if (LD->getMemoryVT() != MemVT)
8223     return false;
8224 
8225   // If the result of the load is an illegal type, then we can't build a
8226   // valid chain for reuse since the legalised loads and token factor node that
8227   // ties the legalised loads together uses a different output chain then the
8228   // illegal load.
8229   if (!isTypeLegal(LD->getValueType(0)))
8230     return false;
8231 
8232   RLI.Ptr = LD->getBasePtr();
8233   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8234     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8235            "Non-pre-inc AM on PPC?");
8236     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8237                           LD->getOffset());
8238   }
8239 
8240   RLI.Chain = LD->getChain();
8241   RLI.MPI = LD->getPointerInfo();
8242   RLI.IsDereferenceable = LD->isDereferenceable();
8243   RLI.IsInvariant = LD->isInvariant();
8244   RLI.Alignment = LD->getAlign();
8245   RLI.AAInfo = LD->getAAInfo();
8246   RLI.Ranges = LD->getRanges();
8247 
8248   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8249   return true;
8250 }
8251 
8252 // Given the head of the old chain, ResChain, insert a token factor containing
8253 // it and NewResChain, and make users of ResChain now be users of that token
8254 // factor.
8255 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8256 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8257                                         SDValue NewResChain,
8258                                         SelectionDAG &DAG) const {
8259   if (!ResChain)
8260     return;
8261 
8262   SDLoc dl(NewResChain);
8263 
8264   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8265                            NewResChain, DAG.getUNDEF(MVT::Other));
8266   assert(TF.getNode() != NewResChain.getNode() &&
8267          "A new TF really is required here");
8268 
8269   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8270   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8271 }
8272 
8273 /// Analyze profitability of direct move
8274 /// prefer float load to int load plus direct move
8275 /// when there is no integer use of int load
8276 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8277   SDNode *Origin = Op.getOperand(0).getNode();
8278   if (Origin->getOpcode() != ISD::LOAD)
8279     return true;
8280 
8281   // If there is no LXSIBZX/LXSIHZX, like Power8,
8282   // prefer direct move if the memory size is 1 or 2 bytes.
8283   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8284   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8285     return true;
8286 
8287   for (SDNode::use_iterator UI = Origin->use_begin(),
8288                             UE = Origin->use_end();
8289        UI != UE; ++UI) {
8290 
8291     // Only look at the users of the loaded value.
8292     if (UI.getUse().get().getResNo() != 0)
8293       continue;
8294 
8295     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8296         UI->getOpcode() != ISD::UINT_TO_FP &&
8297         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8298         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8299       return true;
8300   }
8301 
8302   return false;
8303 }
8304 
8305 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8306                               const PPCSubtarget &Subtarget,
8307                               SDValue Chain = SDValue()) {
8308   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8309                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8310   SDLoc dl(Op);
8311 
8312   // TODO: Any other flags to propagate?
8313   SDNodeFlags Flags;
8314   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8315 
8316   // If we have FCFIDS, then use it when converting to single-precision.
8317   // Otherwise, convert to double-precision and then round.
8318   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8319   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8320                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8321   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8322   if (Op->isStrictFPOpcode()) {
8323     if (!Chain)
8324       Chain = Op.getOperand(0);
8325     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8326                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8327   } else
8328     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8329 }
8330 
8331 /// Custom lowers integer to floating point conversions to use
8332 /// the direct move instructions available in ISA 2.07 to avoid the
8333 /// need for load/store combinations.
8334 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8335                                                     SelectionDAG &DAG,
8336                                                     const SDLoc &dl) const {
8337   assert((Op.getValueType() == MVT::f32 ||
8338           Op.getValueType() == MVT::f64) &&
8339          "Invalid floating point type as target of conversion");
8340   assert(Subtarget.hasFPCVT() &&
8341          "Int to FP conversions with direct moves require FPCVT");
8342   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8343   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8344   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8345                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8346   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8347   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8348   return convertIntToFP(Op, Mov, DAG, Subtarget);
8349 }
8350 
8351 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8352 
8353   EVT VecVT = Vec.getValueType();
8354   assert(VecVT.isVector() && "Expected a vector type.");
8355   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8356 
8357   EVT EltVT = VecVT.getVectorElementType();
8358   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8359   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8360 
8361   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8362   SmallVector<SDValue, 16> Ops(NumConcat);
8363   Ops[0] = Vec;
8364   SDValue UndefVec = DAG.getUNDEF(VecVT);
8365   for (unsigned i = 1; i < NumConcat; ++i)
8366     Ops[i] = UndefVec;
8367 
8368   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8369 }
8370 
8371 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8372                                                 const SDLoc &dl) const {
8373   bool IsStrict = Op->isStrictFPOpcode();
8374   unsigned Opc = Op.getOpcode();
8375   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8376   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8377           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8378          "Unexpected conversion type");
8379   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8380          "Supports conversions to v2f64/v4f32 only.");
8381 
8382   // TODO: Any other flags to propagate?
8383   SDNodeFlags Flags;
8384   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8385 
8386   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8387   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8388 
8389   SDValue Wide = widenVec(DAG, Src, dl);
8390   EVT WideVT = Wide.getValueType();
8391   unsigned WideNumElts = WideVT.getVectorNumElements();
8392   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8393 
8394   SmallVector<int, 16> ShuffV;
8395   for (unsigned i = 0; i < WideNumElts; ++i)
8396     ShuffV.push_back(i + WideNumElts);
8397 
8398   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8399   int SaveElts = FourEltRes ? 4 : 2;
8400   if (Subtarget.isLittleEndian())
8401     for (int i = 0; i < SaveElts; i++)
8402       ShuffV[i * Stride] = i;
8403   else
8404     for (int i = 1; i <= SaveElts; i++)
8405       ShuffV[i * Stride - 1] = i - 1;
8406 
8407   SDValue ShuffleSrc2 =
8408       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8409   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8410 
8411   SDValue Extend;
8412   if (SignedConv) {
8413     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8414     EVT ExtVT = Src.getValueType();
8415     if (Subtarget.hasP9Altivec())
8416       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8417                                IntermediateVT.getVectorNumElements());
8418 
8419     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8420                          DAG.getValueType(ExtVT));
8421   } else
8422     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8423 
8424   if (IsStrict)
8425     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8426                        {Op.getOperand(0), Extend}, Flags);
8427 
8428   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8429 }
8430 
8431 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8432                                           SelectionDAG &DAG) const {
8433   SDLoc dl(Op);
8434   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8435                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8436   bool IsStrict = Op->isStrictFPOpcode();
8437   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8438   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8439 
8440   // TODO: Any other flags to propagate?
8441   SDNodeFlags Flags;
8442   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8443 
8444   EVT InVT = Src.getValueType();
8445   EVT OutVT = Op.getValueType();
8446   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8447       isOperationCustom(Op.getOpcode(), InVT))
8448     return LowerINT_TO_FPVector(Op, DAG, dl);
8449 
8450   // Conversions to f128 are legal.
8451   if (Op.getValueType() == MVT::f128)
8452     return Subtarget.hasP9Vector() ? Op : SDValue();
8453 
8454   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8455   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8456     return SDValue();
8457 
8458   if (Src.getValueType() == MVT::i1) {
8459     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8460                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8461                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8462     if (IsStrict)
8463       return DAG.getMergeValues({Sel, Chain}, dl);
8464     else
8465       return Sel;
8466   }
8467 
8468   // If we have direct moves, we can do all the conversion, skip the store/load
8469   // however, without FPCVT we can't do most conversions.
8470   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8471       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8472     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8473 
8474   assert((IsSigned || Subtarget.hasFPCVT()) &&
8475          "UINT_TO_FP is supported only with FPCVT");
8476 
8477   if (Src.getValueType() == MVT::i64) {
8478     SDValue SINT = Src;
8479     // When converting to single-precision, we actually need to convert
8480     // to double-precision first and then round to single-precision.
8481     // To avoid double-rounding effects during that operation, we have
8482     // to prepare the input operand.  Bits that might be truncated when
8483     // converting to double-precision are replaced by a bit that won't
8484     // be lost at this stage, but is below the single-precision rounding
8485     // position.
8486     //
8487     // However, if -enable-unsafe-fp-math is in effect, accept double
8488     // rounding to avoid the extra overhead.
8489     if (Op.getValueType() == MVT::f32 &&
8490         !Subtarget.hasFPCVT() &&
8491         !DAG.getTarget().Options.UnsafeFPMath) {
8492 
8493       // Twiddle input to make sure the low 11 bits are zero.  (If this
8494       // is the case, we are guaranteed the value will fit into the 53 bit
8495       // mantissa of an IEEE double-precision value without rounding.)
8496       // If any of those low 11 bits were not zero originally, make sure
8497       // bit 12 (value 2048) is set instead, so that the final rounding
8498       // to single-precision gets the correct result.
8499       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8500                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8501       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8502                           Round, DAG.getConstant(2047, dl, MVT::i64));
8503       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8504       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8505                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8506 
8507       // However, we cannot use that value unconditionally: if the magnitude
8508       // of the input value is small, the bit-twiddling we did above might
8509       // end up visibly changing the output.  Fortunately, in that case, we
8510       // don't need to twiddle bits since the original input will convert
8511       // exactly to double-precision floating-point already.  Therefore,
8512       // construct a conditional to use the original value if the top 11
8513       // bits are all sign-bit copies, and use the rounded value computed
8514       // above otherwise.
8515       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8516                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8517       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8518                          Cond, DAG.getConstant(1, dl, MVT::i64));
8519       Cond = DAG.getSetCC(
8520           dl,
8521           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8522           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8523 
8524       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8525     }
8526 
8527     ReuseLoadInfo RLI;
8528     SDValue Bits;
8529 
8530     MachineFunction &MF = DAG.getMachineFunction();
8531     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8532       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8533                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8534       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8535     } else if (Subtarget.hasLFIWAX() &&
8536                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8537       MachineMemOperand *MMO =
8538         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8539                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8540       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8541       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8542                                      DAG.getVTList(MVT::f64, MVT::Other),
8543                                      Ops, MVT::i32, MMO);
8544       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8545     } else if (Subtarget.hasFPCVT() &&
8546                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8547       MachineMemOperand *MMO =
8548         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8549                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8550       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8551       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8552                                      DAG.getVTList(MVT::f64, MVT::Other),
8553                                      Ops, MVT::i32, MMO);
8554       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8555     } else if (((Subtarget.hasLFIWAX() &&
8556                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8557                 (Subtarget.hasFPCVT() &&
8558                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8559                SINT.getOperand(0).getValueType() == MVT::i32) {
8560       MachineFrameInfo &MFI = MF.getFrameInfo();
8561       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8562 
8563       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8564       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8565 
8566       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8567                                    MachinePointerInfo::getFixedStack(
8568                                        DAG.getMachineFunction(), FrameIdx));
8569       Chain = Store;
8570 
8571       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8572              "Expected an i32 store");
8573 
8574       RLI.Ptr = FIdx;
8575       RLI.Chain = Chain;
8576       RLI.MPI =
8577           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8578       RLI.Alignment = Align(4);
8579 
8580       MachineMemOperand *MMO =
8581         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8582                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8583       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8584       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8585                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8586                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8587                                      Ops, MVT::i32, MMO);
8588       Chain = Bits.getValue(1);
8589     } else
8590       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8591 
8592     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8593     if (IsStrict)
8594       Chain = FP.getValue(1);
8595 
8596     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8597       if (IsStrict)
8598         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8599                          DAG.getVTList(MVT::f32, MVT::Other),
8600                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8601       else
8602         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8603                          DAG.getIntPtrConstant(0, dl));
8604     }
8605     return FP;
8606   }
8607 
8608   assert(Src.getValueType() == MVT::i32 &&
8609          "Unhandled INT_TO_FP type in custom expander!");
8610   // Since we only generate this in 64-bit mode, we can take advantage of
8611   // 64-bit registers.  In particular, sign extend the input value into the
8612   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8613   // then lfd it and fcfid it.
8614   MachineFunction &MF = DAG.getMachineFunction();
8615   MachineFrameInfo &MFI = MF.getFrameInfo();
8616   EVT PtrVT = getPointerTy(MF.getDataLayout());
8617 
8618   SDValue Ld;
8619   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8620     ReuseLoadInfo RLI;
8621     bool ReusingLoad;
8622     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8623       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8624       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8625 
8626       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8627                                    MachinePointerInfo::getFixedStack(
8628                                        DAG.getMachineFunction(), FrameIdx));
8629       Chain = Store;
8630 
8631       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8632              "Expected an i32 store");
8633 
8634       RLI.Ptr = FIdx;
8635       RLI.Chain = Chain;
8636       RLI.MPI =
8637           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8638       RLI.Alignment = Align(4);
8639     }
8640 
8641     MachineMemOperand *MMO =
8642       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8643                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8644     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8645     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8646                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8647                                  MVT::i32, MMO);
8648     Chain = Ld.getValue(1);
8649     if (ReusingLoad)
8650       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8651   } else {
8652     assert(Subtarget.isPPC64() &&
8653            "i32->FP without LFIWAX supported only on PPC64");
8654 
8655     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8656     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8657 
8658     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8659 
8660     // STD the extended value into the stack slot.
8661     SDValue Store = DAG.getStore(
8662         Chain, dl, Ext64, FIdx,
8663         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8664     Chain = Store;
8665 
8666     // Load the value as a double.
8667     Ld = DAG.getLoad(
8668         MVT::f64, dl, Chain, FIdx,
8669         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8670     Chain = Ld.getValue(1);
8671   }
8672 
8673   // FCFID it and return it.
8674   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8675   if (IsStrict)
8676     Chain = FP.getValue(1);
8677   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8678     if (IsStrict)
8679       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8680                        DAG.getVTList(MVT::f32, MVT::Other),
8681                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8682     else
8683       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8684                        DAG.getIntPtrConstant(0, dl));
8685   }
8686   return FP;
8687 }
8688 
8689 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8690                                             SelectionDAG &DAG) const {
8691   SDLoc dl(Op);
8692   /*
8693    The rounding mode is in bits 30:31 of FPSR, and has the following
8694    settings:
8695      00 Round to nearest
8696      01 Round to 0
8697      10 Round to +inf
8698      11 Round to -inf
8699 
8700   FLT_ROUNDS, on the other hand, expects the following:
8701     -1 Undefined
8702      0 Round to 0
8703      1 Round to nearest
8704      2 Round to +inf
8705      3 Round to -inf
8706 
8707   To perform the conversion, we do:
8708     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8709   */
8710 
8711   MachineFunction &MF = DAG.getMachineFunction();
8712   EVT VT = Op.getValueType();
8713   EVT PtrVT = getPointerTy(MF.getDataLayout());
8714 
8715   // Save FP Control Word to register
8716   SDValue Chain = Op.getOperand(0);
8717   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8718   Chain = MFFS.getValue(1);
8719 
8720   SDValue CWD;
8721   if (isTypeLegal(MVT::i64)) {
8722     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8723                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8724   } else {
8725     // Save FP register to stack slot
8726     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8727     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8728     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8729 
8730     // Load FP Control Word from low 32 bits of stack slot.
8731     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8732            "Stack slot adjustment is valid only on big endian subtargets!");
8733     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8734     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8735     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8736     Chain = CWD.getValue(1);
8737   }
8738 
8739   // Transform as necessary
8740   SDValue CWD1 =
8741     DAG.getNode(ISD::AND, dl, MVT::i32,
8742                 CWD, DAG.getConstant(3, dl, MVT::i32));
8743   SDValue CWD2 =
8744     DAG.getNode(ISD::SRL, dl, MVT::i32,
8745                 DAG.getNode(ISD::AND, dl, MVT::i32,
8746                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8747                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8748                             DAG.getConstant(3, dl, MVT::i32)),
8749                 DAG.getConstant(1, dl, MVT::i32));
8750 
8751   SDValue RetVal =
8752     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8753 
8754   RetVal =
8755       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8756                   dl, VT, RetVal);
8757 
8758   return DAG.getMergeValues({RetVal, Chain}, dl);
8759 }
8760 
8761 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8762   EVT VT = Op.getValueType();
8763   unsigned BitWidth = VT.getSizeInBits();
8764   SDLoc dl(Op);
8765   assert(Op.getNumOperands() == 3 &&
8766          VT == Op.getOperand(1).getValueType() &&
8767          "Unexpected SHL!");
8768 
8769   // Expand into a bunch of logical ops.  Note that these ops
8770   // depend on the PPC behavior for oversized shift amounts.
8771   SDValue Lo = Op.getOperand(0);
8772   SDValue Hi = Op.getOperand(1);
8773   SDValue Amt = Op.getOperand(2);
8774   EVT AmtVT = Amt.getValueType();
8775 
8776   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8777                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8778   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8779   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8780   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8781   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8782                              DAG.getConstant(-BitWidth, dl, AmtVT));
8783   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8784   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8785   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8786   SDValue OutOps[] = { OutLo, OutHi };
8787   return DAG.getMergeValues(OutOps, dl);
8788 }
8789 
8790 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8791   EVT VT = Op.getValueType();
8792   SDLoc dl(Op);
8793   unsigned BitWidth = VT.getSizeInBits();
8794   assert(Op.getNumOperands() == 3 &&
8795          VT == Op.getOperand(1).getValueType() &&
8796          "Unexpected SRL!");
8797 
8798   // Expand into a bunch of logical ops.  Note that these ops
8799   // depend on the PPC behavior for oversized shift amounts.
8800   SDValue Lo = Op.getOperand(0);
8801   SDValue Hi = Op.getOperand(1);
8802   SDValue Amt = Op.getOperand(2);
8803   EVT AmtVT = Amt.getValueType();
8804 
8805   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8806                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8807   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8808   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8809   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8810   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8811                              DAG.getConstant(-BitWidth, dl, AmtVT));
8812   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8813   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8814   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8815   SDValue OutOps[] = { OutLo, OutHi };
8816   return DAG.getMergeValues(OutOps, dl);
8817 }
8818 
8819 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8820   SDLoc dl(Op);
8821   EVT VT = Op.getValueType();
8822   unsigned BitWidth = VT.getSizeInBits();
8823   assert(Op.getNumOperands() == 3 &&
8824          VT == Op.getOperand(1).getValueType() &&
8825          "Unexpected SRA!");
8826 
8827   // Expand into a bunch of logical ops, followed by a select_cc.
8828   SDValue Lo = Op.getOperand(0);
8829   SDValue Hi = Op.getOperand(1);
8830   SDValue Amt = Op.getOperand(2);
8831   EVT AmtVT = Amt.getValueType();
8832 
8833   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8834                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8835   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8836   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8837   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8838   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8839                              DAG.getConstant(-BitWidth, dl, AmtVT));
8840   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8841   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8842   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8843                                   Tmp4, Tmp6, ISD::SETLE);
8844   SDValue OutOps[] = { OutLo, OutHi };
8845   return DAG.getMergeValues(OutOps, dl);
8846 }
8847 
8848 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8849                                             SelectionDAG &DAG) const {
8850   SDLoc dl(Op);
8851   EVT VT = Op.getValueType();
8852   unsigned BitWidth = VT.getSizeInBits();
8853 
8854   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8855   SDValue X = Op.getOperand(0);
8856   SDValue Y = Op.getOperand(1);
8857   SDValue Z = Op.getOperand(2);
8858   EVT AmtVT = Z.getValueType();
8859 
8860   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8861   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8862   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8863   // on PowerPC shift by BW being well defined.
8864   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8865                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8866   SDValue SubZ =
8867       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8868   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8869   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8870   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8871 }
8872 
8873 //===----------------------------------------------------------------------===//
8874 // Vector related lowering.
8875 //
8876 
8877 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8878 /// element size of SplatSize. Cast the result to VT.
8879 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8880                                       SelectionDAG &DAG, const SDLoc &dl) {
8881   static const MVT VTys[] = { // canonical VT to use for each size.
8882     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8883   };
8884 
8885   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8886 
8887   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8888   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8889     SplatSize = 1;
8890     Val = 0xFF;
8891   }
8892 
8893   EVT CanonicalVT = VTys[SplatSize-1];
8894 
8895   // Build a canonical splat for this value.
8896   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8897 }
8898 
8899 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8900 /// specified intrinsic ID.
8901 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8902                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8903   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8904   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8905                      DAG.getConstant(IID, dl, MVT::i32), Op);
8906 }
8907 
8908 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8909 /// specified intrinsic ID.
8910 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8911                                 SelectionDAG &DAG, const SDLoc &dl,
8912                                 EVT DestVT = MVT::Other) {
8913   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8914   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8915                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8916 }
8917 
8918 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8919 /// specified intrinsic ID.
8920 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8921                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8922                                 EVT DestVT = MVT::Other) {
8923   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8924   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8925                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8926 }
8927 
8928 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8929 /// amount.  The result has the specified value type.
8930 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8931                            SelectionDAG &DAG, const SDLoc &dl) {
8932   // Force LHS/RHS to be the right type.
8933   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8934   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8935 
8936   int Ops[16];
8937   for (unsigned i = 0; i != 16; ++i)
8938     Ops[i] = i + Amt;
8939   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8940   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8941 }
8942 
8943 /// Do we have an efficient pattern in a .td file for this node?
8944 ///
8945 /// \param V - pointer to the BuildVectorSDNode being matched
8946 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8947 ///
8948 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8949 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8950 /// the opposite is true (expansion is beneficial) are:
8951 /// - The node builds a vector out of integers that are not 32 or 64-bits
8952 /// - The node builds a vector out of constants
8953 /// - The node is a "load-and-splat"
8954 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8955 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8956                                             bool HasDirectMove,
8957                                             bool HasP8Vector) {
8958   EVT VecVT = V->getValueType(0);
8959   bool RightType = VecVT == MVT::v2f64 ||
8960     (HasP8Vector && VecVT == MVT::v4f32) ||
8961     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8962   if (!RightType)
8963     return false;
8964 
8965   bool IsSplat = true;
8966   bool IsLoad = false;
8967   SDValue Op0 = V->getOperand(0);
8968 
8969   // This function is called in a block that confirms the node is not a constant
8970   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8971   // different constants.
8972   if (V->isConstant())
8973     return false;
8974   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8975     if (V->getOperand(i).isUndef())
8976       return false;
8977     // We want to expand nodes that represent load-and-splat even if the
8978     // loaded value is a floating point truncation or conversion to int.
8979     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8980         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8981          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8982         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8983          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8984         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8985          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8986       IsLoad = true;
8987     // If the operands are different or the input is not a load and has more
8988     // uses than just this BV node, then it isn't a splat.
8989     if (V->getOperand(i) != Op0 ||
8990         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8991       IsSplat = false;
8992   }
8993   return !(IsSplat && IsLoad);
8994 }
8995 
8996 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8997 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8998 
8999   SDLoc dl(Op);
9000   SDValue Op0 = Op->getOperand(0);
9001 
9002   if ((Op.getValueType() != MVT::f128) ||
9003       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9004       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9005       (Op0.getOperand(1).getValueType() != MVT::i64))
9006     return SDValue();
9007 
9008   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9009                      Op0.getOperand(1));
9010 }
9011 
9012 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9013   const SDValue *InputLoad = &Op;
9014   if (InputLoad->getOpcode() == ISD::BITCAST)
9015     InputLoad = &InputLoad->getOperand(0);
9016   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9017       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9018     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9019     InputLoad = &InputLoad->getOperand(0);
9020   }
9021   if (InputLoad->getOpcode() != ISD::LOAD)
9022     return nullptr;
9023   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9024   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9025 }
9026 
9027 // Convert the argument APFloat to a single precision APFloat if there is no
9028 // loss in information during the conversion to single precision APFloat and the
9029 // resulting number is not a denormal number. Return true if successful.
9030 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9031   APFloat APFloatToConvert = ArgAPFloat;
9032   bool LosesInfo = true;
9033   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9034                            &LosesInfo);
9035   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9036   if (Success)
9037     ArgAPFloat = APFloatToConvert;
9038   return Success;
9039 }
9040 
9041 // Bitcast the argument APInt to a double and convert it to a single precision
9042 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9043 // argument if there is no loss in information during the conversion from
9044 // double to single precision APFloat and the resulting number is not a denormal
9045 // number. Return true if successful.
9046 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9047   double DpValue = ArgAPInt.bitsToDouble();
9048   APFloat APFloatDp(DpValue);
9049   bool Success = convertToNonDenormSingle(APFloatDp);
9050   if (Success)
9051     ArgAPInt = APFloatDp.bitcastToAPInt();
9052   return Success;
9053 }
9054 
9055 // Nondestructive check for convertTonNonDenormSingle.
9056 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9057   // Only convert if it loses info, since XXSPLTIDP should
9058   // handle the other case.
9059   APFloat APFloatToConvert = ArgAPFloat;
9060   bool LosesInfo = true;
9061   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9062                            &LosesInfo);
9063 
9064   return (!LosesInfo && !APFloatToConvert.isDenormal());
9065 }
9066 
9067 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9068                              unsigned &Opcode) {
9069   const SDNode *InputNode = Op.getOperand(0).getNode();
9070   if (!InputNode || !ISD::isUNINDEXEDLoad(InputNode))
9071     return false;
9072 
9073   if (!Subtarget.hasVSX())
9074     return false;
9075 
9076   EVT Ty = Op->getValueType(0);
9077   if (Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32 ||
9078       Ty == MVT::v8i16 || Ty == MVT::v16i8)
9079     return true;
9080 
9081   if (Ty == MVT::v2i64) {
9082     // check the extend type if the input is i32 while the output vector type is
9083     // v2i64.
9084     if (cast<LoadSDNode>(Op.getOperand(0))->getMemoryVT() == MVT::i32) {
9085       if (ISD::isZEXTLoad(InputNode))
9086         Opcode = PPCISD::ZEXT_LD_SPLAT;
9087       if (ISD::isSEXTLoad(InputNode))
9088         Opcode = PPCISD::SEXT_LD_SPLAT;
9089     }
9090     return true;
9091   }
9092   return false;
9093 }
9094 
9095 // If this is a case we can't handle, return null and let the default
9096 // expansion code take care of it.  If we CAN select this case, and if it
9097 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9098 // this case more efficiently than a constant pool load, lower it to the
9099 // sequence of ops that should be used.
9100 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9101                                              SelectionDAG &DAG) const {
9102   SDLoc dl(Op);
9103   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9104   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9105 
9106   // Check if this is a splat of a constant value.
9107   APInt APSplatBits, APSplatUndef;
9108   unsigned SplatBitSize;
9109   bool HasAnyUndefs;
9110   bool BVNIsConstantSplat =
9111       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9112                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9113 
9114   // If it is a splat of a double, check if we can shrink it to a 32 bit
9115   // non-denormal float which when converted back to double gives us the same
9116   // double. This is to exploit the XXSPLTIDP instruction.
9117   // If we lose precision, we use XXSPLTI32DX.
9118   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9119       Subtarget.hasPrefixInstrs()) {
9120     // Check the type first to short-circuit so we don't modify APSplatBits if
9121     // this block isn't executed.
9122     if ((Op->getValueType(0) == MVT::v2f64) &&
9123         convertToNonDenormSingle(APSplatBits)) {
9124       SDValue SplatNode = DAG.getNode(
9125           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9126           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9127       return DAG.getBitcast(Op.getValueType(), SplatNode);
9128     } else {
9129       // We may lose precision, so we have to use XXSPLTI32DX.
9130 
9131       uint32_t Hi =
9132           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9133       uint32_t Lo =
9134           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9135       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9136 
9137       if (!Hi || !Lo)
9138         // If either load is 0, then we should generate XXLXOR to set to 0.
9139         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9140 
9141       if (Hi)
9142         SplatNode = DAG.getNode(
9143             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9144             DAG.getTargetConstant(0, dl, MVT::i32),
9145             DAG.getTargetConstant(Hi, dl, MVT::i32));
9146 
9147       if (Lo)
9148         SplatNode =
9149             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9150                         DAG.getTargetConstant(1, dl, MVT::i32),
9151                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9152 
9153       return DAG.getBitcast(Op.getValueType(), SplatNode);
9154     }
9155   }
9156 
9157   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9158     unsigned NewOpcode = PPCISD::LD_SPLAT;
9159 
9160     // Handle load-and-splat patterns as we have instructions that will do this
9161     // in one go.
9162     if (DAG.isSplatValue(Op, true) &&
9163         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9164       const SDValue *InputLoad = &Op.getOperand(0);
9165       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9166 
9167       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits() *
9168                              ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9169 
9170       // Checking for a single use of this load, we have to check for vector
9171       // width (128 bits) / ElementSize uses (since each operand of the
9172       // BUILD_VECTOR is a separate use of the value.
9173       unsigned NumUsesOfInputLD = 128 / ElementSize;
9174       for (SDValue BVInOp : Op->ops())
9175         if (BVInOp.isUndef())
9176           NumUsesOfInputLD--;
9177 
9178       // Execlude somes case where LD_SPLAT is worse than scalar_to_vector:
9179       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9180       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9181       // 15", but funciton IsValidSplatLoad() now will only return true when
9182       // the data at index 0 is not nullptr. So we will not get into trouble for
9183       // these cases.
9184       //
9185       // case 1 - lfiwzx/lfiwax
9186       // 1.1: load result is i32 and is sign/zero extend to i64;
9187       // 1.2: build a v2i64 vector type with above loaded value;
9188       // 1.3: the vector has only one value at index 0, others are all undef;
9189       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9190       if (NumUsesOfInputLD == 1 &&
9191           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9192            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9193            Subtarget.hasLFIWAX()))
9194         return SDValue();
9195 
9196       // case 2 - lxvrhx
9197       // 2.1: load result is i16;
9198       // 2.2: build a v8i16 vector with above loaded value;
9199       // 2.3: the vector has only one value at index 0, others are all undef;
9200       // 2.4: on LE target, so that lxvrhx does not need any permute.
9201       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9202           Subtarget.isISA3_1() && Op->getValueType(0) == MVT::v16i8)
9203         return SDValue();
9204 
9205       // case 3 - lxvrbx
9206       // 3.1: load result is i8;
9207       // 3.2: build a v16i8 vector with above loaded value;
9208       // 3.3: the vector has only one value at index 0, others are all undef;
9209       // 3.4: on LE target, so that lxvrbx does not need any permute.
9210       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9211           Subtarget.isISA3_1() && Op->getValueType(0) == MVT::v8i16)
9212         return SDValue();
9213 
9214       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9215       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9216           Subtarget.hasVSX()) {
9217         SDValue Ops[] = {
9218           LD->getChain(),    // Chain
9219           LD->getBasePtr(),  // Ptr
9220           DAG.getValueType(Op.getValueType()) // VT
9221         };
9222         SDValue LdSplt = DAG.getMemIntrinsicNode(
9223             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9224             LD->getMemoryVT(), LD->getMemOperand());
9225         // Replace all uses of the output chain of the original load with the
9226         // output chain of the new load.
9227         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9228                                       LdSplt.getValue(1));
9229         return LdSplt;
9230       }
9231     }
9232 
9233     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9234     // 32-bits can be lowered to VSX instructions under certain conditions.
9235     // Without VSX, there is no pattern more efficient than expanding the node.
9236     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9237         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9238                                         Subtarget.hasP8Vector()))
9239       return Op;
9240     return SDValue();
9241   }
9242 
9243   uint64_t SplatBits = APSplatBits.getZExtValue();
9244   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9245   unsigned SplatSize = SplatBitSize / 8;
9246 
9247   // First, handle single instruction cases.
9248 
9249   // All zeros?
9250   if (SplatBits == 0) {
9251     // Canonicalize all zero vectors to be v4i32.
9252     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9253       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9254       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9255     }
9256     return Op;
9257   }
9258 
9259   // We have XXSPLTIW for constant splats four bytes wide.
9260   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9261   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9262   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9263   // turned into a 4-byte splat of 0xABABABAB.
9264   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9265     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9266                                   Op.getValueType(), DAG, dl);
9267 
9268   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9269     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9270                                   dl);
9271 
9272   // We have XXSPLTIB for constant splats one byte wide.
9273   if (Subtarget.hasP9Vector() && SplatSize == 1)
9274     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9275                                   dl);
9276 
9277   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9278   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9279                     (32-SplatBitSize));
9280   if (SextVal >= -16 && SextVal <= 15)
9281     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9282                                   dl);
9283 
9284   // Two instruction sequences.
9285 
9286   // If this value is in the range [-32,30] and is even, use:
9287   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9288   // If this value is in the range [17,31] and is odd, use:
9289   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9290   // If this value is in the range [-31,-17] and is odd, use:
9291   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9292   // Note the last two are three-instruction sequences.
9293   if (SextVal >= -32 && SextVal <= 31) {
9294     // To avoid having these optimizations undone by constant folding,
9295     // we convert to a pseudo that will be expanded later into one of
9296     // the above forms.
9297     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9298     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9299               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9300     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9301     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9302     if (VT == Op.getValueType())
9303       return RetVal;
9304     else
9305       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9306   }
9307 
9308   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9309   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9310   // for fneg/fabs.
9311   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9312     // Make -1 and vspltisw -1:
9313     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9314 
9315     // Make the VSLW intrinsic, computing 0x8000_0000.
9316     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9317                                    OnesV, DAG, dl);
9318 
9319     // xor by OnesV to invert it.
9320     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9321     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9322   }
9323 
9324   // Check to see if this is a wide variety of vsplti*, binop self cases.
9325   static const signed char SplatCsts[] = {
9326     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9327     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9328   };
9329 
9330   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9331     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9332     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9333     int i = SplatCsts[idx];
9334 
9335     // Figure out what shift amount will be used by altivec if shifted by i in
9336     // this splat size.
9337     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9338 
9339     // vsplti + shl self.
9340     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9341       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9342       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9343         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9344         Intrinsic::ppc_altivec_vslw
9345       };
9346       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9347       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9348     }
9349 
9350     // vsplti + srl self.
9351     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9352       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9353       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9354         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9355         Intrinsic::ppc_altivec_vsrw
9356       };
9357       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9358       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9359     }
9360 
9361     // vsplti + rol self.
9362     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9363                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9364       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9365       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9366         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9367         Intrinsic::ppc_altivec_vrlw
9368       };
9369       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9370       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9371     }
9372 
9373     // t = vsplti c, result = vsldoi t, t, 1
9374     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9375       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9376       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9377       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9378     }
9379     // t = vsplti c, result = vsldoi t, t, 2
9380     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9381       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9382       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9383       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9384     }
9385     // t = vsplti c, result = vsldoi t, t, 3
9386     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9387       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9388       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9389       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9390     }
9391   }
9392 
9393   return SDValue();
9394 }
9395 
9396 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9397 /// the specified operations to build the shuffle.
9398 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9399                                       SDValue RHS, SelectionDAG &DAG,
9400                                       const SDLoc &dl) {
9401   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9402   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9403   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9404 
9405   enum {
9406     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9407     OP_VMRGHW,
9408     OP_VMRGLW,
9409     OP_VSPLTISW0,
9410     OP_VSPLTISW1,
9411     OP_VSPLTISW2,
9412     OP_VSPLTISW3,
9413     OP_VSLDOI4,
9414     OP_VSLDOI8,
9415     OP_VSLDOI12
9416   };
9417 
9418   if (OpNum == OP_COPY) {
9419     if (LHSID == (1*9+2)*9+3) return LHS;
9420     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9421     return RHS;
9422   }
9423 
9424   SDValue OpLHS, OpRHS;
9425   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9426   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9427 
9428   int ShufIdxs[16];
9429   switch (OpNum) {
9430   default: llvm_unreachable("Unknown i32 permute!");
9431   case OP_VMRGHW:
9432     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9433     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9434     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9435     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9436     break;
9437   case OP_VMRGLW:
9438     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9439     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9440     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9441     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9442     break;
9443   case OP_VSPLTISW0:
9444     for (unsigned i = 0; i != 16; ++i)
9445       ShufIdxs[i] = (i&3)+0;
9446     break;
9447   case OP_VSPLTISW1:
9448     for (unsigned i = 0; i != 16; ++i)
9449       ShufIdxs[i] = (i&3)+4;
9450     break;
9451   case OP_VSPLTISW2:
9452     for (unsigned i = 0; i != 16; ++i)
9453       ShufIdxs[i] = (i&3)+8;
9454     break;
9455   case OP_VSPLTISW3:
9456     for (unsigned i = 0; i != 16; ++i)
9457       ShufIdxs[i] = (i&3)+12;
9458     break;
9459   case OP_VSLDOI4:
9460     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9461   case OP_VSLDOI8:
9462     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9463   case OP_VSLDOI12:
9464     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9465   }
9466   EVT VT = OpLHS.getValueType();
9467   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9468   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9469   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9470   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9471 }
9472 
9473 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9474 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9475 /// SDValue.
9476 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9477                                            SelectionDAG &DAG) const {
9478   const unsigned BytesInVector = 16;
9479   bool IsLE = Subtarget.isLittleEndian();
9480   SDLoc dl(N);
9481   SDValue V1 = N->getOperand(0);
9482   SDValue V2 = N->getOperand(1);
9483   unsigned ShiftElts = 0, InsertAtByte = 0;
9484   bool Swap = false;
9485 
9486   // Shifts required to get the byte we want at element 7.
9487   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9488                                    0, 15, 14, 13, 12, 11, 10, 9};
9489   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9490                                 1, 2,  3,  4,  5,  6,  7,  8};
9491 
9492   ArrayRef<int> Mask = N->getMask();
9493   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9494 
9495   // For each mask element, find out if we're just inserting something
9496   // from V2 into V1 or vice versa.
9497   // Possible permutations inserting an element from V2 into V1:
9498   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9499   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9500   //   ...
9501   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9502   // Inserting from V1 into V2 will be similar, except mask range will be
9503   // [16,31].
9504 
9505   bool FoundCandidate = false;
9506   // If both vector operands for the shuffle are the same vector, the mask
9507   // will contain only elements from the first one and the second one will be
9508   // undef.
9509   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9510   // Go through the mask of half-words to find an element that's being moved
9511   // from one vector to the other.
9512   for (unsigned i = 0; i < BytesInVector; ++i) {
9513     unsigned CurrentElement = Mask[i];
9514     // If 2nd operand is undefined, we should only look for element 7 in the
9515     // Mask.
9516     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9517       continue;
9518 
9519     bool OtherElementsInOrder = true;
9520     // Examine the other elements in the Mask to see if they're in original
9521     // order.
9522     for (unsigned j = 0; j < BytesInVector; ++j) {
9523       if (j == i)
9524         continue;
9525       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9526       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9527       // in which we always assume we're always picking from the 1st operand.
9528       int MaskOffset =
9529           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9530       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9531         OtherElementsInOrder = false;
9532         break;
9533       }
9534     }
9535     // If other elements are in original order, we record the number of shifts
9536     // we need to get the element we want into element 7. Also record which byte
9537     // in the vector we should insert into.
9538     if (OtherElementsInOrder) {
9539       // If 2nd operand is undefined, we assume no shifts and no swapping.
9540       if (V2.isUndef()) {
9541         ShiftElts = 0;
9542         Swap = false;
9543       } else {
9544         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9545         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9546                          : BigEndianShifts[CurrentElement & 0xF];
9547         Swap = CurrentElement < BytesInVector;
9548       }
9549       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9550       FoundCandidate = true;
9551       break;
9552     }
9553   }
9554 
9555   if (!FoundCandidate)
9556     return SDValue();
9557 
9558   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9559   // optionally with VECSHL if shift is required.
9560   if (Swap)
9561     std::swap(V1, V2);
9562   if (V2.isUndef())
9563     V2 = V1;
9564   if (ShiftElts) {
9565     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9566                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9567     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9568                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9569   }
9570   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9571                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9572 }
9573 
9574 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9575 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9576 /// SDValue.
9577 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9578                                            SelectionDAG &DAG) const {
9579   const unsigned NumHalfWords = 8;
9580   const unsigned BytesInVector = NumHalfWords * 2;
9581   // Check that the shuffle is on half-words.
9582   if (!isNByteElemShuffleMask(N, 2, 1))
9583     return SDValue();
9584 
9585   bool IsLE = Subtarget.isLittleEndian();
9586   SDLoc dl(N);
9587   SDValue V1 = N->getOperand(0);
9588   SDValue V2 = N->getOperand(1);
9589   unsigned ShiftElts = 0, InsertAtByte = 0;
9590   bool Swap = false;
9591 
9592   // Shifts required to get the half-word we want at element 3.
9593   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9594   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9595 
9596   uint32_t Mask = 0;
9597   uint32_t OriginalOrderLow = 0x1234567;
9598   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9599   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9600   // 32-bit space, only need 4-bit nibbles per element.
9601   for (unsigned i = 0; i < NumHalfWords; ++i) {
9602     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9603     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9604   }
9605 
9606   // For each mask element, find out if we're just inserting something
9607   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9608   // from V2 into V1:
9609   //   X, 1, 2, 3, 4, 5, 6, 7
9610   //   0, X, 2, 3, 4, 5, 6, 7
9611   //   0, 1, X, 3, 4, 5, 6, 7
9612   //   0, 1, 2, X, 4, 5, 6, 7
9613   //   0, 1, 2, 3, X, 5, 6, 7
9614   //   0, 1, 2, 3, 4, X, 6, 7
9615   //   0, 1, 2, 3, 4, 5, X, 7
9616   //   0, 1, 2, 3, 4, 5, 6, X
9617   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9618 
9619   bool FoundCandidate = false;
9620   // Go through the mask of half-words to find an element that's being moved
9621   // from one vector to the other.
9622   for (unsigned i = 0; i < NumHalfWords; ++i) {
9623     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9624     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9625     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9626     uint32_t TargetOrder = 0x0;
9627 
9628     // If both vector operands for the shuffle are the same vector, the mask
9629     // will contain only elements from the first one and the second one will be
9630     // undef.
9631     if (V2.isUndef()) {
9632       ShiftElts = 0;
9633       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9634       TargetOrder = OriginalOrderLow;
9635       Swap = false;
9636       // Skip if not the correct element or mask of other elements don't equal
9637       // to our expected order.
9638       if (MaskOneElt == VINSERTHSrcElem &&
9639           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9640         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9641         FoundCandidate = true;
9642         break;
9643       }
9644     } else { // If both operands are defined.
9645       // Target order is [8,15] if the current mask is between [0,7].
9646       TargetOrder =
9647           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9648       // Skip if mask of other elements don't equal our expected order.
9649       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9650         // We only need the last 3 bits for the number of shifts.
9651         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9652                          : BigEndianShifts[MaskOneElt & 0x7];
9653         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9654         Swap = MaskOneElt < NumHalfWords;
9655         FoundCandidate = true;
9656         break;
9657       }
9658     }
9659   }
9660 
9661   if (!FoundCandidate)
9662     return SDValue();
9663 
9664   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9665   // optionally with VECSHL if shift is required.
9666   if (Swap)
9667     std::swap(V1, V2);
9668   if (V2.isUndef())
9669     V2 = V1;
9670   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9671   if (ShiftElts) {
9672     // Double ShiftElts because we're left shifting on v16i8 type.
9673     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9674                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9675     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9676     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9677                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9678     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9679   }
9680   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9681   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9682                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9683   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9684 }
9685 
9686 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9687 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9688 /// return the default SDValue.
9689 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9690                                               SelectionDAG &DAG) const {
9691   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9692   // to v16i8. Peek through the bitcasts to get the actual operands.
9693   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9694   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9695 
9696   auto ShuffleMask = SVN->getMask();
9697   SDValue VecShuffle(SVN, 0);
9698   SDLoc DL(SVN);
9699 
9700   // Check that we have a four byte shuffle.
9701   if (!isNByteElemShuffleMask(SVN, 4, 1))
9702     return SDValue();
9703 
9704   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9705   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9706     std::swap(LHS, RHS);
9707     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9708     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9709   }
9710 
9711   // Ensure that the RHS is a vector of constants.
9712   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9713   if (!BVN)
9714     return SDValue();
9715 
9716   // Check if RHS is a splat of 4-bytes (or smaller).
9717   APInt APSplatValue, APSplatUndef;
9718   unsigned SplatBitSize;
9719   bool HasAnyUndefs;
9720   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9721                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9722       SplatBitSize > 32)
9723     return SDValue();
9724 
9725   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9726   // The instruction splats a constant C into two words of the source vector
9727   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9728   // Thus we check that the shuffle mask is the equivalent  of
9729   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9730   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9731   // within each word are consecutive, so we only need to check the first byte.
9732   SDValue Index;
9733   bool IsLE = Subtarget.isLittleEndian();
9734   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9735       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9736        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9737     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9738   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9739            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9740             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9741     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9742   else
9743     return SDValue();
9744 
9745   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9746   // for XXSPLTI32DX.
9747   unsigned SplatVal = APSplatValue.getZExtValue();
9748   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9749     SplatVal |= (SplatVal << SplatBitSize);
9750 
9751   SDValue SplatNode = DAG.getNode(
9752       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9753       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9754   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9755 }
9756 
9757 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9758 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9759 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9760 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9761 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9762   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9763   assert(Op.getValueType() == MVT::v1i128 &&
9764          "Only set v1i128 as custom, other type shouldn't reach here!");
9765   SDLoc dl(Op);
9766   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9767   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9768   unsigned SHLAmt = N1.getConstantOperandVal(0);
9769   if (SHLAmt % 8 == 0) {
9770     SmallVector<int, 16> Mask(16, 0);
9771     std::iota(Mask.begin(), Mask.end(), 0);
9772     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9773     if (SDValue Shuffle =
9774             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9775                                  DAG.getUNDEF(MVT::v16i8), Mask))
9776       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9777   }
9778   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9779   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9780                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9781   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9782                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9783   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9784   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9785 }
9786 
9787 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9788 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9789 /// return the code it can be lowered into.  Worst case, it can always be
9790 /// lowered into a vperm.
9791 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9792                                                SelectionDAG &DAG) const {
9793   SDLoc dl(Op);
9794   SDValue V1 = Op.getOperand(0);
9795   SDValue V2 = Op.getOperand(1);
9796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9797 
9798   // Any nodes that were combined in the target-independent combiner prior
9799   // to vector legalization will not be sent to the target combine. Try to
9800   // combine it here.
9801   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9802     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9803       return NewShuffle;
9804     Op = NewShuffle;
9805     SVOp = cast<ShuffleVectorSDNode>(Op);
9806     V1 = Op.getOperand(0);
9807     V2 = Op.getOperand(1);
9808   }
9809   EVT VT = Op.getValueType();
9810   bool isLittleEndian = Subtarget.isLittleEndian();
9811 
9812   unsigned ShiftElts, InsertAtByte;
9813   bool Swap = false;
9814 
9815   // If this is a load-and-splat, we can do that with a single instruction
9816   // in some cases. However if the load has multiple uses, we don't want to
9817   // combine it because that will just produce multiple loads.
9818   bool IsPermutedLoad = false;
9819   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9820   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9821       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9822       InputLoad->hasOneUse()) {
9823     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9824     int SplatIdx =
9825       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9826 
9827     // The splat index for permuted loads will be in the left half of the vector
9828     // which is strictly wider than the loaded value by 8 bytes. So we need to
9829     // adjust the splat index to point to the correct address in memory.
9830     if (IsPermutedLoad) {
9831       assert((isLittleEndian || IsFourByte) &&
9832              "Unexpected size for permuted load on big endian target");
9833       SplatIdx += IsFourByte ? 2 : 1;
9834       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9835              "Splat of a value outside of the loaded memory");
9836     }
9837 
9838     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9839     // For 4-byte load-and-splat, we need Power9.
9840     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9841       uint64_t Offset = 0;
9842       if (IsFourByte)
9843         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9844       else
9845         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9846 
9847       // If the width of the load is the same as the width of the splat,
9848       // loading with an offset would load the wrong memory.
9849       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9850         Offset = 0;
9851 
9852       SDValue BasePtr = LD->getBasePtr();
9853       if (Offset != 0)
9854         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9855                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9856       SDValue Ops[] = {
9857         LD->getChain(),    // Chain
9858         BasePtr,           // BasePtr
9859         DAG.getValueType(Op.getValueType()) // VT
9860       };
9861       SDVTList VTL =
9862         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9863       SDValue LdSplt =
9864         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9865                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9866       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9867       if (LdSplt.getValueType() != SVOp->getValueType(0))
9868         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9869       return LdSplt;
9870     }
9871   }
9872   if (Subtarget.hasP9Vector() &&
9873       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9874                            isLittleEndian)) {
9875     if (Swap)
9876       std::swap(V1, V2);
9877     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9878     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9879     if (ShiftElts) {
9880       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9881                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9882       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9883                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9884       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9885     }
9886     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9887                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9888     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9889   }
9890 
9891   if (Subtarget.hasPrefixInstrs()) {
9892     SDValue SplatInsertNode;
9893     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9894       return SplatInsertNode;
9895   }
9896 
9897   if (Subtarget.hasP9Altivec()) {
9898     SDValue NewISDNode;
9899     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9900       return NewISDNode;
9901 
9902     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9903       return NewISDNode;
9904   }
9905 
9906   if (Subtarget.hasVSX() &&
9907       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9908     if (Swap)
9909       std::swap(V1, V2);
9910     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9911     SDValue Conv2 =
9912         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9913 
9914     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9915                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9916     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9917   }
9918 
9919   if (Subtarget.hasVSX() &&
9920     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9921     if (Swap)
9922       std::swap(V1, V2);
9923     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9924     SDValue Conv2 =
9925         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9926 
9927     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9928                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9929     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9930   }
9931 
9932   if (Subtarget.hasP9Vector()) {
9933      if (PPC::isXXBRHShuffleMask(SVOp)) {
9934       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9935       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9936       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9937     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9938       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9939       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9940       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9941     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9942       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9943       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9944       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9945     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9946       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9947       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9948       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9949     }
9950   }
9951 
9952   if (Subtarget.hasVSX()) {
9953     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9954       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9955 
9956       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9957       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9958                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9959       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9960     }
9961 
9962     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9963     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9964       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9965       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9966       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9967     }
9968   }
9969 
9970   // Cases that are handled by instructions that take permute immediates
9971   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9972   // selected by the instruction selector.
9973   if (V2.isUndef()) {
9974     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9975         PPC::isSplatShuffleMask(SVOp, 2) ||
9976         PPC::isSplatShuffleMask(SVOp, 4) ||
9977         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9978         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9979         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9980         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9981         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9982         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9983         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9984         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9985         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9986         (Subtarget.hasP8Altivec() && (
9987          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9988          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9989          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9990       return Op;
9991     }
9992   }
9993 
9994   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9995   // and produce a fixed permutation.  If any of these match, do not lower to
9996   // VPERM.
9997   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9998   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9999       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10000       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10001       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10002       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10003       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10004       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10005       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10006       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10007       (Subtarget.hasP8Altivec() && (
10008        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10009        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10010        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10011     return Op;
10012 
10013   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10014   // perfect shuffle table to emit an optimal matching sequence.
10015   ArrayRef<int> PermMask = SVOp->getMask();
10016 
10017   unsigned PFIndexes[4];
10018   bool isFourElementShuffle = true;
10019   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
10020     unsigned EltNo = 8;   // Start out undef.
10021     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
10022       if (PermMask[i*4+j] < 0)
10023         continue;   // Undef, ignore it.
10024 
10025       unsigned ByteSource = PermMask[i*4+j];
10026       if ((ByteSource & 3) != j) {
10027         isFourElementShuffle = false;
10028         break;
10029       }
10030 
10031       if (EltNo == 8) {
10032         EltNo = ByteSource/4;
10033       } else if (EltNo != ByteSource/4) {
10034         isFourElementShuffle = false;
10035         break;
10036       }
10037     }
10038     PFIndexes[i] = EltNo;
10039   }
10040 
10041   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10042   // perfect shuffle vector to determine if it is cost effective to do this as
10043   // discrete instructions, or whether we should use a vperm.
10044   // For now, we skip this for little endian until such time as we have a
10045   // little-endian perfect shuffle table.
10046   if (isFourElementShuffle && !isLittleEndian) {
10047     // Compute the index in the perfect shuffle table.
10048     unsigned PFTableIndex =
10049       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10050 
10051     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10052     unsigned Cost  = (PFEntry >> 30);
10053 
10054     // Determining when to avoid vperm is tricky.  Many things affect the cost
10055     // of vperm, particularly how many times the perm mask needs to be computed.
10056     // For example, if the perm mask can be hoisted out of a loop or is already
10057     // used (perhaps because there are multiple permutes with the same shuffle
10058     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10059     // the loop requires an extra register.
10060     //
10061     // As a compromise, we only emit discrete instructions if the shuffle can be
10062     // generated in 3 or fewer operations.  When we have loop information
10063     // available, if this block is within a loop, we should avoid using vperm
10064     // for 3-operation perms and use a constant pool load instead.
10065     if (Cost < 3)
10066       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10067   }
10068 
10069   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10070   // vector that will get spilled to the constant pool.
10071   if (V2.isUndef()) V2 = V1;
10072 
10073   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10074   // that it is in input element units, not in bytes.  Convert now.
10075 
10076   // For little endian, the order of the input vectors is reversed, and
10077   // the permutation mask is complemented with respect to 31.  This is
10078   // necessary to produce proper semantics with the big-endian-biased vperm
10079   // instruction.
10080   EVT EltVT = V1.getValueType().getVectorElementType();
10081   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10082 
10083   SmallVector<SDValue, 16> ResultMask;
10084   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10085     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10086 
10087     for (unsigned j = 0; j != BytesPerElement; ++j)
10088       if (isLittleEndian)
10089         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10090                                              dl, MVT::i32));
10091       else
10092         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10093                                              MVT::i32));
10094   }
10095 
10096   ShufflesHandledWithVPERM++;
10097   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10098   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10099   LLVM_DEBUG(SVOp->dump());
10100   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10101   LLVM_DEBUG(VPermMask.dump());
10102 
10103   if (isLittleEndian)
10104     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10105                        V2, V1, VPermMask);
10106   else
10107     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10108                        V1, V2, VPermMask);
10109 }
10110 
10111 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10112 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10113 /// information about the intrinsic.
10114 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10115                                  bool &isDot, const PPCSubtarget &Subtarget) {
10116   unsigned IntrinsicID =
10117       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10118   CompareOpc = -1;
10119   isDot = false;
10120   switch (IntrinsicID) {
10121   default:
10122     return false;
10123   // Comparison predicates.
10124   case Intrinsic::ppc_altivec_vcmpbfp_p:
10125     CompareOpc = 966;
10126     isDot = true;
10127     break;
10128   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10129     CompareOpc = 198;
10130     isDot = true;
10131     break;
10132   case Intrinsic::ppc_altivec_vcmpequb_p:
10133     CompareOpc = 6;
10134     isDot = true;
10135     break;
10136   case Intrinsic::ppc_altivec_vcmpequh_p:
10137     CompareOpc = 70;
10138     isDot = true;
10139     break;
10140   case Intrinsic::ppc_altivec_vcmpequw_p:
10141     CompareOpc = 134;
10142     isDot = true;
10143     break;
10144   case Intrinsic::ppc_altivec_vcmpequd_p:
10145     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10146       CompareOpc = 199;
10147       isDot = true;
10148     } else
10149       return false;
10150     break;
10151   case Intrinsic::ppc_altivec_vcmpneb_p:
10152   case Intrinsic::ppc_altivec_vcmpneh_p:
10153   case Intrinsic::ppc_altivec_vcmpnew_p:
10154   case Intrinsic::ppc_altivec_vcmpnezb_p:
10155   case Intrinsic::ppc_altivec_vcmpnezh_p:
10156   case Intrinsic::ppc_altivec_vcmpnezw_p:
10157     if (Subtarget.hasP9Altivec()) {
10158       switch (IntrinsicID) {
10159       default:
10160         llvm_unreachable("Unknown comparison intrinsic.");
10161       case Intrinsic::ppc_altivec_vcmpneb_p:
10162         CompareOpc = 7;
10163         break;
10164       case Intrinsic::ppc_altivec_vcmpneh_p:
10165         CompareOpc = 71;
10166         break;
10167       case Intrinsic::ppc_altivec_vcmpnew_p:
10168         CompareOpc = 135;
10169         break;
10170       case Intrinsic::ppc_altivec_vcmpnezb_p:
10171         CompareOpc = 263;
10172         break;
10173       case Intrinsic::ppc_altivec_vcmpnezh_p:
10174         CompareOpc = 327;
10175         break;
10176       case Intrinsic::ppc_altivec_vcmpnezw_p:
10177         CompareOpc = 391;
10178         break;
10179       }
10180       isDot = true;
10181     } else
10182       return false;
10183     break;
10184   case Intrinsic::ppc_altivec_vcmpgefp_p:
10185     CompareOpc = 454;
10186     isDot = true;
10187     break;
10188   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10189     CompareOpc = 710;
10190     isDot = true;
10191     break;
10192   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10193     CompareOpc = 774;
10194     isDot = true;
10195     break;
10196   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10197     CompareOpc = 838;
10198     isDot = true;
10199     break;
10200   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10201     CompareOpc = 902;
10202     isDot = true;
10203     break;
10204   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10205     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10206       CompareOpc = 967;
10207       isDot = true;
10208     } else
10209       return false;
10210     break;
10211   case Intrinsic::ppc_altivec_vcmpgtub_p:
10212     CompareOpc = 518;
10213     isDot = true;
10214     break;
10215   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10216     CompareOpc = 582;
10217     isDot = true;
10218     break;
10219   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10220     CompareOpc = 646;
10221     isDot = true;
10222     break;
10223   case Intrinsic::ppc_altivec_vcmpgtud_p:
10224     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10225       CompareOpc = 711;
10226       isDot = true;
10227     } else
10228       return false;
10229     break;
10230 
10231   case Intrinsic::ppc_altivec_vcmpequq:
10232   case Intrinsic::ppc_altivec_vcmpgtsq:
10233   case Intrinsic::ppc_altivec_vcmpgtuq:
10234     if (!Subtarget.isISA3_1())
10235       return false;
10236     switch (IntrinsicID) {
10237     default:
10238       llvm_unreachable("Unknown comparison intrinsic.");
10239     case Intrinsic::ppc_altivec_vcmpequq:
10240       CompareOpc = 455;
10241       break;
10242     case Intrinsic::ppc_altivec_vcmpgtsq:
10243       CompareOpc = 903;
10244       break;
10245     case Intrinsic::ppc_altivec_vcmpgtuq:
10246       CompareOpc = 647;
10247       break;
10248     }
10249     break;
10250 
10251   // VSX predicate comparisons use the same infrastructure
10252   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10253   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10254   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10255   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10256   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10257   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10258     if (Subtarget.hasVSX()) {
10259       switch (IntrinsicID) {
10260       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10261         CompareOpc = 99;
10262         break;
10263       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10264         CompareOpc = 115;
10265         break;
10266       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10267         CompareOpc = 107;
10268         break;
10269       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10270         CompareOpc = 67;
10271         break;
10272       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10273         CompareOpc = 83;
10274         break;
10275       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10276         CompareOpc = 75;
10277         break;
10278       }
10279       isDot = true;
10280     } else
10281       return false;
10282     break;
10283 
10284   // Normal Comparisons.
10285   case Intrinsic::ppc_altivec_vcmpbfp:
10286     CompareOpc = 966;
10287     break;
10288   case Intrinsic::ppc_altivec_vcmpeqfp:
10289     CompareOpc = 198;
10290     break;
10291   case Intrinsic::ppc_altivec_vcmpequb:
10292     CompareOpc = 6;
10293     break;
10294   case Intrinsic::ppc_altivec_vcmpequh:
10295     CompareOpc = 70;
10296     break;
10297   case Intrinsic::ppc_altivec_vcmpequw:
10298     CompareOpc = 134;
10299     break;
10300   case Intrinsic::ppc_altivec_vcmpequd:
10301     if (Subtarget.hasP8Altivec())
10302       CompareOpc = 199;
10303     else
10304       return false;
10305     break;
10306   case Intrinsic::ppc_altivec_vcmpneb:
10307   case Intrinsic::ppc_altivec_vcmpneh:
10308   case Intrinsic::ppc_altivec_vcmpnew:
10309   case Intrinsic::ppc_altivec_vcmpnezb:
10310   case Intrinsic::ppc_altivec_vcmpnezh:
10311   case Intrinsic::ppc_altivec_vcmpnezw:
10312     if (Subtarget.hasP9Altivec())
10313       switch (IntrinsicID) {
10314       default:
10315         llvm_unreachable("Unknown comparison intrinsic.");
10316       case Intrinsic::ppc_altivec_vcmpneb:
10317         CompareOpc = 7;
10318         break;
10319       case Intrinsic::ppc_altivec_vcmpneh:
10320         CompareOpc = 71;
10321         break;
10322       case Intrinsic::ppc_altivec_vcmpnew:
10323         CompareOpc = 135;
10324         break;
10325       case Intrinsic::ppc_altivec_vcmpnezb:
10326         CompareOpc = 263;
10327         break;
10328       case Intrinsic::ppc_altivec_vcmpnezh:
10329         CompareOpc = 327;
10330         break;
10331       case Intrinsic::ppc_altivec_vcmpnezw:
10332         CompareOpc = 391;
10333         break;
10334       }
10335     else
10336       return false;
10337     break;
10338   case Intrinsic::ppc_altivec_vcmpgefp:
10339     CompareOpc = 454;
10340     break;
10341   case Intrinsic::ppc_altivec_vcmpgtfp:
10342     CompareOpc = 710;
10343     break;
10344   case Intrinsic::ppc_altivec_vcmpgtsb:
10345     CompareOpc = 774;
10346     break;
10347   case Intrinsic::ppc_altivec_vcmpgtsh:
10348     CompareOpc = 838;
10349     break;
10350   case Intrinsic::ppc_altivec_vcmpgtsw:
10351     CompareOpc = 902;
10352     break;
10353   case Intrinsic::ppc_altivec_vcmpgtsd:
10354     if (Subtarget.hasP8Altivec())
10355       CompareOpc = 967;
10356     else
10357       return false;
10358     break;
10359   case Intrinsic::ppc_altivec_vcmpgtub:
10360     CompareOpc = 518;
10361     break;
10362   case Intrinsic::ppc_altivec_vcmpgtuh:
10363     CompareOpc = 582;
10364     break;
10365   case Intrinsic::ppc_altivec_vcmpgtuw:
10366     CompareOpc = 646;
10367     break;
10368   case Intrinsic::ppc_altivec_vcmpgtud:
10369     if (Subtarget.hasP8Altivec())
10370       CompareOpc = 711;
10371     else
10372       return false;
10373     break;
10374   case Intrinsic::ppc_altivec_vcmpequq_p:
10375   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10376   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10377     if (!Subtarget.isISA3_1())
10378       return false;
10379     switch (IntrinsicID) {
10380     default:
10381       llvm_unreachable("Unknown comparison intrinsic.");
10382     case Intrinsic::ppc_altivec_vcmpequq_p:
10383       CompareOpc = 455;
10384       break;
10385     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10386       CompareOpc = 903;
10387       break;
10388     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10389       CompareOpc = 647;
10390       break;
10391     }
10392     isDot = true;
10393     break;
10394   }
10395   return true;
10396 }
10397 
10398 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10399 /// lower, do it, otherwise return null.
10400 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10401                                                    SelectionDAG &DAG) const {
10402   unsigned IntrinsicID =
10403     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10404 
10405   SDLoc dl(Op);
10406 
10407   switch (IntrinsicID) {
10408   case Intrinsic::thread_pointer:
10409     // Reads the thread pointer register, used for __builtin_thread_pointer.
10410     if (Subtarget.isPPC64())
10411       return DAG.getRegister(PPC::X13, MVT::i64);
10412     return DAG.getRegister(PPC::R2, MVT::i32);
10413 
10414   case Intrinsic::ppc_mma_disassemble_acc:
10415   case Intrinsic::ppc_vsx_disassemble_pair: {
10416     int NumVecs = 2;
10417     SDValue WideVec = Op.getOperand(1);
10418     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10419       NumVecs = 4;
10420       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10421     }
10422     SmallVector<SDValue, 4> RetOps;
10423     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10424       SDValue Extract = DAG.getNode(
10425           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10426           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10427                                                      : VecNo,
10428                           dl, getPointerTy(DAG.getDataLayout())));
10429       RetOps.push_back(Extract);
10430     }
10431     return DAG.getMergeValues(RetOps, dl);
10432   }
10433 
10434   case Intrinsic::ppc_unpack_longdouble: {
10435     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10436     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10437            "Argument of long double unpack must be 0 or 1!");
10438     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10439                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10440                                        Idx->getValueType(0)));
10441   }
10442 
10443   case Intrinsic::ppc_compare_exp_lt:
10444   case Intrinsic::ppc_compare_exp_gt:
10445   case Intrinsic::ppc_compare_exp_eq:
10446   case Intrinsic::ppc_compare_exp_uo: {
10447     unsigned Pred;
10448     switch (IntrinsicID) {
10449     case Intrinsic::ppc_compare_exp_lt:
10450       Pred = PPC::PRED_LT;
10451       break;
10452     case Intrinsic::ppc_compare_exp_gt:
10453       Pred = PPC::PRED_GT;
10454       break;
10455     case Intrinsic::ppc_compare_exp_eq:
10456       Pred = PPC::PRED_EQ;
10457       break;
10458     case Intrinsic::ppc_compare_exp_uo:
10459       Pred = PPC::PRED_UN;
10460       break;
10461     }
10462     return SDValue(
10463         DAG.getMachineNode(
10464             PPC::SELECT_CC_I4, dl, MVT::i32,
10465             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10466                                         Op.getOperand(1), Op.getOperand(2)),
10467                      0),
10468              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10469              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10470         0);
10471   }
10472   case Intrinsic::ppc_test_data_class_d:
10473   case Intrinsic::ppc_test_data_class_f: {
10474     unsigned CmprOpc = PPC::XSTSTDCDP;
10475     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10476       CmprOpc = PPC::XSTSTDCSP;
10477     return SDValue(
10478         DAG.getMachineNode(
10479             PPC::SELECT_CC_I4, dl, MVT::i32,
10480             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10481                                         Op.getOperand(1)),
10482                      0),
10483              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10484              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10485         0);
10486   }
10487   }
10488 
10489   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10490   // opcode number of the comparison.
10491   int CompareOpc;
10492   bool isDot;
10493   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10494     return SDValue();    // Don't custom lower most intrinsics.
10495 
10496   // If this is a non-dot comparison, make the VCMP node and we are done.
10497   if (!isDot) {
10498     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10499                               Op.getOperand(1), Op.getOperand(2),
10500                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10501     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10502   }
10503 
10504   // Create the PPCISD altivec 'dot' comparison node.
10505   SDValue Ops[] = {
10506     Op.getOperand(2),  // LHS
10507     Op.getOperand(3),  // RHS
10508     DAG.getConstant(CompareOpc, dl, MVT::i32)
10509   };
10510   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10511   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10512 
10513   // Now that we have the comparison, emit a copy from the CR to a GPR.
10514   // This is flagged to the above dot comparison.
10515   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10516                                 DAG.getRegister(PPC::CR6, MVT::i32),
10517                                 CompNode.getValue(1));
10518 
10519   // Unpack the result based on how the target uses it.
10520   unsigned BitNo;   // Bit # of CR6.
10521   bool InvertBit;   // Invert result?
10522   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10523   default:  // Can't happen, don't crash on invalid number though.
10524   case 0:   // Return the value of the EQ bit of CR6.
10525     BitNo = 0; InvertBit = false;
10526     break;
10527   case 1:   // Return the inverted value of the EQ bit of CR6.
10528     BitNo = 0; InvertBit = true;
10529     break;
10530   case 2:   // Return the value of the LT bit of CR6.
10531     BitNo = 2; InvertBit = false;
10532     break;
10533   case 3:   // Return the inverted value of the LT bit of CR6.
10534     BitNo = 2; InvertBit = true;
10535     break;
10536   }
10537 
10538   // Shift the bit into the low position.
10539   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10540                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10541   // Isolate the bit.
10542   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10543                       DAG.getConstant(1, dl, MVT::i32));
10544 
10545   // If we are supposed to, toggle the bit.
10546   if (InvertBit)
10547     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10548                         DAG.getConstant(1, dl, MVT::i32));
10549   return Flags;
10550 }
10551 
10552 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10553                                                SelectionDAG &DAG) const {
10554   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10555   // the beginning of the argument list.
10556   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10557   SDLoc DL(Op);
10558   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10559   case Intrinsic::ppc_cfence: {
10560     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10561     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10562     SDValue Val = Op.getOperand(ArgStart + 1);
10563     EVT Ty = Val.getValueType();
10564     if (Ty == MVT::i128) {
10565       // FIXME: Testing one of two paired registers is sufficient to guarantee
10566       // ordering?
10567       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10568     }
10569     return SDValue(
10570         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10571                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10572                            Op.getOperand(0)),
10573         0);
10574   }
10575   default:
10576     break;
10577   }
10578   return SDValue();
10579 }
10580 
10581 // Lower scalar BSWAP64 to xxbrd.
10582 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10583   SDLoc dl(Op);
10584   if (!Subtarget.isPPC64())
10585     return Op;
10586   // MTVSRDD
10587   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10588                    Op.getOperand(0));
10589   // XXBRD
10590   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10591   // MFVSRD
10592   int VectorIndex = 0;
10593   if (Subtarget.isLittleEndian())
10594     VectorIndex = 1;
10595   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10596                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10597   return Op;
10598 }
10599 
10600 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10601 // compared to a value that is atomically loaded (atomic loads zero-extend).
10602 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10603                                                 SelectionDAG &DAG) const {
10604   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10605          "Expecting an atomic compare-and-swap here.");
10606   SDLoc dl(Op);
10607   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10608   EVT MemVT = AtomicNode->getMemoryVT();
10609   if (MemVT.getSizeInBits() >= 32)
10610     return Op;
10611 
10612   SDValue CmpOp = Op.getOperand(2);
10613   // If this is already correctly zero-extended, leave it alone.
10614   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10615   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10616     return Op;
10617 
10618   // Clear the high bits of the compare operand.
10619   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10620   SDValue NewCmpOp =
10621     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10622                 DAG.getConstant(MaskVal, dl, MVT::i32));
10623 
10624   // Replace the existing compare operand with the properly zero-extended one.
10625   SmallVector<SDValue, 4> Ops;
10626   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10627     Ops.push_back(AtomicNode->getOperand(i));
10628   Ops[2] = NewCmpOp;
10629   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10630   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10631   auto NodeTy =
10632     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10633   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10634 }
10635 
10636 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10637                                                   SelectionDAG &DAG) const {
10638   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10639   EVT MemVT = N->getMemoryVT();
10640   assert(MemVT.getSimpleVT() == MVT::i128 &&
10641          "Expect quadword atomic operations");
10642   SDLoc dl(N);
10643   unsigned Opc = N->getOpcode();
10644   switch (Opc) {
10645   case ISD::ATOMIC_LOAD: {
10646     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10647     // lowered to ppc instructions by pattern matching instruction selector.
10648     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10649     SmallVector<SDValue, 4> Ops{
10650         N->getOperand(0),
10651         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10652     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10653       Ops.push_back(N->getOperand(I));
10654     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10655                                                 Ops, MemVT, N->getMemOperand());
10656     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10657     SDValue ValHi =
10658         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10659     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10660                         DAG.getConstant(64, dl, MVT::i32));
10661     SDValue Val =
10662         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10663     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10664                        {Val, LoadedVal.getValue(2)});
10665   }
10666   case ISD::ATOMIC_STORE: {
10667     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10668     // lowered to ppc instructions by pattern matching instruction selector.
10669     SDVTList Tys = DAG.getVTList(MVT::Other);
10670     SmallVector<SDValue, 4> Ops{
10671         N->getOperand(0),
10672         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10673     SDValue Val = N->getOperand(2);
10674     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10675     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10676                                 DAG.getConstant(64, dl, MVT::i32));
10677     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10678     Ops.push_back(ValLo);
10679     Ops.push_back(ValHi);
10680     Ops.push_back(N->getOperand(1));
10681     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10682                                    N->getMemOperand());
10683   }
10684   default:
10685     llvm_unreachable("Unexpected atomic opcode");
10686   }
10687 }
10688 
10689 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10690                                                  SelectionDAG &DAG) const {
10691   SDLoc dl(Op);
10692   // Create a stack slot that is 16-byte aligned.
10693   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10694   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10695   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10696   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10697 
10698   // Store the input value into Value#0 of the stack slot.
10699   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10700                                MachinePointerInfo());
10701   // Load it out.
10702   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10703 }
10704 
10705 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10706                                                   SelectionDAG &DAG) const {
10707   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10708          "Should only be called for ISD::INSERT_VECTOR_ELT");
10709 
10710   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10711 
10712   EVT VT = Op.getValueType();
10713   SDLoc dl(Op);
10714   SDValue V1 = Op.getOperand(0);
10715   SDValue V2 = Op.getOperand(1);
10716   SDValue V3 = Op.getOperand(2);
10717 
10718   if (VT == MVT::v2f64 && C)
10719     return Op;
10720 
10721   if (Subtarget.isISA3_1()) {
10722     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10723       return SDValue();
10724     // On P10, we have legal lowering for constant and variable indices for
10725     // integer vectors.
10726     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10727         VT == MVT::v2i64)
10728       return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10729     // For f32 and f64 vectors, we have legal lowering for variable indices.
10730     // For f32 we also have legal lowering when the element is loaded from
10731     // memory.
10732     if (VT == MVT::v4f32 || VT == MVT::v2f64) {
10733       if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2)))
10734         return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10735       return Op;
10736     }
10737   }
10738 
10739   // Before P10, we have legal lowering for constant indices but not for
10740   // variable ones.
10741   if (!C)
10742     return SDValue();
10743 
10744   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10745   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10746     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10747     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10748     unsigned InsertAtElement = C->getZExtValue();
10749     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10750     if (Subtarget.isLittleEndian()) {
10751       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10752     }
10753     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10754                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10755   }
10756   return Op;
10757 }
10758 
10759 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10760                                            SelectionDAG &DAG) const {
10761   SDLoc dl(Op);
10762   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10763   SDValue LoadChain = LN->getChain();
10764   SDValue BasePtr = LN->getBasePtr();
10765   EVT VT = Op.getValueType();
10766 
10767   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10768     return Op;
10769 
10770   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10771   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10772   // 2 or 4 vsx registers.
10773   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10774          "Type unsupported without MMA");
10775   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10776          "Type unsupported without paired vector support");
10777   Align Alignment = LN->getAlign();
10778   SmallVector<SDValue, 4> Loads;
10779   SmallVector<SDValue, 4> LoadChains;
10780   unsigned NumVecs = VT.getSizeInBits() / 128;
10781   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10782     SDValue Load =
10783         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10784                     LN->getPointerInfo().getWithOffset(Idx * 16),
10785                     commonAlignment(Alignment, Idx * 16),
10786                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10787     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10788                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10789     Loads.push_back(Load);
10790     LoadChains.push_back(Load.getValue(1));
10791   }
10792   if (Subtarget.isLittleEndian()) {
10793     std::reverse(Loads.begin(), Loads.end());
10794     std::reverse(LoadChains.begin(), LoadChains.end());
10795   }
10796   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10797   SDValue Value =
10798       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10799                   dl, VT, Loads);
10800   SDValue RetOps[] = {Value, TF};
10801   return DAG.getMergeValues(RetOps, dl);
10802 }
10803 
10804 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10805                                             SelectionDAG &DAG) const {
10806   SDLoc dl(Op);
10807   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10808   SDValue StoreChain = SN->getChain();
10809   SDValue BasePtr = SN->getBasePtr();
10810   SDValue Value = SN->getValue();
10811   EVT StoreVT = Value.getValueType();
10812 
10813   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10814     return Op;
10815 
10816   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10817   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10818   // underlying registers individually.
10819   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10820          "Type unsupported without MMA");
10821   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10822          "Type unsupported without paired vector support");
10823   Align Alignment = SN->getAlign();
10824   SmallVector<SDValue, 4> Stores;
10825   unsigned NumVecs = 2;
10826   if (StoreVT == MVT::v512i1) {
10827     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10828     NumVecs = 4;
10829   }
10830   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10831     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10832     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10833                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10834     SDValue Store =
10835         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10836                      SN->getPointerInfo().getWithOffset(Idx * 16),
10837                      commonAlignment(Alignment, Idx * 16),
10838                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10839     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10840                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10841     Stores.push_back(Store);
10842   }
10843   SDValue TF = DAG.getTokenFactor(dl, Stores);
10844   return TF;
10845 }
10846 
10847 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10848   SDLoc dl(Op);
10849   if (Op.getValueType() == MVT::v4i32) {
10850     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10851 
10852     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10853     // +16 as shift amt.
10854     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10855     SDValue RHSSwap =   // = vrlw RHS, 16
10856       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10857 
10858     // Shrinkify inputs to v8i16.
10859     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10860     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10861     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10862 
10863     // Low parts multiplied together, generating 32-bit results (we ignore the
10864     // top parts).
10865     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10866                                         LHS, RHS, DAG, dl, MVT::v4i32);
10867 
10868     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10869                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10870     // Shift the high parts up 16 bits.
10871     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10872                               Neg16, DAG, dl);
10873     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10874   } else if (Op.getValueType() == MVT::v16i8) {
10875     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10876     bool isLittleEndian = Subtarget.isLittleEndian();
10877 
10878     // Multiply the even 8-bit parts, producing 16-bit sums.
10879     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10880                                            LHS, RHS, DAG, dl, MVT::v8i16);
10881     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10882 
10883     // Multiply the odd 8-bit parts, producing 16-bit sums.
10884     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10885                                           LHS, RHS, DAG, dl, MVT::v8i16);
10886     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10887 
10888     // Merge the results together.  Because vmuleub and vmuloub are
10889     // instructions with a big-endian bias, we must reverse the
10890     // element numbering and reverse the meaning of "odd" and "even"
10891     // when generating little endian code.
10892     int Ops[16];
10893     for (unsigned i = 0; i != 8; ++i) {
10894       if (isLittleEndian) {
10895         Ops[i*2  ] = 2*i;
10896         Ops[i*2+1] = 2*i+16;
10897       } else {
10898         Ops[i*2  ] = 2*i+1;
10899         Ops[i*2+1] = 2*i+1+16;
10900       }
10901     }
10902     if (isLittleEndian)
10903       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10904     else
10905       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10906   } else {
10907     llvm_unreachable("Unknown mul to lower!");
10908   }
10909 }
10910 
10911 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10912   bool IsStrict = Op->isStrictFPOpcode();
10913   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10914       !Subtarget.hasP9Vector())
10915     return SDValue();
10916 
10917   return Op;
10918 }
10919 
10920 // Custom lowering for fpext vf32 to v2f64
10921 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10922 
10923   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10924          "Should only be called for ISD::FP_EXTEND");
10925 
10926   // FIXME: handle extends from half precision float vectors on P9.
10927   // We only want to custom lower an extend from v2f32 to v2f64.
10928   if (Op.getValueType() != MVT::v2f64 ||
10929       Op.getOperand(0).getValueType() != MVT::v2f32)
10930     return SDValue();
10931 
10932   SDLoc dl(Op);
10933   SDValue Op0 = Op.getOperand(0);
10934 
10935   switch (Op0.getOpcode()) {
10936   default:
10937     return SDValue();
10938   case ISD::EXTRACT_SUBVECTOR: {
10939     assert(Op0.getNumOperands() == 2 &&
10940            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10941            "Node should have 2 operands with second one being a constant!");
10942 
10943     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10944       return SDValue();
10945 
10946     // Custom lower is only done for high or low doubleword.
10947     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10948     if (Idx % 2 != 0)
10949       return SDValue();
10950 
10951     // Since input is v4f32, at this point Idx is either 0 or 2.
10952     // Shift to get the doubleword position we want.
10953     int DWord = Idx >> 1;
10954 
10955     // High and low word positions are different on little endian.
10956     if (Subtarget.isLittleEndian())
10957       DWord ^= 0x1;
10958 
10959     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10960                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10961   }
10962   case ISD::FADD:
10963   case ISD::FMUL:
10964   case ISD::FSUB: {
10965     SDValue NewLoad[2];
10966     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10967       // Ensure both input are loads.
10968       SDValue LdOp = Op0.getOperand(i);
10969       if (LdOp.getOpcode() != ISD::LOAD)
10970         return SDValue();
10971       // Generate new load node.
10972       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10973       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10974       NewLoad[i] = DAG.getMemIntrinsicNode(
10975           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10976           LD->getMemoryVT(), LD->getMemOperand());
10977     }
10978     SDValue NewOp =
10979         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10980                     NewLoad[1], Op0.getNode()->getFlags());
10981     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10982                        DAG.getConstant(0, dl, MVT::i32));
10983   }
10984   case ISD::LOAD: {
10985     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10986     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10987     SDValue NewLd = DAG.getMemIntrinsicNode(
10988         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10989         LD->getMemoryVT(), LD->getMemOperand());
10990     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10991                        DAG.getConstant(0, dl, MVT::i32));
10992   }
10993   }
10994   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10995 }
10996 
10997 /// LowerOperation - Provide custom lowering hooks for some operations.
10998 ///
10999 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11000   switch (Op.getOpcode()) {
11001   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11002   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11003   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11004   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11005   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11006   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11007   case ISD::STRICT_FSETCC:
11008   case ISD::STRICT_FSETCCS:
11009   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11010   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11011   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11012 
11013   case ISD::INLINEASM:
11014   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11015   // Variable argument lowering.
11016   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11017   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11018   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11019 
11020   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11021   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11022   case ISD::GET_DYNAMIC_AREA_OFFSET:
11023     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11024 
11025   // Exception handling lowering.
11026   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11027   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11028   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11029 
11030   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11031   case ISD::STORE:              return LowerSTORE(Op, DAG);
11032   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11033   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11034   case ISD::STRICT_FP_TO_UINT:
11035   case ISD::STRICT_FP_TO_SINT:
11036   case ISD::FP_TO_UINT:
11037   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11038   case ISD::STRICT_UINT_TO_FP:
11039   case ISD::STRICT_SINT_TO_FP:
11040   case ISD::UINT_TO_FP:
11041   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11042   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11043 
11044   // Lower 64-bit shifts.
11045   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11046   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11047   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11048 
11049   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11050   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11051 
11052   // Vector-related lowering.
11053   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11054   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11055   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11056   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11057   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11058   case ISD::MUL:                return LowerMUL(Op, DAG);
11059   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11060   case ISD::STRICT_FP_ROUND:
11061   case ISD::FP_ROUND:
11062     return LowerFP_ROUND(Op, DAG);
11063   case ISD::ROTL:               return LowerROTL(Op, DAG);
11064 
11065   // For counter-based loop handling.
11066   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11067 
11068   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11069 
11070   // Frame & Return address.
11071   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11072   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11073 
11074   case ISD::INTRINSIC_VOID:
11075     return LowerINTRINSIC_VOID(Op, DAG);
11076   case ISD::BSWAP:
11077     return LowerBSWAP(Op, DAG);
11078   case ISD::ATOMIC_CMP_SWAP:
11079     return LowerATOMIC_CMP_SWAP(Op, DAG);
11080   case ISD::ATOMIC_STORE:
11081     return LowerATOMIC_LOAD_STORE(Op, DAG);
11082   }
11083 }
11084 
11085 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11086                                            SmallVectorImpl<SDValue>&Results,
11087                                            SelectionDAG &DAG) const {
11088   SDLoc dl(N);
11089   switch (N->getOpcode()) {
11090   default:
11091     llvm_unreachable("Do not know how to custom type legalize this operation!");
11092   case ISD::ATOMIC_LOAD: {
11093     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11094     Results.push_back(Res);
11095     Results.push_back(Res.getValue(1));
11096     break;
11097   }
11098   case ISD::READCYCLECOUNTER: {
11099     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11100     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11101 
11102     Results.push_back(
11103         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11104     Results.push_back(RTB.getValue(2));
11105     break;
11106   }
11107   case ISD::INTRINSIC_W_CHAIN: {
11108     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11109         Intrinsic::loop_decrement)
11110       break;
11111 
11112     assert(N->getValueType(0) == MVT::i1 &&
11113            "Unexpected result type for CTR decrement intrinsic");
11114     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11115                                  N->getValueType(0));
11116     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11117     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11118                                  N->getOperand(1));
11119 
11120     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11121     Results.push_back(NewInt.getValue(1));
11122     break;
11123   }
11124   case ISD::INTRINSIC_WO_CHAIN: {
11125     unsigned IntrinsicID =
11126         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11127 
11128     if (IntrinsicID == Intrinsic::ppc_pack_longdouble)
11129       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11130                                     N->getOperand(2), N->getOperand(1)));
11131     break;
11132   }
11133   case ISD::VAARG: {
11134     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11135       return;
11136 
11137     EVT VT = N->getValueType(0);
11138 
11139     if (VT == MVT::i64) {
11140       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11141 
11142       Results.push_back(NewNode);
11143       Results.push_back(NewNode.getValue(1));
11144     }
11145     return;
11146   }
11147   case ISD::STRICT_FP_TO_SINT:
11148   case ISD::STRICT_FP_TO_UINT:
11149   case ISD::FP_TO_SINT:
11150   case ISD::FP_TO_UINT:
11151     // LowerFP_TO_INT() can only handle f32 and f64.
11152     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11153         MVT::ppcf128)
11154       return;
11155     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11156     return;
11157   case ISD::TRUNCATE: {
11158     if (!N->getValueType(0).isVector())
11159       return;
11160     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11161     if (Lowered)
11162       Results.push_back(Lowered);
11163     return;
11164   }
11165   case ISD::FSHL:
11166   case ISD::FSHR:
11167     // Don't handle funnel shifts here.
11168     return;
11169   case ISD::BITCAST:
11170     // Don't handle bitcast here.
11171     return;
11172   case ISD::FP_EXTEND:
11173     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11174     if (Lowered)
11175       Results.push_back(Lowered);
11176     return;
11177   }
11178 }
11179 
11180 //===----------------------------------------------------------------------===//
11181 //  Other Lowering Code
11182 //===----------------------------------------------------------------------===//
11183 
11184 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11185   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11186   Function *Func = Intrinsic::getDeclaration(M, Id);
11187   return Builder.CreateCall(Func, {});
11188 }
11189 
11190 // The mappings for emitLeading/TrailingFence is taken from
11191 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11192 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11193                                                  Instruction *Inst,
11194                                                  AtomicOrdering Ord) const {
11195   if (Ord == AtomicOrdering::SequentiallyConsistent)
11196     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11197   if (isReleaseOrStronger(Ord))
11198     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11199   return nullptr;
11200 }
11201 
11202 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11203                                                   Instruction *Inst,
11204                                                   AtomicOrdering Ord) const {
11205   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11206     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11207     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11208     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11209     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11210       return Builder.CreateCall(
11211           Intrinsic::getDeclaration(
11212               Builder.GetInsertBlock()->getParent()->getParent(),
11213               Intrinsic::ppc_cfence, {Inst->getType()}),
11214           {Inst});
11215     // FIXME: Can use isync for rmw operation.
11216     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11217   }
11218   return nullptr;
11219 }
11220 
11221 MachineBasicBlock *
11222 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11223                                     unsigned AtomicSize,
11224                                     unsigned BinOpcode,
11225                                     unsigned CmpOpcode,
11226                                     unsigned CmpPred) const {
11227   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11228   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11229 
11230   auto LoadMnemonic = PPC::LDARX;
11231   auto StoreMnemonic = PPC::STDCX;
11232   switch (AtomicSize) {
11233   default:
11234     llvm_unreachable("Unexpected size of atomic entity");
11235   case 1:
11236     LoadMnemonic = PPC::LBARX;
11237     StoreMnemonic = PPC::STBCX;
11238     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11239     break;
11240   case 2:
11241     LoadMnemonic = PPC::LHARX;
11242     StoreMnemonic = PPC::STHCX;
11243     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11244     break;
11245   case 4:
11246     LoadMnemonic = PPC::LWARX;
11247     StoreMnemonic = PPC::STWCX;
11248     break;
11249   case 8:
11250     LoadMnemonic = PPC::LDARX;
11251     StoreMnemonic = PPC::STDCX;
11252     break;
11253   }
11254 
11255   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11256   MachineFunction *F = BB->getParent();
11257   MachineFunction::iterator It = ++BB->getIterator();
11258 
11259   Register dest = MI.getOperand(0).getReg();
11260   Register ptrA = MI.getOperand(1).getReg();
11261   Register ptrB = MI.getOperand(2).getReg();
11262   Register incr = MI.getOperand(3).getReg();
11263   DebugLoc dl = MI.getDebugLoc();
11264 
11265   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11266   MachineBasicBlock *loop2MBB =
11267     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11268   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11269   F->insert(It, loopMBB);
11270   if (CmpOpcode)
11271     F->insert(It, loop2MBB);
11272   F->insert(It, exitMBB);
11273   exitMBB->splice(exitMBB->begin(), BB,
11274                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11275   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11276 
11277   MachineRegisterInfo &RegInfo = F->getRegInfo();
11278   Register TmpReg = (!BinOpcode) ? incr :
11279     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11280                                            : &PPC::GPRCRegClass);
11281 
11282   //  thisMBB:
11283   //   ...
11284   //   fallthrough --> loopMBB
11285   BB->addSuccessor(loopMBB);
11286 
11287   //  loopMBB:
11288   //   l[wd]arx dest, ptr
11289   //   add r0, dest, incr
11290   //   st[wd]cx. r0, ptr
11291   //   bne- loopMBB
11292   //   fallthrough --> exitMBB
11293 
11294   // For max/min...
11295   //  loopMBB:
11296   //   l[wd]arx dest, ptr
11297   //   cmpl?[wd] incr, dest
11298   //   bgt exitMBB
11299   //  loop2MBB:
11300   //   st[wd]cx. dest, ptr
11301   //   bne- loopMBB
11302   //   fallthrough --> exitMBB
11303 
11304   BB = loopMBB;
11305   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11306     .addReg(ptrA).addReg(ptrB);
11307   if (BinOpcode)
11308     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11309   if (CmpOpcode) {
11310     // Signed comparisons of byte or halfword values must be sign-extended.
11311     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11312       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11313       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11314               ExtReg).addReg(dest);
11315       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11316         .addReg(incr).addReg(ExtReg);
11317     } else
11318       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11319         .addReg(incr).addReg(dest);
11320 
11321     BuildMI(BB, dl, TII->get(PPC::BCC))
11322       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11323     BB->addSuccessor(loop2MBB);
11324     BB->addSuccessor(exitMBB);
11325     BB = loop2MBB;
11326   }
11327   BuildMI(BB, dl, TII->get(StoreMnemonic))
11328     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11329   BuildMI(BB, dl, TII->get(PPC::BCC))
11330     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11331   BB->addSuccessor(loopMBB);
11332   BB->addSuccessor(exitMBB);
11333 
11334   //  exitMBB:
11335   //   ...
11336   BB = exitMBB;
11337   return BB;
11338 }
11339 
11340 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11341   switch(MI.getOpcode()) {
11342   default:
11343     return false;
11344   case PPC::COPY:
11345     return TII->isSignExtended(MI);
11346   case PPC::LHA:
11347   case PPC::LHA8:
11348   case PPC::LHAU:
11349   case PPC::LHAU8:
11350   case PPC::LHAUX:
11351   case PPC::LHAUX8:
11352   case PPC::LHAX:
11353   case PPC::LHAX8:
11354   case PPC::LWA:
11355   case PPC::LWAUX:
11356   case PPC::LWAX:
11357   case PPC::LWAX_32:
11358   case PPC::LWA_32:
11359   case PPC::PLHA:
11360   case PPC::PLHA8:
11361   case PPC::PLHA8pc:
11362   case PPC::PLHApc:
11363   case PPC::PLWA:
11364   case PPC::PLWA8:
11365   case PPC::PLWA8pc:
11366   case PPC::PLWApc:
11367   case PPC::EXTSB:
11368   case PPC::EXTSB8:
11369   case PPC::EXTSB8_32_64:
11370   case PPC::EXTSB8_rec:
11371   case PPC::EXTSB_rec:
11372   case PPC::EXTSH:
11373   case PPC::EXTSH8:
11374   case PPC::EXTSH8_32_64:
11375   case PPC::EXTSH8_rec:
11376   case PPC::EXTSH_rec:
11377   case PPC::EXTSW:
11378   case PPC::EXTSWSLI:
11379   case PPC::EXTSWSLI_32_64:
11380   case PPC::EXTSWSLI_32_64_rec:
11381   case PPC::EXTSWSLI_rec:
11382   case PPC::EXTSW_32:
11383   case PPC::EXTSW_32_64:
11384   case PPC::EXTSW_32_64_rec:
11385   case PPC::EXTSW_rec:
11386   case PPC::SRAW:
11387   case PPC::SRAWI:
11388   case PPC::SRAWI_rec:
11389   case PPC::SRAW_rec:
11390     return true;
11391   }
11392   return false;
11393 }
11394 
11395 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11396     MachineInstr &MI, MachineBasicBlock *BB,
11397     bool is8bit, // operation
11398     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11399   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11400   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11401 
11402   // If this is a signed comparison and the value being compared is not known
11403   // to be sign extended, sign extend it here.
11404   DebugLoc dl = MI.getDebugLoc();
11405   MachineFunction *F = BB->getParent();
11406   MachineRegisterInfo &RegInfo = F->getRegInfo();
11407   Register incr = MI.getOperand(3).getReg();
11408   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11409     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11410 
11411   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11412     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11413     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11414         .addReg(MI.getOperand(3).getReg());
11415     MI.getOperand(3).setReg(ValueReg);
11416   }
11417   // If we support part-word atomic mnemonics, just use them
11418   if (Subtarget.hasPartwordAtomics())
11419     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11420                             CmpPred);
11421 
11422   // In 64 bit mode we have to use 64 bits for addresses, even though the
11423   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11424   // registers without caring whether they're 32 or 64, but here we're
11425   // doing actual arithmetic on the addresses.
11426   bool is64bit = Subtarget.isPPC64();
11427   bool isLittleEndian = Subtarget.isLittleEndian();
11428   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11429 
11430   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11431   MachineFunction::iterator It = ++BB->getIterator();
11432 
11433   Register dest = MI.getOperand(0).getReg();
11434   Register ptrA = MI.getOperand(1).getReg();
11435   Register ptrB = MI.getOperand(2).getReg();
11436 
11437   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11438   MachineBasicBlock *loop2MBB =
11439       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11440   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11441   F->insert(It, loopMBB);
11442   if (CmpOpcode)
11443     F->insert(It, loop2MBB);
11444   F->insert(It, exitMBB);
11445   exitMBB->splice(exitMBB->begin(), BB,
11446                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11447   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11448 
11449   const TargetRegisterClass *RC =
11450       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11451   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11452 
11453   Register PtrReg = RegInfo.createVirtualRegister(RC);
11454   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11455   Register ShiftReg =
11456       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11457   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11458   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11459   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11460   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11461   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11462   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11463   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11464   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11465   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11466   Register Ptr1Reg;
11467   Register TmpReg =
11468       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11469 
11470   //  thisMBB:
11471   //   ...
11472   //   fallthrough --> loopMBB
11473   BB->addSuccessor(loopMBB);
11474 
11475   // The 4-byte load must be aligned, while a char or short may be
11476   // anywhere in the word.  Hence all this nasty bookkeeping code.
11477   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11478   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11479   //   xori shift, shift1, 24 [16]
11480   //   rlwinm ptr, ptr1, 0, 0, 29
11481   //   slw incr2, incr, shift
11482   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11483   //   slw mask, mask2, shift
11484   //  loopMBB:
11485   //   lwarx tmpDest, ptr
11486   //   add tmp, tmpDest, incr2
11487   //   andc tmp2, tmpDest, mask
11488   //   and tmp3, tmp, mask
11489   //   or tmp4, tmp3, tmp2
11490   //   stwcx. tmp4, ptr
11491   //   bne- loopMBB
11492   //   fallthrough --> exitMBB
11493   //   srw SrwDest, tmpDest, shift
11494   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11495   if (ptrA != ZeroReg) {
11496     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11497     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11498         .addReg(ptrA)
11499         .addReg(ptrB);
11500   } else {
11501     Ptr1Reg = ptrB;
11502   }
11503   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11504   // mode.
11505   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11506       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11507       .addImm(3)
11508       .addImm(27)
11509       .addImm(is8bit ? 28 : 27);
11510   if (!isLittleEndian)
11511     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11512         .addReg(Shift1Reg)
11513         .addImm(is8bit ? 24 : 16);
11514   if (is64bit)
11515     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11516         .addReg(Ptr1Reg)
11517         .addImm(0)
11518         .addImm(61);
11519   else
11520     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11521         .addReg(Ptr1Reg)
11522         .addImm(0)
11523         .addImm(0)
11524         .addImm(29);
11525   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11526   if (is8bit)
11527     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11528   else {
11529     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11530     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11531         .addReg(Mask3Reg)
11532         .addImm(65535);
11533   }
11534   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11535       .addReg(Mask2Reg)
11536       .addReg(ShiftReg);
11537 
11538   BB = loopMBB;
11539   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11540       .addReg(ZeroReg)
11541       .addReg(PtrReg);
11542   if (BinOpcode)
11543     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11544         .addReg(Incr2Reg)
11545         .addReg(TmpDestReg);
11546   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11547       .addReg(TmpDestReg)
11548       .addReg(MaskReg);
11549   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11550   if (CmpOpcode) {
11551     // For unsigned comparisons, we can directly compare the shifted values.
11552     // For signed comparisons we shift and sign extend.
11553     Register SReg = RegInfo.createVirtualRegister(GPRC);
11554     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11555         .addReg(TmpDestReg)
11556         .addReg(MaskReg);
11557     unsigned ValueReg = SReg;
11558     unsigned CmpReg = Incr2Reg;
11559     if (CmpOpcode == PPC::CMPW) {
11560       ValueReg = RegInfo.createVirtualRegister(GPRC);
11561       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11562           .addReg(SReg)
11563           .addReg(ShiftReg);
11564       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11565       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11566           .addReg(ValueReg);
11567       ValueReg = ValueSReg;
11568       CmpReg = incr;
11569     }
11570     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11571         .addReg(CmpReg)
11572         .addReg(ValueReg);
11573     BuildMI(BB, dl, TII->get(PPC::BCC))
11574         .addImm(CmpPred)
11575         .addReg(PPC::CR0)
11576         .addMBB(exitMBB);
11577     BB->addSuccessor(loop2MBB);
11578     BB->addSuccessor(exitMBB);
11579     BB = loop2MBB;
11580   }
11581   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11582   BuildMI(BB, dl, TII->get(PPC::STWCX))
11583       .addReg(Tmp4Reg)
11584       .addReg(ZeroReg)
11585       .addReg(PtrReg);
11586   BuildMI(BB, dl, TII->get(PPC::BCC))
11587       .addImm(PPC::PRED_NE)
11588       .addReg(PPC::CR0)
11589       .addMBB(loopMBB);
11590   BB->addSuccessor(loopMBB);
11591   BB->addSuccessor(exitMBB);
11592 
11593   //  exitMBB:
11594   //   ...
11595   BB = exitMBB;
11596   // Since the shift amount is not a constant, we need to clear
11597   // the upper bits with a separate RLWINM.
11598   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11599       .addReg(SrwDestReg)
11600       .addImm(0)
11601       .addImm(is8bit ? 24 : 16)
11602       .addImm(31);
11603   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11604       .addReg(TmpDestReg)
11605       .addReg(ShiftReg);
11606   return BB;
11607 }
11608 
11609 llvm::MachineBasicBlock *
11610 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11611                                     MachineBasicBlock *MBB) const {
11612   DebugLoc DL = MI.getDebugLoc();
11613   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11614   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11615 
11616   MachineFunction *MF = MBB->getParent();
11617   MachineRegisterInfo &MRI = MF->getRegInfo();
11618 
11619   const BasicBlock *BB = MBB->getBasicBlock();
11620   MachineFunction::iterator I = ++MBB->getIterator();
11621 
11622   Register DstReg = MI.getOperand(0).getReg();
11623   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11624   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11625   Register mainDstReg = MRI.createVirtualRegister(RC);
11626   Register restoreDstReg = MRI.createVirtualRegister(RC);
11627 
11628   MVT PVT = getPointerTy(MF->getDataLayout());
11629   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11630          "Invalid Pointer Size!");
11631   // For v = setjmp(buf), we generate
11632   //
11633   // thisMBB:
11634   //  SjLjSetup mainMBB
11635   //  bl mainMBB
11636   //  v_restore = 1
11637   //  b sinkMBB
11638   //
11639   // mainMBB:
11640   //  buf[LabelOffset] = LR
11641   //  v_main = 0
11642   //
11643   // sinkMBB:
11644   //  v = phi(main, restore)
11645   //
11646 
11647   MachineBasicBlock *thisMBB = MBB;
11648   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11649   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11650   MF->insert(I, mainMBB);
11651   MF->insert(I, sinkMBB);
11652 
11653   MachineInstrBuilder MIB;
11654 
11655   // Transfer the remainder of BB and its successor edges to sinkMBB.
11656   sinkMBB->splice(sinkMBB->begin(), MBB,
11657                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11658   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11659 
11660   // Note that the structure of the jmp_buf used here is not compatible
11661   // with that used by libc, and is not designed to be. Specifically, it
11662   // stores only those 'reserved' registers that LLVM does not otherwise
11663   // understand how to spill. Also, by convention, by the time this
11664   // intrinsic is called, Clang has already stored the frame address in the
11665   // first slot of the buffer and stack address in the third. Following the
11666   // X86 target code, we'll store the jump address in the second slot. We also
11667   // need to save the TOC pointer (R2) to handle jumps between shared
11668   // libraries, and that will be stored in the fourth slot. The thread
11669   // identifier (R13) is not affected.
11670 
11671   // thisMBB:
11672   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11673   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11674   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11675 
11676   // Prepare IP either in reg.
11677   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11678   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11679   Register BufReg = MI.getOperand(1).getReg();
11680 
11681   if (Subtarget.is64BitELFABI()) {
11682     setUsesTOCBasePtr(*MBB->getParent());
11683     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11684               .addReg(PPC::X2)
11685               .addImm(TOCOffset)
11686               .addReg(BufReg)
11687               .cloneMemRefs(MI);
11688   }
11689 
11690   // Naked functions never have a base pointer, and so we use r1. For all
11691   // other functions, this decision must be delayed until during PEI.
11692   unsigned BaseReg;
11693   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11694     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11695   else
11696     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11697 
11698   MIB = BuildMI(*thisMBB, MI, DL,
11699                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11700             .addReg(BaseReg)
11701             .addImm(BPOffset)
11702             .addReg(BufReg)
11703             .cloneMemRefs(MI);
11704 
11705   // Setup
11706   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11707   MIB.addRegMask(TRI->getNoPreservedMask());
11708 
11709   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11710 
11711   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11712           .addMBB(mainMBB);
11713   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11714 
11715   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11716   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11717 
11718   // mainMBB:
11719   //  mainDstReg = 0
11720   MIB =
11721       BuildMI(mainMBB, DL,
11722               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11723 
11724   // Store IP
11725   if (Subtarget.isPPC64()) {
11726     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11727             .addReg(LabelReg)
11728             .addImm(LabelOffset)
11729             .addReg(BufReg);
11730   } else {
11731     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11732             .addReg(LabelReg)
11733             .addImm(LabelOffset)
11734             .addReg(BufReg);
11735   }
11736   MIB.cloneMemRefs(MI);
11737 
11738   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11739   mainMBB->addSuccessor(sinkMBB);
11740 
11741   // sinkMBB:
11742   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11743           TII->get(PPC::PHI), DstReg)
11744     .addReg(mainDstReg).addMBB(mainMBB)
11745     .addReg(restoreDstReg).addMBB(thisMBB);
11746 
11747   MI.eraseFromParent();
11748   return sinkMBB;
11749 }
11750 
11751 MachineBasicBlock *
11752 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11753                                      MachineBasicBlock *MBB) const {
11754   DebugLoc DL = MI.getDebugLoc();
11755   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11756 
11757   MachineFunction *MF = MBB->getParent();
11758   MachineRegisterInfo &MRI = MF->getRegInfo();
11759 
11760   MVT PVT = getPointerTy(MF->getDataLayout());
11761   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11762          "Invalid Pointer Size!");
11763 
11764   const TargetRegisterClass *RC =
11765     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11766   Register Tmp = MRI.createVirtualRegister(RC);
11767   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11768   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11769   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11770   unsigned BP =
11771       (PVT == MVT::i64)
11772           ? PPC::X30
11773           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11774                                                               : PPC::R30);
11775 
11776   MachineInstrBuilder MIB;
11777 
11778   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11779   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11780   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11781   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11782 
11783   Register BufReg = MI.getOperand(0).getReg();
11784 
11785   // Reload FP (the jumped-to function may not have had a
11786   // frame pointer, and if so, then its r31 will be restored
11787   // as necessary).
11788   if (PVT == MVT::i64) {
11789     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11790             .addImm(0)
11791             .addReg(BufReg);
11792   } else {
11793     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11794             .addImm(0)
11795             .addReg(BufReg);
11796   }
11797   MIB.cloneMemRefs(MI);
11798 
11799   // Reload IP
11800   if (PVT == MVT::i64) {
11801     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11802             .addImm(LabelOffset)
11803             .addReg(BufReg);
11804   } else {
11805     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11806             .addImm(LabelOffset)
11807             .addReg(BufReg);
11808   }
11809   MIB.cloneMemRefs(MI);
11810 
11811   // Reload SP
11812   if (PVT == MVT::i64) {
11813     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11814             .addImm(SPOffset)
11815             .addReg(BufReg);
11816   } else {
11817     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11818             .addImm(SPOffset)
11819             .addReg(BufReg);
11820   }
11821   MIB.cloneMemRefs(MI);
11822 
11823   // Reload BP
11824   if (PVT == MVT::i64) {
11825     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11826             .addImm(BPOffset)
11827             .addReg(BufReg);
11828   } else {
11829     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11830             .addImm(BPOffset)
11831             .addReg(BufReg);
11832   }
11833   MIB.cloneMemRefs(MI);
11834 
11835   // Reload TOC
11836   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11837     setUsesTOCBasePtr(*MBB->getParent());
11838     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11839               .addImm(TOCOffset)
11840               .addReg(BufReg)
11841               .cloneMemRefs(MI);
11842   }
11843 
11844   // Jump
11845   BuildMI(*MBB, MI, DL,
11846           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11847   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11848 
11849   MI.eraseFromParent();
11850   return MBB;
11851 }
11852 
11853 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11854   // If the function specifically requests inline stack probes, emit them.
11855   if (MF.getFunction().hasFnAttribute("probe-stack"))
11856     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11857            "inline-asm";
11858   return false;
11859 }
11860 
11861 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11862   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11863   unsigned StackAlign = TFI->getStackAlignment();
11864   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11865          "Unexpected stack alignment");
11866   // The default stack probe size is 4096 if the function has no
11867   // stack-probe-size attribute.
11868   unsigned StackProbeSize = 4096;
11869   const Function &Fn = MF.getFunction();
11870   if (Fn.hasFnAttribute("stack-probe-size"))
11871     Fn.getFnAttribute("stack-probe-size")
11872         .getValueAsString()
11873         .getAsInteger(0, StackProbeSize);
11874   // Round down to the stack alignment.
11875   StackProbeSize &= ~(StackAlign - 1);
11876   return StackProbeSize ? StackProbeSize : StackAlign;
11877 }
11878 
11879 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11880 // into three phases. In the first phase, it uses pseudo instruction
11881 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11882 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11883 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11884 // MaxCallFrameSize so that it can calculate correct data area pointer.
11885 MachineBasicBlock *
11886 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11887                                     MachineBasicBlock *MBB) const {
11888   const bool isPPC64 = Subtarget.isPPC64();
11889   MachineFunction *MF = MBB->getParent();
11890   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11891   DebugLoc DL = MI.getDebugLoc();
11892   const unsigned ProbeSize = getStackProbeSize(*MF);
11893   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11894   MachineRegisterInfo &MRI = MF->getRegInfo();
11895   // The CFG of probing stack looks as
11896   //         +-----+
11897   //         | MBB |
11898   //         +--+--+
11899   //            |
11900   //       +----v----+
11901   //  +--->+ TestMBB +---+
11902   //  |    +----+----+   |
11903   //  |         |        |
11904   //  |   +-----v----+   |
11905   //  +---+ BlockMBB |   |
11906   //      +----------+   |
11907   //                     |
11908   //       +---------+   |
11909   //       | TailMBB +<--+
11910   //       +---------+
11911   // In MBB, calculate previous frame pointer and final stack pointer.
11912   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11913   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11914   // TailMBB is spliced via \p MI.
11915   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11916   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11917   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11918 
11919   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11920   MF->insert(MBBIter, TestMBB);
11921   MF->insert(MBBIter, BlockMBB);
11922   MF->insert(MBBIter, TailMBB);
11923 
11924   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11925   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11926 
11927   Register DstReg = MI.getOperand(0).getReg();
11928   Register NegSizeReg = MI.getOperand(1).getReg();
11929   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11930   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11931   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11932   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11933 
11934   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11935   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11936   // NegSize.
11937   unsigned ProbeOpc;
11938   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11939     ProbeOpc =
11940         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11941   else
11942     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11943     // and NegSizeReg will be allocated in the same phyreg to avoid
11944     // redundant copy when NegSizeReg has only one use which is current MI and
11945     // will be replaced by PREPARE_PROBED_ALLOCA then.
11946     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11947                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11948   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11949       .addDef(ActualNegSizeReg)
11950       .addReg(NegSizeReg)
11951       .add(MI.getOperand(2))
11952       .add(MI.getOperand(3));
11953 
11954   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11955   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11956           FinalStackPtr)
11957       .addReg(SPReg)
11958       .addReg(ActualNegSizeReg);
11959 
11960   // Materialize a scratch register for update.
11961   int64_t NegProbeSize = -(int64_t)ProbeSize;
11962   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11963   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11964   if (!isInt<16>(NegProbeSize)) {
11965     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11966     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11967         .addImm(NegProbeSize >> 16);
11968     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11969             ScratchReg)
11970         .addReg(TempReg)
11971         .addImm(NegProbeSize & 0xFFFF);
11972   } else
11973     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11974         .addImm(NegProbeSize);
11975 
11976   {
11977     // Probing leading residual part.
11978     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11979     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11980         .addReg(ActualNegSizeReg)
11981         .addReg(ScratchReg);
11982     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11983     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11984         .addReg(Div)
11985         .addReg(ScratchReg);
11986     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11987     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11988         .addReg(Mul)
11989         .addReg(ActualNegSizeReg);
11990     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11991         .addReg(FramePointer)
11992         .addReg(SPReg)
11993         .addReg(NegMod);
11994   }
11995 
11996   {
11997     // Remaining part should be multiple of ProbeSize.
11998     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11999     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12000         .addReg(SPReg)
12001         .addReg(FinalStackPtr);
12002     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12003         .addImm(PPC::PRED_EQ)
12004         .addReg(CmpResult)
12005         .addMBB(TailMBB);
12006     TestMBB->addSuccessor(BlockMBB);
12007     TestMBB->addSuccessor(TailMBB);
12008   }
12009 
12010   {
12011     // Touch the block.
12012     // |P...|P...|P...
12013     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12014         .addReg(FramePointer)
12015         .addReg(SPReg)
12016         .addReg(ScratchReg);
12017     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12018     BlockMBB->addSuccessor(TestMBB);
12019   }
12020 
12021   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12022   // DYNAREAOFFSET pseudo instruction to get the future result.
12023   Register MaxCallFrameSizeReg =
12024       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12025   BuildMI(TailMBB, DL,
12026           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12027           MaxCallFrameSizeReg)
12028       .add(MI.getOperand(2))
12029       .add(MI.getOperand(3));
12030   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12031       .addReg(SPReg)
12032       .addReg(MaxCallFrameSizeReg);
12033 
12034   // Splice instructions after MI to TailMBB.
12035   TailMBB->splice(TailMBB->end(), MBB,
12036                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12037   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12038   MBB->addSuccessor(TestMBB);
12039 
12040   // Delete the pseudo instruction.
12041   MI.eraseFromParent();
12042 
12043   ++NumDynamicAllocaProbed;
12044   return TailMBB;
12045 }
12046 
12047 MachineBasicBlock *
12048 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12049                                                MachineBasicBlock *BB) const {
12050   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12051       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12052     if (Subtarget.is64BitELFABI() &&
12053         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12054         !Subtarget.isUsingPCRelativeCalls()) {
12055       // Call lowering should have added an r2 operand to indicate a dependence
12056       // on the TOC base pointer value. It can't however, because there is no
12057       // way to mark the dependence as implicit there, and so the stackmap code
12058       // will confuse it with a regular operand. Instead, add the dependence
12059       // here.
12060       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12061     }
12062 
12063     return emitPatchPoint(MI, BB);
12064   }
12065 
12066   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12067       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12068     return emitEHSjLjSetJmp(MI, BB);
12069   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12070              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12071     return emitEHSjLjLongJmp(MI, BB);
12072   }
12073 
12074   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12075 
12076   // To "insert" these instructions we actually have to insert their
12077   // control-flow patterns.
12078   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12079   MachineFunction::iterator It = ++BB->getIterator();
12080 
12081   MachineFunction *F = BB->getParent();
12082 
12083   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12084       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12085       MI.getOpcode() == PPC::SELECT_I8) {
12086     SmallVector<MachineOperand, 2> Cond;
12087     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12088         MI.getOpcode() == PPC::SELECT_CC_I8)
12089       Cond.push_back(MI.getOperand(4));
12090     else
12091       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12092     Cond.push_back(MI.getOperand(1));
12093 
12094     DebugLoc dl = MI.getDebugLoc();
12095     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12096                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12097   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12098              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12099              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12100              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12101              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12102              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12103              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12104              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12105              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12106              MI.getOpcode() == PPC::SELECT_F4 ||
12107              MI.getOpcode() == PPC::SELECT_F8 ||
12108              MI.getOpcode() == PPC::SELECT_F16 ||
12109              MI.getOpcode() == PPC::SELECT_SPE ||
12110              MI.getOpcode() == PPC::SELECT_SPE4 ||
12111              MI.getOpcode() == PPC::SELECT_VRRC ||
12112              MI.getOpcode() == PPC::SELECT_VSFRC ||
12113              MI.getOpcode() == PPC::SELECT_VSSRC ||
12114              MI.getOpcode() == PPC::SELECT_VSRC) {
12115     // The incoming instruction knows the destination vreg to set, the
12116     // condition code register to branch on, the true/false values to
12117     // select between, and a branch opcode to use.
12118 
12119     //  thisMBB:
12120     //  ...
12121     //   TrueVal = ...
12122     //   cmpTY ccX, r1, r2
12123     //   bCC copy1MBB
12124     //   fallthrough --> copy0MBB
12125     MachineBasicBlock *thisMBB = BB;
12126     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12127     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12128     DebugLoc dl = MI.getDebugLoc();
12129     F->insert(It, copy0MBB);
12130     F->insert(It, sinkMBB);
12131 
12132     // Transfer the remainder of BB and its successor edges to sinkMBB.
12133     sinkMBB->splice(sinkMBB->begin(), BB,
12134                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12135     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12136 
12137     // Next, add the true and fallthrough blocks as its successors.
12138     BB->addSuccessor(copy0MBB);
12139     BB->addSuccessor(sinkMBB);
12140 
12141     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12142         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12143         MI.getOpcode() == PPC::SELECT_F16 ||
12144         MI.getOpcode() == PPC::SELECT_SPE4 ||
12145         MI.getOpcode() == PPC::SELECT_SPE ||
12146         MI.getOpcode() == PPC::SELECT_VRRC ||
12147         MI.getOpcode() == PPC::SELECT_VSFRC ||
12148         MI.getOpcode() == PPC::SELECT_VSSRC ||
12149         MI.getOpcode() == PPC::SELECT_VSRC) {
12150       BuildMI(BB, dl, TII->get(PPC::BC))
12151           .addReg(MI.getOperand(1).getReg())
12152           .addMBB(sinkMBB);
12153     } else {
12154       unsigned SelectPred = MI.getOperand(4).getImm();
12155       BuildMI(BB, dl, TII->get(PPC::BCC))
12156           .addImm(SelectPred)
12157           .addReg(MI.getOperand(1).getReg())
12158           .addMBB(sinkMBB);
12159     }
12160 
12161     //  copy0MBB:
12162     //   %FalseValue = ...
12163     //   # fallthrough to sinkMBB
12164     BB = copy0MBB;
12165 
12166     // Update machine-CFG edges
12167     BB->addSuccessor(sinkMBB);
12168 
12169     //  sinkMBB:
12170     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12171     //  ...
12172     BB = sinkMBB;
12173     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12174         .addReg(MI.getOperand(3).getReg())
12175         .addMBB(copy0MBB)
12176         .addReg(MI.getOperand(2).getReg())
12177         .addMBB(thisMBB);
12178   } else if (MI.getOpcode() == PPC::ReadTB) {
12179     // To read the 64-bit time-base register on a 32-bit target, we read the
12180     // two halves. Should the counter have wrapped while it was being read, we
12181     // need to try again.
12182     // ...
12183     // readLoop:
12184     // mfspr Rx,TBU # load from TBU
12185     // mfspr Ry,TB  # load from TB
12186     // mfspr Rz,TBU # load from TBU
12187     // cmpw crX,Rx,Rz # check if 'old'='new'
12188     // bne readLoop   # branch if they're not equal
12189     // ...
12190 
12191     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12192     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12193     DebugLoc dl = MI.getDebugLoc();
12194     F->insert(It, readMBB);
12195     F->insert(It, sinkMBB);
12196 
12197     // Transfer the remainder of BB and its successor edges to sinkMBB.
12198     sinkMBB->splice(sinkMBB->begin(), BB,
12199                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12200     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12201 
12202     BB->addSuccessor(readMBB);
12203     BB = readMBB;
12204 
12205     MachineRegisterInfo &RegInfo = F->getRegInfo();
12206     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12207     Register LoReg = MI.getOperand(0).getReg();
12208     Register HiReg = MI.getOperand(1).getReg();
12209 
12210     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12211     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12212     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12213 
12214     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12215 
12216     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12217         .addReg(HiReg)
12218         .addReg(ReadAgainReg);
12219     BuildMI(BB, dl, TII->get(PPC::BCC))
12220         .addImm(PPC::PRED_NE)
12221         .addReg(CmpReg)
12222         .addMBB(readMBB);
12223 
12224     BB->addSuccessor(readMBB);
12225     BB->addSuccessor(sinkMBB);
12226   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12227     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12228   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12229     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12230   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12231     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12232   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12233     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12234 
12235   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12236     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12237   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12238     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12239   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12240     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12241   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12242     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12243 
12244   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12245     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12246   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12247     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12248   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12249     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12250   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12251     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12252 
12253   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12254     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12255   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12256     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12257   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12258     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12259   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12260     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12261 
12262   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12263     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12264   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12265     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12266   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12267     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12268   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12269     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12270 
12271   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12272     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12273   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12274     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12275   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12276     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12277   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12278     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12279 
12280   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12281     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12282   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12283     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12284   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12285     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12286   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12287     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12288 
12289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12290     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12291   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12292     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12293   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12294     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12295   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12296     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12297 
12298   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12299     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12300   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12301     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12302   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12303     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12304   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12305     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12306 
12307   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12308     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12309   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12310     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12311   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12312     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12313   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12314     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12315 
12316   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12317     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12318   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12319     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12320   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12321     BB = EmitAtomicBinary(MI, BB, 4, 0);
12322   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12323     BB = EmitAtomicBinary(MI, BB, 8, 0);
12324   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12325            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12326            (Subtarget.hasPartwordAtomics() &&
12327             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12328            (Subtarget.hasPartwordAtomics() &&
12329             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12330     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12331 
12332     auto LoadMnemonic = PPC::LDARX;
12333     auto StoreMnemonic = PPC::STDCX;
12334     switch (MI.getOpcode()) {
12335     default:
12336       llvm_unreachable("Compare and swap of unknown size");
12337     case PPC::ATOMIC_CMP_SWAP_I8:
12338       LoadMnemonic = PPC::LBARX;
12339       StoreMnemonic = PPC::STBCX;
12340       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12341       break;
12342     case PPC::ATOMIC_CMP_SWAP_I16:
12343       LoadMnemonic = PPC::LHARX;
12344       StoreMnemonic = PPC::STHCX;
12345       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12346       break;
12347     case PPC::ATOMIC_CMP_SWAP_I32:
12348       LoadMnemonic = PPC::LWARX;
12349       StoreMnemonic = PPC::STWCX;
12350       break;
12351     case PPC::ATOMIC_CMP_SWAP_I64:
12352       LoadMnemonic = PPC::LDARX;
12353       StoreMnemonic = PPC::STDCX;
12354       break;
12355     }
12356     Register dest = MI.getOperand(0).getReg();
12357     Register ptrA = MI.getOperand(1).getReg();
12358     Register ptrB = MI.getOperand(2).getReg();
12359     Register oldval = MI.getOperand(3).getReg();
12360     Register newval = MI.getOperand(4).getReg();
12361     DebugLoc dl = MI.getDebugLoc();
12362 
12363     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12364     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12365     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12366     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12367     F->insert(It, loop1MBB);
12368     F->insert(It, loop2MBB);
12369     F->insert(It, midMBB);
12370     F->insert(It, exitMBB);
12371     exitMBB->splice(exitMBB->begin(), BB,
12372                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12373     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12374 
12375     //  thisMBB:
12376     //   ...
12377     //   fallthrough --> loopMBB
12378     BB->addSuccessor(loop1MBB);
12379 
12380     // loop1MBB:
12381     //   l[bhwd]arx dest, ptr
12382     //   cmp[wd] dest, oldval
12383     //   bne- midMBB
12384     // loop2MBB:
12385     //   st[bhwd]cx. newval, ptr
12386     //   bne- loopMBB
12387     //   b exitBB
12388     // midMBB:
12389     //   st[bhwd]cx. dest, ptr
12390     // exitBB:
12391     BB = loop1MBB;
12392     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12393     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12394         .addReg(oldval)
12395         .addReg(dest);
12396     BuildMI(BB, dl, TII->get(PPC::BCC))
12397         .addImm(PPC::PRED_NE)
12398         .addReg(PPC::CR0)
12399         .addMBB(midMBB);
12400     BB->addSuccessor(loop2MBB);
12401     BB->addSuccessor(midMBB);
12402 
12403     BB = loop2MBB;
12404     BuildMI(BB, dl, TII->get(StoreMnemonic))
12405         .addReg(newval)
12406         .addReg(ptrA)
12407         .addReg(ptrB);
12408     BuildMI(BB, dl, TII->get(PPC::BCC))
12409         .addImm(PPC::PRED_NE)
12410         .addReg(PPC::CR0)
12411         .addMBB(loop1MBB);
12412     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12413     BB->addSuccessor(loop1MBB);
12414     BB->addSuccessor(exitMBB);
12415 
12416     BB = midMBB;
12417     BuildMI(BB, dl, TII->get(StoreMnemonic))
12418         .addReg(dest)
12419         .addReg(ptrA)
12420         .addReg(ptrB);
12421     BB->addSuccessor(exitMBB);
12422 
12423     //  exitMBB:
12424     //   ...
12425     BB = exitMBB;
12426   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12427              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12428     // We must use 64-bit registers for addresses when targeting 64-bit,
12429     // since we're actually doing arithmetic on them.  Other registers
12430     // can be 32-bit.
12431     bool is64bit = Subtarget.isPPC64();
12432     bool isLittleEndian = Subtarget.isLittleEndian();
12433     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12434 
12435     Register dest = MI.getOperand(0).getReg();
12436     Register ptrA = MI.getOperand(1).getReg();
12437     Register ptrB = MI.getOperand(2).getReg();
12438     Register oldval = MI.getOperand(3).getReg();
12439     Register newval = MI.getOperand(4).getReg();
12440     DebugLoc dl = MI.getDebugLoc();
12441 
12442     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12443     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12444     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12445     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12446     F->insert(It, loop1MBB);
12447     F->insert(It, loop2MBB);
12448     F->insert(It, midMBB);
12449     F->insert(It, exitMBB);
12450     exitMBB->splice(exitMBB->begin(), BB,
12451                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12452     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12453 
12454     MachineRegisterInfo &RegInfo = F->getRegInfo();
12455     const TargetRegisterClass *RC =
12456         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12457     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12458 
12459     Register PtrReg = RegInfo.createVirtualRegister(RC);
12460     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12461     Register ShiftReg =
12462         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12463     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12464     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12465     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12466     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12467     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12468     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12469     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12470     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12471     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12472     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12473     Register Ptr1Reg;
12474     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12475     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12476     //  thisMBB:
12477     //   ...
12478     //   fallthrough --> loopMBB
12479     BB->addSuccessor(loop1MBB);
12480 
12481     // The 4-byte load must be aligned, while a char or short may be
12482     // anywhere in the word.  Hence all this nasty bookkeeping code.
12483     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12484     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12485     //   xori shift, shift1, 24 [16]
12486     //   rlwinm ptr, ptr1, 0, 0, 29
12487     //   slw newval2, newval, shift
12488     //   slw oldval2, oldval,shift
12489     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12490     //   slw mask, mask2, shift
12491     //   and newval3, newval2, mask
12492     //   and oldval3, oldval2, mask
12493     // loop1MBB:
12494     //   lwarx tmpDest, ptr
12495     //   and tmp, tmpDest, mask
12496     //   cmpw tmp, oldval3
12497     //   bne- midMBB
12498     // loop2MBB:
12499     //   andc tmp2, tmpDest, mask
12500     //   or tmp4, tmp2, newval3
12501     //   stwcx. tmp4, ptr
12502     //   bne- loop1MBB
12503     //   b exitBB
12504     // midMBB:
12505     //   stwcx. tmpDest, ptr
12506     // exitBB:
12507     //   srw dest, tmpDest, shift
12508     if (ptrA != ZeroReg) {
12509       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12510       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12511           .addReg(ptrA)
12512           .addReg(ptrB);
12513     } else {
12514       Ptr1Reg = ptrB;
12515     }
12516 
12517     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12518     // mode.
12519     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12520         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12521         .addImm(3)
12522         .addImm(27)
12523         .addImm(is8bit ? 28 : 27);
12524     if (!isLittleEndian)
12525       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12526           .addReg(Shift1Reg)
12527           .addImm(is8bit ? 24 : 16);
12528     if (is64bit)
12529       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12530           .addReg(Ptr1Reg)
12531           .addImm(0)
12532           .addImm(61);
12533     else
12534       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12535           .addReg(Ptr1Reg)
12536           .addImm(0)
12537           .addImm(0)
12538           .addImm(29);
12539     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12540         .addReg(newval)
12541         .addReg(ShiftReg);
12542     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12543         .addReg(oldval)
12544         .addReg(ShiftReg);
12545     if (is8bit)
12546       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12547     else {
12548       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12549       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12550           .addReg(Mask3Reg)
12551           .addImm(65535);
12552     }
12553     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12554         .addReg(Mask2Reg)
12555         .addReg(ShiftReg);
12556     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12557         .addReg(NewVal2Reg)
12558         .addReg(MaskReg);
12559     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12560         .addReg(OldVal2Reg)
12561         .addReg(MaskReg);
12562 
12563     BB = loop1MBB;
12564     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12565         .addReg(ZeroReg)
12566         .addReg(PtrReg);
12567     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12568         .addReg(TmpDestReg)
12569         .addReg(MaskReg);
12570     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12571         .addReg(TmpReg)
12572         .addReg(OldVal3Reg);
12573     BuildMI(BB, dl, TII->get(PPC::BCC))
12574         .addImm(PPC::PRED_NE)
12575         .addReg(PPC::CR0)
12576         .addMBB(midMBB);
12577     BB->addSuccessor(loop2MBB);
12578     BB->addSuccessor(midMBB);
12579 
12580     BB = loop2MBB;
12581     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12582         .addReg(TmpDestReg)
12583         .addReg(MaskReg);
12584     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12585         .addReg(Tmp2Reg)
12586         .addReg(NewVal3Reg);
12587     BuildMI(BB, dl, TII->get(PPC::STWCX))
12588         .addReg(Tmp4Reg)
12589         .addReg(ZeroReg)
12590         .addReg(PtrReg);
12591     BuildMI(BB, dl, TII->get(PPC::BCC))
12592         .addImm(PPC::PRED_NE)
12593         .addReg(PPC::CR0)
12594         .addMBB(loop1MBB);
12595     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12596     BB->addSuccessor(loop1MBB);
12597     BB->addSuccessor(exitMBB);
12598 
12599     BB = midMBB;
12600     BuildMI(BB, dl, TII->get(PPC::STWCX))
12601         .addReg(TmpDestReg)
12602         .addReg(ZeroReg)
12603         .addReg(PtrReg);
12604     BB->addSuccessor(exitMBB);
12605 
12606     //  exitMBB:
12607     //   ...
12608     BB = exitMBB;
12609     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12610         .addReg(TmpReg)
12611         .addReg(ShiftReg);
12612   } else if (MI.getOpcode() == PPC::FADDrtz) {
12613     // This pseudo performs an FADD with rounding mode temporarily forced
12614     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12615     // is not modeled at the SelectionDAG level.
12616     Register Dest = MI.getOperand(0).getReg();
12617     Register Src1 = MI.getOperand(1).getReg();
12618     Register Src2 = MI.getOperand(2).getReg();
12619     DebugLoc dl = MI.getDebugLoc();
12620 
12621     MachineRegisterInfo &RegInfo = F->getRegInfo();
12622     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12623 
12624     // Save FPSCR value.
12625     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12626 
12627     // Set rounding mode to round-to-zero.
12628     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12629         .addImm(31)
12630         .addReg(PPC::RM, RegState::ImplicitDefine);
12631 
12632     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12633         .addImm(30)
12634         .addReg(PPC::RM, RegState::ImplicitDefine);
12635 
12636     // Perform addition.
12637     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12638                    .addReg(Src1)
12639                    .addReg(Src2);
12640     if (MI.getFlag(MachineInstr::NoFPExcept))
12641       MIB.setMIFlag(MachineInstr::NoFPExcept);
12642 
12643     // Restore FPSCR value.
12644     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12645   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12646              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12647              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12648              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12649     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12650                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12651                           ? PPC::ANDI8_rec
12652                           : PPC::ANDI_rec;
12653     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12654                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12655 
12656     MachineRegisterInfo &RegInfo = F->getRegInfo();
12657     Register Dest = RegInfo.createVirtualRegister(
12658         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12659 
12660     DebugLoc Dl = MI.getDebugLoc();
12661     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12662         .addReg(MI.getOperand(1).getReg())
12663         .addImm(1);
12664     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12665             MI.getOperand(0).getReg())
12666         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12667   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12668     DebugLoc Dl = MI.getDebugLoc();
12669     MachineRegisterInfo &RegInfo = F->getRegInfo();
12670     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12671     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12672     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12673             MI.getOperand(0).getReg())
12674         .addReg(CRReg);
12675   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12676     DebugLoc Dl = MI.getDebugLoc();
12677     unsigned Imm = MI.getOperand(1).getImm();
12678     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12679     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12680             MI.getOperand(0).getReg())
12681         .addReg(PPC::CR0EQ);
12682   } else if (MI.getOpcode() == PPC::SETRNDi) {
12683     DebugLoc dl = MI.getDebugLoc();
12684     Register OldFPSCRReg = MI.getOperand(0).getReg();
12685 
12686     // Save FPSCR value.
12687     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12688 
12689     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12690     // the following settings:
12691     //   00 Round to nearest
12692     //   01 Round to 0
12693     //   10 Round to +inf
12694     //   11 Round to -inf
12695 
12696     // When the operand is immediate, using the two least significant bits of
12697     // the immediate to set the bits 62:63 of FPSCR.
12698     unsigned Mode = MI.getOperand(1).getImm();
12699     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12700         .addImm(31)
12701         .addReg(PPC::RM, RegState::ImplicitDefine);
12702 
12703     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12704         .addImm(30)
12705         .addReg(PPC::RM, RegState::ImplicitDefine);
12706   } else if (MI.getOpcode() == PPC::SETRND) {
12707     DebugLoc dl = MI.getDebugLoc();
12708 
12709     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12710     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12711     // If the target doesn't have DirectMove, we should use stack to do the
12712     // conversion, because the target doesn't have the instructions like mtvsrd
12713     // or mfvsrd to do this conversion directly.
12714     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12715       if (Subtarget.hasDirectMove()) {
12716         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12717           .addReg(SrcReg);
12718       } else {
12719         // Use stack to do the register copy.
12720         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12721         MachineRegisterInfo &RegInfo = F->getRegInfo();
12722         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12723         if (RC == &PPC::F8RCRegClass) {
12724           // Copy register from F8RCRegClass to G8RCRegclass.
12725           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12726                  "Unsupported RegClass.");
12727 
12728           StoreOp = PPC::STFD;
12729           LoadOp = PPC::LD;
12730         } else {
12731           // Copy register from G8RCRegClass to F8RCRegclass.
12732           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12733                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12734                  "Unsupported RegClass.");
12735         }
12736 
12737         MachineFrameInfo &MFI = F->getFrameInfo();
12738         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12739 
12740         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12741             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12742             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12743             MFI.getObjectAlign(FrameIdx));
12744 
12745         // Store the SrcReg into the stack.
12746         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12747           .addReg(SrcReg)
12748           .addImm(0)
12749           .addFrameIndex(FrameIdx)
12750           .addMemOperand(MMOStore);
12751 
12752         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12753             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12754             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12755             MFI.getObjectAlign(FrameIdx));
12756 
12757         // Load from the stack where SrcReg is stored, and save to DestReg,
12758         // so we have done the RegClass conversion from RegClass::SrcReg to
12759         // RegClass::DestReg.
12760         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12761           .addImm(0)
12762           .addFrameIndex(FrameIdx)
12763           .addMemOperand(MMOLoad);
12764       }
12765     };
12766 
12767     Register OldFPSCRReg = MI.getOperand(0).getReg();
12768 
12769     // Save FPSCR value.
12770     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12771 
12772     // When the operand is gprc register, use two least significant bits of the
12773     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12774     //
12775     // copy OldFPSCRTmpReg, OldFPSCRReg
12776     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12777     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12778     // copy NewFPSCRReg, NewFPSCRTmpReg
12779     // mtfsf 255, NewFPSCRReg
12780     MachineOperand SrcOp = MI.getOperand(1);
12781     MachineRegisterInfo &RegInfo = F->getRegInfo();
12782     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12783 
12784     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12785 
12786     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12787     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12788 
12789     // The first operand of INSERT_SUBREG should be a register which has
12790     // subregisters, we only care about its RegClass, so we should use an
12791     // IMPLICIT_DEF register.
12792     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12793     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12794       .addReg(ImDefReg)
12795       .add(SrcOp)
12796       .addImm(1);
12797 
12798     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12799     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12800       .addReg(OldFPSCRTmpReg)
12801       .addReg(ExtSrcReg)
12802       .addImm(0)
12803       .addImm(62);
12804 
12805     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12806     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12807 
12808     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12809     // bits of FPSCR.
12810     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12811       .addImm(255)
12812       .addReg(NewFPSCRReg)
12813       .addImm(0)
12814       .addImm(0);
12815   } else if (MI.getOpcode() == PPC::SETFLM) {
12816     DebugLoc Dl = MI.getDebugLoc();
12817 
12818     // Result of setflm is previous FPSCR content, so we need to save it first.
12819     Register OldFPSCRReg = MI.getOperand(0).getReg();
12820     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12821 
12822     // Put bits in 32:63 to FPSCR.
12823     Register NewFPSCRReg = MI.getOperand(1).getReg();
12824     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12825         .addImm(255)
12826         .addReg(NewFPSCRReg)
12827         .addImm(0)
12828         .addImm(0);
12829   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12830              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12831     return emitProbedAlloca(MI, BB);
12832   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12833     DebugLoc DL = MI.getDebugLoc();
12834     Register Src = MI.getOperand(2).getReg();
12835     Register Lo = MI.getOperand(0).getReg();
12836     Register Hi = MI.getOperand(1).getReg();
12837     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12838         .addDef(Lo)
12839         .addUse(Src, 0, PPC::sub_gp8_x1);
12840     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12841         .addDef(Hi)
12842         .addUse(Src, 0, PPC::sub_gp8_x0);
12843   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12844              MI.getOpcode() == PPC::STQX_PSEUDO) {
12845     DebugLoc DL = MI.getDebugLoc();
12846     // Ptr is used as the ptr_rc_no_r0 part
12847     // of LQ/STQ's memory operand and adding result of RA and RB,
12848     // so it has to be g8rc_and_g8rc_nox0.
12849     Register Ptr =
12850         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12851     Register Val = MI.getOperand(0).getReg();
12852     Register RA = MI.getOperand(1).getReg();
12853     Register RB = MI.getOperand(2).getReg();
12854     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12855     BuildMI(*BB, MI, DL,
12856             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12857                                               : TII->get(PPC::STQ))
12858         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12859         .addImm(0)
12860         .addReg(Ptr);
12861   } else {
12862     llvm_unreachable("Unexpected instr type to insert");
12863   }
12864 
12865   MI.eraseFromParent(); // The pseudo instruction is gone now.
12866   return BB;
12867 }
12868 
12869 //===----------------------------------------------------------------------===//
12870 // Target Optimization Hooks
12871 //===----------------------------------------------------------------------===//
12872 
12873 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12874   // For the estimates, convergence is quadratic, so we essentially double the
12875   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12876   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12877   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12878   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12879   if (VT.getScalarType() == MVT::f64)
12880     RefinementSteps++;
12881   return RefinementSteps;
12882 }
12883 
12884 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12885                                             const DenormalMode &Mode) const {
12886   // We only have VSX Vector Test for software Square Root.
12887   EVT VT = Op.getValueType();
12888   if (!isTypeLegal(MVT::i1) ||
12889       (VT != MVT::f64 &&
12890        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12891     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12892 
12893   SDLoc DL(Op);
12894   // The output register of FTSQRT is CR field.
12895   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12896   // ftsqrt BF,FRB
12897   // Let e_b be the unbiased exponent of the double-precision
12898   // floating-point operand in register FRB.
12899   // fe_flag is set to 1 if either of the following conditions occurs.
12900   //   - The double-precision floating-point operand in register FRB is a zero,
12901   //     a NaN, or an infinity, or a negative value.
12902   //   - e_b is less than or equal to -970.
12903   // Otherwise fe_flag is set to 0.
12904   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12905   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12906   // exponent is less than -970)
12907   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12908   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12909                                     FTSQRT, SRIdxVal),
12910                  0);
12911 }
12912 
12913 SDValue
12914 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12915                                                SelectionDAG &DAG) const {
12916   // We only have VSX Vector Square Root.
12917   EVT VT = Op.getValueType();
12918   if (VT != MVT::f64 &&
12919       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12920     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12921 
12922   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12923 }
12924 
12925 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12926                                            int Enabled, int &RefinementSteps,
12927                                            bool &UseOneConstNR,
12928                                            bool Reciprocal) const {
12929   EVT VT = Operand.getValueType();
12930   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12931       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12932       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12933       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12934     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12935       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12936 
12937     // The Newton-Raphson computation with a single constant does not provide
12938     // enough accuracy on some CPUs.
12939     UseOneConstNR = !Subtarget.needsTwoConstNR();
12940     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12941   }
12942   return SDValue();
12943 }
12944 
12945 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12946                                             int Enabled,
12947                                             int &RefinementSteps) const {
12948   EVT VT = Operand.getValueType();
12949   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12950       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12951       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12952       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12953     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12954       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12955     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12956   }
12957   return SDValue();
12958 }
12959 
12960 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12961   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12962   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12963   // enabled for division), this functionality is redundant with the default
12964   // combiner logic (once the division -> reciprocal/multiply transformation
12965   // has taken place). As a result, this matters more for older cores than for
12966   // newer ones.
12967 
12968   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12969   // reciprocal if there are two or more FDIVs (for embedded cores with only
12970   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12971   switch (Subtarget.getCPUDirective()) {
12972   default:
12973     return 3;
12974   case PPC::DIR_440:
12975   case PPC::DIR_A2:
12976   case PPC::DIR_E500:
12977   case PPC::DIR_E500mc:
12978   case PPC::DIR_E5500:
12979     return 2;
12980   }
12981 }
12982 
12983 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12984 // collapsed, and so we need to look through chains of them.
12985 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12986                                      int64_t& Offset, SelectionDAG &DAG) {
12987   if (DAG.isBaseWithConstantOffset(Loc)) {
12988     Base = Loc.getOperand(0);
12989     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12990 
12991     // The base might itself be a base plus an offset, and if so, accumulate
12992     // that as well.
12993     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12994   }
12995 }
12996 
12997 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12998                             unsigned Bytes, int Dist,
12999                             SelectionDAG &DAG) {
13000   if (VT.getSizeInBits() / 8 != Bytes)
13001     return false;
13002 
13003   SDValue BaseLoc = Base->getBasePtr();
13004   if (Loc.getOpcode() == ISD::FrameIndex) {
13005     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13006       return false;
13007     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13008     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13009     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13010     int FS  = MFI.getObjectSize(FI);
13011     int BFS = MFI.getObjectSize(BFI);
13012     if (FS != BFS || FS != (int)Bytes) return false;
13013     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13014   }
13015 
13016   SDValue Base1 = Loc, Base2 = BaseLoc;
13017   int64_t Offset1 = 0, Offset2 = 0;
13018   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13019   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13020   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13021     return true;
13022 
13023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13024   const GlobalValue *GV1 = nullptr;
13025   const GlobalValue *GV2 = nullptr;
13026   Offset1 = 0;
13027   Offset2 = 0;
13028   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13029   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13030   if (isGA1 && isGA2 && GV1 == GV2)
13031     return Offset1 == (Offset2 + Dist*Bytes);
13032   return false;
13033 }
13034 
13035 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13036 // not enforce equality of the chain operands.
13037 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13038                             unsigned Bytes, int Dist,
13039                             SelectionDAG &DAG) {
13040   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13041     EVT VT = LS->getMemoryVT();
13042     SDValue Loc = LS->getBasePtr();
13043     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13044   }
13045 
13046   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13047     EVT VT;
13048     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13049     default: return false;
13050     case Intrinsic::ppc_altivec_lvx:
13051     case Intrinsic::ppc_altivec_lvxl:
13052     case Intrinsic::ppc_vsx_lxvw4x:
13053     case Intrinsic::ppc_vsx_lxvw4x_be:
13054       VT = MVT::v4i32;
13055       break;
13056     case Intrinsic::ppc_vsx_lxvd2x:
13057     case Intrinsic::ppc_vsx_lxvd2x_be:
13058       VT = MVT::v2f64;
13059       break;
13060     case Intrinsic::ppc_altivec_lvebx:
13061       VT = MVT::i8;
13062       break;
13063     case Intrinsic::ppc_altivec_lvehx:
13064       VT = MVT::i16;
13065       break;
13066     case Intrinsic::ppc_altivec_lvewx:
13067       VT = MVT::i32;
13068       break;
13069     }
13070 
13071     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13072   }
13073 
13074   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13075     EVT VT;
13076     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13077     default: return false;
13078     case Intrinsic::ppc_altivec_stvx:
13079     case Intrinsic::ppc_altivec_stvxl:
13080     case Intrinsic::ppc_vsx_stxvw4x:
13081       VT = MVT::v4i32;
13082       break;
13083     case Intrinsic::ppc_vsx_stxvd2x:
13084       VT = MVT::v2f64;
13085       break;
13086     case Intrinsic::ppc_vsx_stxvw4x_be:
13087       VT = MVT::v4i32;
13088       break;
13089     case Intrinsic::ppc_vsx_stxvd2x_be:
13090       VT = MVT::v2f64;
13091       break;
13092     case Intrinsic::ppc_altivec_stvebx:
13093       VT = MVT::i8;
13094       break;
13095     case Intrinsic::ppc_altivec_stvehx:
13096       VT = MVT::i16;
13097       break;
13098     case Intrinsic::ppc_altivec_stvewx:
13099       VT = MVT::i32;
13100       break;
13101     }
13102 
13103     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13104   }
13105 
13106   return false;
13107 }
13108 
13109 // Return true is there is a nearyby consecutive load to the one provided
13110 // (regardless of alignment). We search up and down the chain, looking though
13111 // token factors and other loads (but nothing else). As a result, a true result
13112 // indicates that it is safe to create a new consecutive load adjacent to the
13113 // load provided.
13114 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13115   SDValue Chain = LD->getChain();
13116   EVT VT = LD->getMemoryVT();
13117 
13118   SmallSet<SDNode *, 16> LoadRoots;
13119   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13120   SmallSet<SDNode *, 16> Visited;
13121 
13122   // First, search up the chain, branching to follow all token-factor operands.
13123   // If we find a consecutive load, then we're done, otherwise, record all
13124   // nodes just above the top-level loads and token factors.
13125   while (!Queue.empty()) {
13126     SDNode *ChainNext = Queue.pop_back_val();
13127     if (!Visited.insert(ChainNext).second)
13128       continue;
13129 
13130     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13131       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13132         return true;
13133 
13134       if (!Visited.count(ChainLD->getChain().getNode()))
13135         Queue.push_back(ChainLD->getChain().getNode());
13136     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13137       for (const SDUse &O : ChainNext->ops())
13138         if (!Visited.count(O.getNode()))
13139           Queue.push_back(O.getNode());
13140     } else
13141       LoadRoots.insert(ChainNext);
13142   }
13143 
13144   // Second, search down the chain, starting from the top-level nodes recorded
13145   // in the first phase. These top-level nodes are the nodes just above all
13146   // loads and token factors. Starting with their uses, recursively look though
13147   // all loads (just the chain uses) and token factors to find a consecutive
13148   // load.
13149   Visited.clear();
13150   Queue.clear();
13151 
13152   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13153        IE = LoadRoots.end(); I != IE; ++I) {
13154     Queue.push_back(*I);
13155 
13156     while (!Queue.empty()) {
13157       SDNode *LoadRoot = Queue.pop_back_val();
13158       if (!Visited.insert(LoadRoot).second)
13159         continue;
13160 
13161       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13162         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13163           return true;
13164 
13165       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
13166            UE = LoadRoot->use_end(); UI != UE; ++UI)
13167         if (((isa<MemSDNode>(*UI) &&
13168             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
13169             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
13170           Queue.push_back(*UI);
13171     }
13172   }
13173 
13174   return false;
13175 }
13176 
13177 /// This function is called when we have proved that a SETCC node can be replaced
13178 /// by subtraction (and other supporting instructions) so that the result of
13179 /// comparison is kept in a GPR instead of CR. This function is purely for
13180 /// codegen purposes and has some flags to guide the codegen process.
13181 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13182                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13183   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13184 
13185   // Zero extend the operands to the largest legal integer. Originally, they
13186   // must be of a strictly smaller size.
13187   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13188                          DAG.getConstant(Size, DL, MVT::i32));
13189   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13190                          DAG.getConstant(Size, DL, MVT::i32));
13191 
13192   // Swap if needed. Depends on the condition code.
13193   if (Swap)
13194     std::swap(Op0, Op1);
13195 
13196   // Subtract extended integers.
13197   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13198 
13199   // Move the sign bit to the least significant position and zero out the rest.
13200   // Now the least significant bit carries the result of original comparison.
13201   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13202                              DAG.getConstant(Size - 1, DL, MVT::i32));
13203   auto Final = Shifted;
13204 
13205   // Complement the result if needed. Based on the condition code.
13206   if (Complement)
13207     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13208                         DAG.getConstant(1, DL, MVT::i64));
13209 
13210   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13211 }
13212 
13213 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13214                                                   DAGCombinerInfo &DCI) const {
13215   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13216 
13217   SelectionDAG &DAG = DCI.DAG;
13218   SDLoc DL(N);
13219 
13220   // Size of integers being compared has a critical role in the following
13221   // analysis, so we prefer to do this when all types are legal.
13222   if (!DCI.isAfterLegalizeDAG())
13223     return SDValue();
13224 
13225   // If all users of SETCC extend its value to a legal integer type
13226   // then we replace SETCC with a subtraction
13227   for (SDNode::use_iterator UI = N->use_begin(),
13228        UE = N->use_end(); UI != UE; ++UI) {
13229     if (UI->getOpcode() != ISD::ZERO_EXTEND)
13230       return SDValue();
13231   }
13232 
13233   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13234   auto OpSize = N->getOperand(0).getValueSizeInBits();
13235 
13236   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13237 
13238   if (OpSize < Size) {
13239     switch (CC) {
13240     default: break;
13241     case ISD::SETULT:
13242       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13243     case ISD::SETULE:
13244       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13245     case ISD::SETUGT:
13246       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13247     case ISD::SETUGE:
13248       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13249     }
13250   }
13251 
13252   return SDValue();
13253 }
13254 
13255 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13256                                                   DAGCombinerInfo &DCI) const {
13257   SelectionDAG &DAG = DCI.DAG;
13258   SDLoc dl(N);
13259 
13260   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13261   // If we're tracking CR bits, we need to be careful that we don't have:
13262   //   trunc(binary-ops(zext(x), zext(y)))
13263   // or
13264   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13265   // such that we're unnecessarily moving things into GPRs when it would be
13266   // better to keep them in CR bits.
13267 
13268   // Note that trunc here can be an actual i1 trunc, or can be the effective
13269   // truncation that comes from a setcc or select_cc.
13270   if (N->getOpcode() == ISD::TRUNCATE &&
13271       N->getValueType(0) != MVT::i1)
13272     return SDValue();
13273 
13274   if (N->getOperand(0).getValueType() != MVT::i32 &&
13275       N->getOperand(0).getValueType() != MVT::i64)
13276     return SDValue();
13277 
13278   if (N->getOpcode() == ISD::SETCC ||
13279       N->getOpcode() == ISD::SELECT_CC) {
13280     // If we're looking at a comparison, then we need to make sure that the
13281     // high bits (all except for the first) don't matter the result.
13282     ISD::CondCode CC =
13283       cast<CondCodeSDNode>(N->getOperand(
13284         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13285     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13286 
13287     if (ISD::isSignedIntSetCC(CC)) {
13288       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13289           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13290         return SDValue();
13291     } else if (ISD::isUnsignedIntSetCC(CC)) {
13292       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13293                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13294           !DAG.MaskedValueIsZero(N->getOperand(1),
13295                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13296         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13297                                              : SDValue());
13298     } else {
13299       // This is neither a signed nor an unsigned comparison, just make sure
13300       // that the high bits are equal.
13301       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13302       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13303 
13304       // We don't really care about what is known about the first bit (if
13305       // anything), so pretend that it is known zero for both to ensure they can
13306       // be compared as constants.
13307       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13308       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13309 
13310       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13311           Op1Known.getConstant() != Op2Known.getConstant())
13312         return SDValue();
13313     }
13314   }
13315 
13316   // We now know that the higher-order bits are irrelevant, we just need to
13317   // make sure that all of the intermediate operations are bit operations, and
13318   // all inputs are extensions.
13319   if (N->getOperand(0).getOpcode() != ISD::AND &&
13320       N->getOperand(0).getOpcode() != ISD::OR  &&
13321       N->getOperand(0).getOpcode() != ISD::XOR &&
13322       N->getOperand(0).getOpcode() != ISD::SELECT &&
13323       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13324       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13325       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13326       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13327       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13328     return SDValue();
13329 
13330   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13331       N->getOperand(1).getOpcode() != ISD::AND &&
13332       N->getOperand(1).getOpcode() != ISD::OR  &&
13333       N->getOperand(1).getOpcode() != ISD::XOR &&
13334       N->getOperand(1).getOpcode() != ISD::SELECT &&
13335       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13336       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13337       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13338       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13339       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13340     return SDValue();
13341 
13342   SmallVector<SDValue, 4> Inputs;
13343   SmallVector<SDValue, 8> BinOps, PromOps;
13344   SmallPtrSet<SDNode *, 16> Visited;
13345 
13346   for (unsigned i = 0; i < 2; ++i) {
13347     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13348           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13349           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13350           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13351         isa<ConstantSDNode>(N->getOperand(i)))
13352       Inputs.push_back(N->getOperand(i));
13353     else
13354       BinOps.push_back(N->getOperand(i));
13355 
13356     if (N->getOpcode() == ISD::TRUNCATE)
13357       break;
13358   }
13359 
13360   // Visit all inputs, collect all binary operations (and, or, xor and
13361   // select) that are all fed by extensions.
13362   while (!BinOps.empty()) {
13363     SDValue BinOp = BinOps.pop_back_val();
13364 
13365     if (!Visited.insert(BinOp.getNode()).second)
13366       continue;
13367 
13368     PromOps.push_back(BinOp);
13369 
13370     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13371       // The condition of the select is not promoted.
13372       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13373         continue;
13374       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13375         continue;
13376 
13377       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13378             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13379             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13380            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13381           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13382         Inputs.push_back(BinOp.getOperand(i));
13383       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13384                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13385                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13386                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13387                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13388                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13389                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13390                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13391                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13392         BinOps.push_back(BinOp.getOperand(i));
13393       } else {
13394         // We have an input that is not an extension or another binary
13395         // operation; we'll abort this transformation.
13396         return SDValue();
13397       }
13398     }
13399   }
13400 
13401   // Make sure that this is a self-contained cluster of operations (which
13402   // is not quite the same thing as saying that everything has only one
13403   // use).
13404   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13405     if (isa<ConstantSDNode>(Inputs[i]))
13406       continue;
13407 
13408     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13409                               UE = Inputs[i].getNode()->use_end();
13410          UI != UE; ++UI) {
13411       SDNode *User = *UI;
13412       if (User != N && !Visited.count(User))
13413         return SDValue();
13414 
13415       // Make sure that we're not going to promote the non-output-value
13416       // operand(s) or SELECT or SELECT_CC.
13417       // FIXME: Although we could sometimes handle this, and it does occur in
13418       // practice that one of the condition inputs to the select is also one of
13419       // the outputs, we currently can't deal with this.
13420       if (User->getOpcode() == ISD::SELECT) {
13421         if (User->getOperand(0) == Inputs[i])
13422           return SDValue();
13423       } else if (User->getOpcode() == ISD::SELECT_CC) {
13424         if (User->getOperand(0) == Inputs[i] ||
13425             User->getOperand(1) == Inputs[i])
13426           return SDValue();
13427       }
13428     }
13429   }
13430 
13431   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13432     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13433                               UE = PromOps[i].getNode()->use_end();
13434          UI != UE; ++UI) {
13435       SDNode *User = *UI;
13436       if (User != N && !Visited.count(User))
13437         return SDValue();
13438 
13439       // Make sure that we're not going to promote the non-output-value
13440       // operand(s) or SELECT or SELECT_CC.
13441       // FIXME: Although we could sometimes handle this, and it does occur in
13442       // practice that one of the condition inputs to the select is also one of
13443       // the outputs, we currently can't deal with this.
13444       if (User->getOpcode() == ISD::SELECT) {
13445         if (User->getOperand(0) == PromOps[i])
13446           return SDValue();
13447       } else if (User->getOpcode() == ISD::SELECT_CC) {
13448         if (User->getOperand(0) == PromOps[i] ||
13449             User->getOperand(1) == PromOps[i])
13450           return SDValue();
13451       }
13452     }
13453   }
13454 
13455   // Replace all inputs with the extension operand.
13456   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13457     // Constants may have users outside the cluster of to-be-promoted nodes,
13458     // and so we need to replace those as we do the promotions.
13459     if (isa<ConstantSDNode>(Inputs[i]))
13460       continue;
13461     else
13462       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13463   }
13464 
13465   std::list<HandleSDNode> PromOpHandles;
13466   for (auto &PromOp : PromOps)
13467     PromOpHandles.emplace_back(PromOp);
13468 
13469   // Replace all operations (these are all the same, but have a different
13470   // (i1) return type). DAG.getNode will validate that the types of
13471   // a binary operator match, so go through the list in reverse so that
13472   // we've likely promoted both operands first. Any intermediate truncations or
13473   // extensions disappear.
13474   while (!PromOpHandles.empty()) {
13475     SDValue PromOp = PromOpHandles.back().getValue();
13476     PromOpHandles.pop_back();
13477 
13478     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13479         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13480         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13481         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13482       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13483           PromOp.getOperand(0).getValueType() != MVT::i1) {
13484         // The operand is not yet ready (see comment below).
13485         PromOpHandles.emplace_front(PromOp);
13486         continue;
13487       }
13488 
13489       SDValue RepValue = PromOp.getOperand(0);
13490       if (isa<ConstantSDNode>(RepValue))
13491         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13492 
13493       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13494       continue;
13495     }
13496 
13497     unsigned C;
13498     switch (PromOp.getOpcode()) {
13499     default:             C = 0; break;
13500     case ISD::SELECT:    C = 1; break;
13501     case ISD::SELECT_CC: C = 2; break;
13502     }
13503 
13504     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13505          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13506         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13507          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13508       // The to-be-promoted operands of this node have not yet been
13509       // promoted (this should be rare because we're going through the
13510       // list backward, but if one of the operands has several users in
13511       // this cluster of to-be-promoted nodes, it is possible).
13512       PromOpHandles.emplace_front(PromOp);
13513       continue;
13514     }
13515 
13516     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13517                                 PromOp.getNode()->op_end());
13518 
13519     // If there are any constant inputs, make sure they're replaced now.
13520     for (unsigned i = 0; i < 2; ++i)
13521       if (isa<ConstantSDNode>(Ops[C+i]))
13522         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13523 
13524     DAG.ReplaceAllUsesOfValueWith(PromOp,
13525       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13526   }
13527 
13528   // Now we're left with the initial truncation itself.
13529   if (N->getOpcode() == ISD::TRUNCATE)
13530     return N->getOperand(0);
13531 
13532   // Otherwise, this is a comparison. The operands to be compared have just
13533   // changed type (to i1), but everything else is the same.
13534   return SDValue(N, 0);
13535 }
13536 
13537 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13538                                                   DAGCombinerInfo &DCI) const {
13539   SelectionDAG &DAG = DCI.DAG;
13540   SDLoc dl(N);
13541 
13542   // If we're tracking CR bits, we need to be careful that we don't have:
13543   //   zext(binary-ops(trunc(x), trunc(y)))
13544   // or
13545   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13546   // such that we're unnecessarily moving things into CR bits that can more
13547   // efficiently stay in GPRs. Note that if we're not certain that the high
13548   // bits are set as required by the final extension, we still may need to do
13549   // some masking to get the proper behavior.
13550 
13551   // This same functionality is important on PPC64 when dealing with
13552   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13553   // the return values of functions. Because it is so similar, it is handled
13554   // here as well.
13555 
13556   if (N->getValueType(0) != MVT::i32 &&
13557       N->getValueType(0) != MVT::i64)
13558     return SDValue();
13559 
13560   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13561         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13562     return SDValue();
13563 
13564   if (N->getOperand(0).getOpcode() != ISD::AND &&
13565       N->getOperand(0).getOpcode() != ISD::OR  &&
13566       N->getOperand(0).getOpcode() != ISD::XOR &&
13567       N->getOperand(0).getOpcode() != ISD::SELECT &&
13568       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13569     return SDValue();
13570 
13571   SmallVector<SDValue, 4> Inputs;
13572   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13573   SmallPtrSet<SDNode *, 16> Visited;
13574 
13575   // Visit all inputs, collect all binary operations (and, or, xor and
13576   // select) that are all fed by truncations.
13577   while (!BinOps.empty()) {
13578     SDValue BinOp = BinOps.pop_back_val();
13579 
13580     if (!Visited.insert(BinOp.getNode()).second)
13581       continue;
13582 
13583     PromOps.push_back(BinOp);
13584 
13585     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13586       // The condition of the select is not promoted.
13587       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13588         continue;
13589       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13590         continue;
13591 
13592       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13593           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13594         Inputs.push_back(BinOp.getOperand(i));
13595       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13596                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13597                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13598                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13599                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13600         BinOps.push_back(BinOp.getOperand(i));
13601       } else {
13602         // We have an input that is not a truncation or another binary
13603         // operation; we'll abort this transformation.
13604         return SDValue();
13605       }
13606     }
13607   }
13608 
13609   // The operands of a select that must be truncated when the select is
13610   // promoted because the operand is actually part of the to-be-promoted set.
13611   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13612 
13613   // Make sure that this is a self-contained cluster of operations (which
13614   // is not quite the same thing as saying that everything has only one
13615   // use).
13616   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13617     if (isa<ConstantSDNode>(Inputs[i]))
13618       continue;
13619 
13620     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13621                               UE = Inputs[i].getNode()->use_end();
13622          UI != UE; ++UI) {
13623       SDNode *User = *UI;
13624       if (User != N && !Visited.count(User))
13625         return SDValue();
13626 
13627       // If we're going to promote the non-output-value operand(s) or SELECT or
13628       // SELECT_CC, record them for truncation.
13629       if (User->getOpcode() == ISD::SELECT) {
13630         if (User->getOperand(0) == Inputs[i])
13631           SelectTruncOp[0].insert(std::make_pair(User,
13632                                     User->getOperand(0).getValueType()));
13633       } else if (User->getOpcode() == ISD::SELECT_CC) {
13634         if (User->getOperand(0) == Inputs[i])
13635           SelectTruncOp[0].insert(std::make_pair(User,
13636                                     User->getOperand(0).getValueType()));
13637         if (User->getOperand(1) == Inputs[i])
13638           SelectTruncOp[1].insert(std::make_pair(User,
13639                                     User->getOperand(1).getValueType()));
13640       }
13641     }
13642   }
13643 
13644   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13645     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13646                               UE = PromOps[i].getNode()->use_end();
13647          UI != UE; ++UI) {
13648       SDNode *User = *UI;
13649       if (User != N && !Visited.count(User))
13650         return SDValue();
13651 
13652       // If we're going to promote the non-output-value operand(s) or SELECT or
13653       // SELECT_CC, record them for truncation.
13654       if (User->getOpcode() == ISD::SELECT) {
13655         if (User->getOperand(0) == PromOps[i])
13656           SelectTruncOp[0].insert(std::make_pair(User,
13657                                     User->getOperand(0).getValueType()));
13658       } else if (User->getOpcode() == ISD::SELECT_CC) {
13659         if (User->getOperand(0) == PromOps[i])
13660           SelectTruncOp[0].insert(std::make_pair(User,
13661                                     User->getOperand(0).getValueType()));
13662         if (User->getOperand(1) == PromOps[i])
13663           SelectTruncOp[1].insert(std::make_pair(User,
13664                                     User->getOperand(1).getValueType()));
13665       }
13666     }
13667   }
13668 
13669   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13670   bool ReallyNeedsExt = false;
13671   if (N->getOpcode() != ISD::ANY_EXTEND) {
13672     // If all of the inputs are not already sign/zero extended, then
13673     // we'll still need to do that at the end.
13674     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13675       if (isa<ConstantSDNode>(Inputs[i]))
13676         continue;
13677 
13678       unsigned OpBits =
13679         Inputs[i].getOperand(0).getValueSizeInBits();
13680       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13681 
13682       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13683            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13684                                   APInt::getHighBitsSet(OpBits,
13685                                                         OpBits-PromBits))) ||
13686           (N->getOpcode() == ISD::SIGN_EXTEND &&
13687            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13688              (OpBits-(PromBits-1)))) {
13689         ReallyNeedsExt = true;
13690         break;
13691       }
13692     }
13693   }
13694 
13695   // Replace all inputs, either with the truncation operand, or a
13696   // truncation or extension to the final output type.
13697   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13698     // Constant inputs need to be replaced with the to-be-promoted nodes that
13699     // use them because they might have users outside of the cluster of
13700     // promoted nodes.
13701     if (isa<ConstantSDNode>(Inputs[i]))
13702       continue;
13703 
13704     SDValue InSrc = Inputs[i].getOperand(0);
13705     if (Inputs[i].getValueType() == N->getValueType(0))
13706       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13707     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13708       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13709         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13710     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13711       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13712         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13713     else
13714       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13715         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13716   }
13717 
13718   std::list<HandleSDNode> PromOpHandles;
13719   for (auto &PromOp : PromOps)
13720     PromOpHandles.emplace_back(PromOp);
13721 
13722   // Replace all operations (these are all the same, but have a different
13723   // (promoted) return type). DAG.getNode will validate that the types of
13724   // a binary operator match, so go through the list in reverse so that
13725   // we've likely promoted both operands first.
13726   while (!PromOpHandles.empty()) {
13727     SDValue PromOp = PromOpHandles.back().getValue();
13728     PromOpHandles.pop_back();
13729 
13730     unsigned C;
13731     switch (PromOp.getOpcode()) {
13732     default:             C = 0; break;
13733     case ISD::SELECT:    C = 1; break;
13734     case ISD::SELECT_CC: C = 2; break;
13735     }
13736 
13737     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13738          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13739         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13740          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13741       // The to-be-promoted operands of this node have not yet been
13742       // promoted (this should be rare because we're going through the
13743       // list backward, but if one of the operands has several users in
13744       // this cluster of to-be-promoted nodes, it is possible).
13745       PromOpHandles.emplace_front(PromOp);
13746       continue;
13747     }
13748 
13749     // For SELECT and SELECT_CC nodes, we do a similar check for any
13750     // to-be-promoted comparison inputs.
13751     if (PromOp.getOpcode() == ISD::SELECT ||
13752         PromOp.getOpcode() == ISD::SELECT_CC) {
13753       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13754            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13755           (SelectTruncOp[1].count(PromOp.getNode()) &&
13756            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13757         PromOpHandles.emplace_front(PromOp);
13758         continue;
13759       }
13760     }
13761 
13762     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13763                                 PromOp.getNode()->op_end());
13764 
13765     // If this node has constant inputs, then they'll need to be promoted here.
13766     for (unsigned i = 0; i < 2; ++i) {
13767       if (!isa<ConstantSDNode>(Ops[C+i]))
13768         continue;
13769       if (Ops[C+i].getValueType() == N->getValueType(0))
13770         continue;
13771 
13772       if (N->getOpcode() == ISD::SIGN_EXTEND)
13773         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13774       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13775         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13776       else
13777         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13778     }
13779 
13780     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13781     // truncate them again to the original value type.
13782     if (PromOp.getOpcode() == ISD::SELECT ||
13783         PromOp.getOpcode() == ISD::SELECT_CC) {
13784       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13785       if (SI0 != SelectTruncOp[0].end())
13786         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13787       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13788       if (SI1 != SelectTruncOp[1].end())
13789         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13790     }
13791 
13792     DAG.ReplaceAllUsesOfValueWith(PromOp,
13793       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13794   }
13795 
13796   // Now we're left with the initial extension itself.
13797   if (!ReallyNeedsExt)
13798     return N->getOperand(0);
13799 
13800   // To zero extend, just mask off everything except for the first bit (in the
13801   // i1 case).
13802   if (N->getOpcode() == ISD::ZERO_EXTEND)
13803     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13804                        DAG.getConstant(APInt::getLowBitsSet(
13805                                          N->getValueSizeInBits(0), PromBits),
13806                                        dl, N->getValueType(0)));
13807 
13808   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13809          "Invalid extension type");
13810   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13811   SDValue ShiftCst =
13812       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13813   return DAG.getNode(
13814       ISD::SRA, dl, N->getValueType(0),
13815       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13816       ShiftCst);
13817 }
13818 
13819 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13820                                         DAGCombinerInfo &DCI) const {
13821   assert(N->getOpcode() == ISD::SETCC &&
13822          "Should be called with a SETCC node");
13823 
13824   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13825   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13826     SDValue LHS = N->getOperand(0);
13827     SDValue RHS = N->getOperand(1);
13828 
13829     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13830     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13831         LHS.hasOneUse())
13832       std::swap(LHS, RHS);
13833 
13834     // x == 0-y --> x+y == 0
13835     // x != 0-y --> x+y != 0
13836     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13837         RHS.hasOneUse()) {
13838       SDLoc DL(N);
13839       SelectionDAG &DAG = DCI.DAG;
13840       EVT VT = N->getValueType(0);
13841       EVT OpVT = LHS.getValueType();
13842       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13843       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13844     }
13845   }
13846 
13847   return DAGCombineTruncBoolExt(N, DCI);
13848 }
13849 
13850 // Is this an extending load from an f32 to an f64?
13851 static bool isFPExtLoad(SDValue Op) {
13852   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13853     return LD->getExtensionType() == ISD::EXTLOAD &&
13854       Op.getValueType() == MVT::f64;
13855   return false;
13856 }
13857 
13858 /// Reduces the number of fp-to-int conversion when building a vector.
13859 ///
13860 /// If this vector is built out of floating to integer conversions,
13861 /// transform it to a vector built out of floating point values followed by a
13862 /// single floating to integer conversion of the vector.
13863 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13864 /// becomes (fptosi (build_vector ($A, $B, ...)))
13865 SDValue PPCTargetLowering::
13866 combineElementTruncationToVectorTruncation(SDNode *N,
13867                                            DAGCombinerInfo &DCI) const {
13868   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13869          "Should be called with a BUILD_VECTOR node");
13870 
13871   SelectionDAG &DAG = DCI.DAG;
13872   SDLoc dl(N);
13873 
13874   SDValue FirstInput = N->getOperand(0);
13875   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13876          "The input operand must be an fp-to-int conversion.");
13877 
13878   // This combine happens after legalization so the fp_to_[su]i nodes are
13879   // already converted to PPCSISD nodes.
13880   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13881   if (FirstConversion == PPCISD::FCTIDZ ||
13882       FirstConversion == PPCISD::FCTIDUZ ||
13883       FirstConversion == PPCISD::FCTIWZ ||
13884       FirstConversion == PPCISD::FCTIWUZ) {
13885     bool IsSplat = true;
13886     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13887       FirstConversion == PPCISD::FCTIWUZ;
13888     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13889     SmallVector<SDValue, 4> Ops;
13890     EVT TargetVT = N->getValueType(0);
13891     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13892       SDValue NextOp = N->getOperand(i);
13893       if (NextOp.getOpcode() != PPCISD::MFVSR)
13894         return SDValue();
13895       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13896       if (NextConversion != FirstConversion)
13897         return SDValue();
13898       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13899       // This is not valid if the input was originally double precision. It is
13900       // also not profitable to do unless this is an extending load in which
13901       // case doing this combine will allow us to combine consecutive loads.
13902       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13903         return SDValue();
13904       if (N->getOperand(i) != FirstInput)
13905         IsSplat = false;
13906     }
13907 
13908     // If this is a splat, we leave it as-is since there will be only a single
13909     // fp-to-int conversion followed by a splat of the integer. This is better
13910     // for 32-bit and smaller ints and neutral for 64-bit ints.
13911     if (IsSplat)
13912       return SDValue();
13913 
13914     // Now that we know we have the right type of node, get its operands
13915     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13916       SDValue In = N->getOperand(i).getOperand(0);
13917       if (Is32Bit) {
13918         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13919         // here, we know that all inputs are extending loads so this is safe).
13920         if (In.isUndef())
13921           Ops.push_back(DAG.getUNDEF(SrcVT));
13922         else {
13923           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13924                                       MVT::f32, In.getOperand(0),
13925                                       DAG.getIntPtrConstant(1, dl));
13926           Ops.push_back(Trunc);
13927         }
13928       } else
13929         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13930     }
13931 
13932     unsigned Opcode;
13933     if (FirstConversion == PPCISD::FCTIDZ ||
13934         FirstConversion == PPCISD::FCTIWZ)
13935       Opcode = ISD::FP_TO_SINT;
13936     else
13937       Opcode = ISD::FP_TO_UINT;
13938 
13939     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13940     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13941     return DAG.getNode(Opcode, dl, TargetVT, BV);
13942   }
13943   return SDValue();
13944 }
13945 
13946 /// Reduce the number of loads when building a vector.
13947 ///
13948 /// Building a vector out of multiple loads can be converted to a load
13949 /// of the vector type if the loads are consecutive. If the loads are
13950 /// consecutive but in descending order, a shuffle is added at the end
13951 /// to reorder the vector.
13952 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13953   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13954          "Should be called with a BUILD_VECTOR node");
13955 
13956   SDLoc dl(N);
13957 
13958   // Return early for non byte-sized type, as they can't be consecutive.
13959   if (!N->getValueType(0).getVectorElementType().isByteSized())
13960     return SDValue();
13961 
13962   bool InputsAreConsecutiveLoads = true;
13963   bool InputsAreReverseConsecutive = true;
13964   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13965   SDValue FirstInput = N->getOperand(0);
13966   bool IsRoundOfExtLoad = false;
13967 
13968   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13969       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13970     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13971     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13972   }
13973   // Not a build vector of (possibly fp_rounded) loads.
13974   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13975       N->getNumOperands() == 1)
13976     return SDValue();
13977 
13978   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13979     // If any inputs are fp_round(extload), they all must be.
13980     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13981       return SDValue();
13982 
13983     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13984       N->getOperand(i);
13985     if (NextInput.getOpcode() != ISD::LOAD)
13986       return SDValue();
13987 
13988     SDValue PreviousInput =
13989       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13990     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13991     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13992 
13993     // If any inputs are fp_round(extload), they all must be.
13994     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13995       return SDValue();
13996 
13997     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13998       InputsAreConsecutiveLoads = false;
13999     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14000       InputsAreReverseConsecutive = false;
14001 
14002     // Exit early if the loads are neither consecutive nor reverse consecutive.
14003     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14004       return SDValue();
14005   }
14006 
14007   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14008          "The loads cannot be both consecutive and reverse consecutive.");
14009 
14010   SDValue FirstLoadOp =
14011     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14012   SDValue LastLoadOp =
14013     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14014                        N->getOperand(N->getNumOperands()-1);
14015 
14016   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14017   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14018   if (InputsAreConsecutiveLoads) {
14019     assert(LD1 && "Input needs to be a LoadSDNode.");
14020     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14021                        LD1->getBasePtr(), LD1->getPointerInfo(),
14022                        LD1->getAlignment());
14023   }
14024   if (InputsAreReverseConsecutive) {
14025     assert(LDL && "Input needs to be a LoadSDNode.");
14026     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14027                                LDL->getBasePtr(), LDL->getPointerInfo(),
14028                                LDL->getAlignment());
14029     SmallVector<int, 16> Ops;
14030     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14031       Ops.push_back(i);
14032 
14033     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14034                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14035   }
14036   return SDValue();
14037 }
14038 
14039 // This function adds the required vector_shuffle needed to get
14040 // the elements of the vector extract in the correct position
14041 // as specified by the CorrectElems encoding.
14042 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14043                                       SDValue Input, uint64_t Elems,
14044                                       uint64_t CorrectElems) {
14045   SDLoc dl(N);
14046 
14047   unsigned NumElems = Input.getValueType().getVectorNumElements();
14048   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14049 
14050   // Knowing the element indices being extracted from the original
14051   // vector and the order in which they're being inserted, just put
14052   // them at element indices required for the instruction.
14053   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14054     if (DAG.getDataLayout().isLittleEndian())
14055       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14056     else
14057       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14058     CorrectElems = CorrectElems >> 8;
14059     Elems = Elems >> 8;
14060   }
14061 
14062   SDValue Shuffle =
14063       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14064                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14065 
14066   EVT VT = N->getValueType(0);
14067   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14068 
14069   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14070                                Input.getValueType().getVectorElementType(),
14071                                VT.getVectorNumElements());
14072   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14073                      DAG.getValueType(ExtVT));
14074 }
14075 
14076 // Look for build vector patterns where input operands come from sign
14077 // extended vector_extract elements of specific indices. If the correct indices
14078 // aren't used, add a vector shuffle to fix up the indices and create
14079 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14080 // during instruction selection.
14081 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14082   // This array encodes the indices that the vector sign extend instructions
14083   // extract from when extending from one type to another for both BE and LE.
14084   // The right nibble of each byte corresponds to the LE incides.
14085   // and the left nibble of each byte corresponds to the BE incides.
14086   // For example: 0x3074B8FC  byte->word
14087   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14088   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14089   // For example: 0x000070F8  byte->double word
14090   // For LE: the allowed indices are: 0x0,0x8
14091   // For BE: the allowed indices are: 0x7,0xF
14092   uint64_t TargetElems[] = {
14093       0x3074B8FC, // b->w
14094       0x000070F8, // b->d
14095       0x10325476, // h->w
14096       0x00003074, // h->d
14097       0x00001032, // w->d
14098   };
14099 
14100   uint64_t Elems = 0;
14101   int Index;
14102   SDValue Input;
14103 
14104   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14105     if (!Op)
14106       return false;
14107     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14108         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14109       return false;
14110 
14111     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14112     // of the right width.
14113     SDValue Extract = Op.getOperand(0);
14114     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14115       Extract = Extract.getOperand(0);
14116     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14117       return false;
14118 
14119     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14120     if (!ExtOp)
14121       return false;
14122 
14123     Index = ExtOp->getZExtValue();
14124     if (Input && Input != Extract.getOperand(0))
14125       return false;
14126 
14127     if (!Input)
14128       Input = Extract.getOperand(0);
14129 
14130     Elems = Elems << 8;
14131     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14132     Elems |= Index;
14133 
14134     return true;
14135   };
14136 
14137   // If the build vector operands aren't sign extended vector extracts,
14138   // of the same input vector, then return.
14139   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14140     if (!isSExtOfVecExtract(N->getOperand(i))) {
14141       return SDValue();
14142     }
14143   }
14144 
14145   // If the vector extract indicies are not correct, add the appropriate
14146   // vector_shuffle.
14147   int TgtElemArrayIdx;
14148   int InputSize = Input.getValueType().getScalarSizeInBits();
14149   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14150   if (InputSize + OutputSize == 40)
14151     TgtElemArrayIdx = 0;
14152   else if (InputSize + OutputSize == 72)
14153     TgtElemArrayIdx = 1;
14154   else if (InputSize + OutputSize == 48)
14155     TgtElemArrayIdx = 2;
14156   else if (InputSize + OutputSize == 80)
14157     TgtElemArrayIdx = 3;
14158   else if (InputSize + OutputSize == 96)
14159     TgtElemArrayIdx = 4;
14160   else
14161     return SDValue();
14162 
14163   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14164   CorrectElems = DAG.getDataLayout().isLittleEndian()
14165                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14166                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14167   if (Elems != CorrectElems) {
14168     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14169   }
14170 
14171   // Regular lowering will catch cases where a shuffle is not needed.
14172   return SDValue();
14173 }
14174 
14175 // Look for the pattern of a load from a narrow width to i128, feeding
14176 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14177 // (LXVRZX). This node represents a zero extending load that will be matched
14178 // to the Load VSX Vector Rightmost instructions.
14179 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14180   SDLoc DL(N);
14181 
14182   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14183   if (N->getValueType(0) != MVT::v1i128)
14184     return SDValue();
14185 
14186   SDValue Operand = N->getOperand(0);
14187   // Proceed with the transformation if the operand to the BUILD_VECTOR
14188   // is a load instruction.
14189   if (Operand.getOpcode() != ISD::LOAD)
14190     return SDValue();
14191 
14192   auto *LD = cast<LoadSDNode>(Operand);
14193   EVT MemoryType = LD->getMemoryVT();
14194 
14195   // This transformation is only valid if the we are loading either a byte,
14196   // halfword, word, or doubleword.
14197   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14198                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14199 
14200   // Ensure that the load from the narrow width is being zero extended to i128.
14201   if (!ValidLDType ||
14202       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14203        LD->getExtensionType() != ISD::EXTLOAD))
14204     return SDValue();
14205 
14206   SDValue LoadOps[] = {
14207       LD->getChain(), LD->getBasePtr(),
14208       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14209 
14210   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14211                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14212                                  LoadOps, MemoryType, LD->getMemOperand());
14213 }
14214 
14215 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14216                                                  DAGCombinerInfo &DCI) const {
14217   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14218          "Should be called with a BUILD_VECTOR node");
14219 
14220   SelectionDAG &DAG = DCI.DAG;
14221   SDLoc dl(N);
14222 
14223   if (!Subtarget.hasVSX())
14224     return SDValue();
14225 
14226   // The target independent DAG combiner will leave a build_vector of
14227   // float-to-int conversions intact. We can generate MUCH better code for
14228   // a float-to-int conversion of a vector of floats.
14229   SDValue FirstInput = N->getOperand(0);
14230   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14231     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14232     if (Reduced)
14233       return Reduced;
14234   }
14235 
14236   // If we're building a vector out of consecutive loads, just load that
14237   // vector type.
14238   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14239   if (Reduced)
14240     return Reduced;
14241 
14242   // If we're building a vector out of extended elements from another vector
14243   // we have P9 vector integer extend instructions. The code assumes legal
14244   // input types (i.e. it can't handle things like v4i16) so do not run before
14245   // legalization.
14246   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14247     Reduced = combineBVOfVecSExt(N, DAG);
14248     if (Reduced)
14249       return Reduced;
14250   }
14251 
14252   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14253   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14254   // is a load from <valid narrow width> to i128.
14255   if (Subtarget.isISA3_1()) {
14256     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14257     if (BVOfZLoad)
14258       return BVOfZLoad;
14259   }
14260 
14261   if (N->getValueType(0) != MVT::v2f64)
14262     return SDValue();
14263 
14264   // Looking for:
14265   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14266   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14267       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14268     return SDValue();
14269   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14270       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14271     return SDValue();
14272   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14273     return SDValue();
14274 
14275   SDValue Ext1 = FirstInput.getOperand(0);
14276   SDValue Ext2 = N->getOperand(1).getOperand(0);
14277   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14278      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14279     return SDValue();
14280 
14281   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14282   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14283   if (!Ext1Op || !Ext2Op)
14284     return SDValue();
14285   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14286       Ext1.getOperand(0) != Ext2.getOperand(0))
14287     return SDValue();
14288 
14289   int FirstElem = Ext1Op->getZExtValue();
14290   int SecondElem = Ext2Op->getZExtValue();
14291   int SubvecIdx;
14292   if (FirstElem == 0 && SecondElem == 1)
14293     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14294   else if (FirstElem == 2 && SecondElem == 3)
14295     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14296   else
14297     return SDValue();
14298 
14299   SDValue SrcVec = Ext1.getOperand(0);
14300   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14301     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14302   return DAG.getNode(NodeType, dl, MVT::v2f64,
14303                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14304 }
14305 
14306 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14307                                               DAGCombinerInfo &DCI) const {
14308   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14309           N->getOpcode() == ISD::UINT_TO_FP) &&
14310          "Need an int -> FP conversion node here");
14311 
14312   if (useSoftFloat() || !Subtarget.has64BitSupport())
14313     return SDValue();
14314 
14315   SelectionDAG &DAG = DCI.DAG;
14316   SDLoc dl(N);
14317   SDValue Op(N, 0);
14318 
14319   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14320   // from the hardware.
14321   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14322     return SDValue();
14323   if (!Op.getOperand(0).getValueType().isSimple())
14324     return SDValue();
14325   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14326       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14327     return SDValue();
14328 
14329   SDValue FirstOperand(Op.getOperand(0));
14330   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14331     (FirstOperand.getValueType() == MVT::i8 ||
14332      FirstOperand.getValueType() == MVT::i16);
14333   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14334     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14335     bool DstDouble = Op.getValueType() == MVT::f64;
14336     unsigned ConvOp = Signed ?
14337       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14338       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14339     SDValue WidthConst =
14340       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14341                             dl, false);
14342     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14343     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14344     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14345                                          DAG.getVTList(MVT::f64, MVT::Other),
14346                                          Ops, MVT::i8, LDN->getMemOperand());
14347 
14348     // For signed conversion, we need to sign-extend the value in the VSR
14349     if (Signed) {
14350       SDValue ExtOps[] = { Ld, WidthConst };
14351       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14352       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14353     } else
14354       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14355   }
14356 
14357 
14358   // For i32 intermediate values, unfortunately, the conversion functions
14359   // leave the upper 32 bits of the value are undefined. Within the set of
14360   // scalar instructions, we have no method for zero- or sign-extending the
14361   // value. Thus, we cannot handle i32 intermediate values here.
14362   if (Op.getOperand(0).getValueType() == MVT::i32)
14363     return SDValue();
14364 
14365   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14366          "UINT_TO_FP is supported only with FPCVT");
14367 
14368   // If we have FCFIDS, then use it when converting to single-precision.
14369   // Otherwise, convert to double-precision and then round.
14370   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14371                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14372                                                             : PPCISD::FCFIDS)
14373                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14374                                                             : PPCISD::FCFID);
14375   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14376                   ? MVT::f32
14377                   : MVT::f64;
14378 
14379   // If we're converting from a float, to an int, and back to a float again,
14380   // then we don't need the store/load pair at all.
14381   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14382        Subtarget.hasFPCVT()) ||
14383       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14384     SDValue Src = Op.getOperand(0).getOperand(0);
14385     if (Src.getValueType() == MVT::f32) {
14386       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14387       DCI.AddToWorklist(Src.getNode());
14388     } else if (Src.getValueType() != MVT::f64) {
14389       // Make sure that we don't pick up a ppc_fp128 source value.
14390       return SDValue();
14391     }
14392 
14393     unsigned FCTOp =
14394       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14395                                                         PPCISD::FCTIDUZ;
14396 
14397     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14398     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14399 
14400     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14401       FP = DAG.getNode(ISD::FP_ROUND, dl,
14402                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14403       DCI.AddToWorklist(FP.getNode());
14404     }
14405 
14406     return FP;
14407   }
14408 
14409   return SDValue();
14410 }
14411 
14412 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14413 // builtins) into loads with swaps.
14414 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14415                                               DAGCombinerInfo &DCI) const {
14416   SelectionDAG &DAG = DCI.DAG;
14417   SDLoc dl(N);
14418   SDValue Chain;
14419   SDValue Base;
14420   MachineMemOperand *MMO;
14421 
14422   switch (N->getOpcode()) {
14423   default:
14424     llvm_unreachable("Unexpected opcode for little endian VSX load");
14425   case ISD::LOAD: {
14426     LoadSDNode *LD = cast<LoadSDNode>(N);
14427     Chain = LD->getChain();
14428     Base = LD->getBasePtr();
14429     MMO = LD->getMemOperand();
14430     // If the MMO suggests this isn't a load of a full vector, leave
14431     // things alone.  For a built-in, we have to make the change for
14432     // correctness, so if there is a size problem that will be a bug.
14433     if (MMO->getSize() < 16)
14434       return SDValue();
14435     break;
14436   }
14437   case ISD::INTRINSIC_W_CHAIN: {
14438     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14439     Chain = Intrin->getChain();
14440     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14441     // us what we want. Get operand 2 instead.
14442     Base = Intrin->getOperand(2);
14443     MMO = Intrin->getMemOperand();
14444     break;
14445   }
14446   }
14447 
14448   MVT VecTy = N->getValueType(0).getSimpleVT();
14449 
14450   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14451   // aligned and the type is a vector with elements up to 4 bytes
14452   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14453       VecTy.getScalarSizeInBits() <= 32) {
14454     return SDValue();
14455   }
14456 
14457   SDValue LoadOps[] = { Chain, Base };
14458   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14459                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14460                                          LoadOps, MVT::v2f64, MMO);
14461 
14462   DCI.AddToWorklist(Load.getNode());
14463   Chain = Load.getValue(1);
14464   SDValue Swap = DAG.getNode(
14465       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14466   DCI.AddToWorklist(Swap.getNode());
14467 
14468   // Add a bitcast if the resulting load type doesn't match v2f64.
14469   if (VecTy != MVT::v2f64) {
14470     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14471     DCI.AddToWorklist(N.getNode());
14472     // Package {bitcast value, swap's chain} to match Load's shape.
14473     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14474                        N, Swap.getValue(1));
14475   }
14476 
14477   return Swap;
14478 }
14479 
14480 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14481 // builtins) into stores with swaps.
14482 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14483                                                DAGCombinerInfo &DCI) const {
14484   SelectionDAG &DAG = DCI.DAG;
14485   SDLoc dl(N);
14486   SDValue Chain;
14487   SDValue Base;
14488   unsigned SrcOpnd;
14489   MachineMemOperand *MMO;
14490 
14491   switch (N->getOpcode()) {
14492   default:
14493     llvm_unreachable("Unexpected opcode for little endian VSX store");
14494   case ISD::STORE: {
14495     StoreSDNode *ST = cast<StoreSDNode>(N);
14496     Chain = ST->getChain();
14497     Base = ST->getBasePtr();
14498     MMO = ST->getMemOperand();
14499     SrcOpnd = 1;
14500     // If the MMO suggests this isn't a store of a full vector, leave
14501     // things alone.  For a built-in, we have to make the change for
14502     // correctness, so if there is a size problem that will be a bug.
14503     if (MMO->getSize() < 16)
14504       return SDValue();
14505     break;
14506   }
14507   case ISD::INTRINSIC_VOID: {
14508     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14509     Chain = Intrin->getChain();
14510     // Intrin->getBasePtr() oddly does not get what we want.
14511     Base = Intrin->getOperand(3);
14512     MMO = Intrin->getMemOperand();
14513     SrcOpnd = 2;
14514     break;
14515   }
14516   }
14517 
14518   SDValue Src = N->getOperand(SrcOpnd);
14519   MVT VecTy = Src.getValueType().getSimpleVT();
14520 
14521   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14522   // aligned and the type is a vector with elements up to 4 bytes
14523   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14524       VecTy.getScalarSizeInBits() <= 32) {
14525     return SDValue();
14526   }
14527 
14528   // All stores are done as v2f64 and possible bit cast.
14529   if (VecTy != MVT::v2f64) {
14530     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14531     DCI.AddToWorklist(Src.getNode());
14532   }
14533 
14534   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14535                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14536   DCI.AddToWorklist(Swap.getNode());
14537   Chain = Swap.getValue(1);
14538   SDValue StoreOps[] = { Chain, Swap, Base };
14539   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14540                                           DAG.getVTList(MVT::Other),
14541                                           StoreOps, VecTy, MMO);
14542   DCI.AddToWorklist(Store.getNode());
14543   return Store;
14544 }
14545 
14546 // Handle DAG combine for STORE (FP_TO_INT F).
14547 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14548                                                DAGCombinerInfo &DCI) const {
14549 
14550   SelectionDAG &DAG = DCI.DAG;
14551   SDLoc dl(N);
14552   unsigned Opcode = N->getOperand(1).getOpcode();
14553 
14554   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14555          && "Not a FP_TO_INT Instruction!");
14556 
14557   SDValue Val = N->getOperand(1).getOperand(0);
14558   EVT Op1VT = N->getOperand(1).getValueType();
14559   EVT ResVT = Val.getValueType();
14560 
14561   if (!isTypeLegal(ResVT))
14562     return SDValue();
14563 
14564   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14565   bool ValidTypeForStoreFltAsInt =
14566         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14567          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14568 
14569   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14570     return SDValue();
14571 
14572   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14573       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14574     return SDValue();
14575 
14576   // Extend f32 values to f64
14577   if (ResVT.getScalarSizeInBits() == 32) {
14578     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14579     DCI.AddToWorklist(Val.getNode());
14580   }
14581 
14582   // Set signed or unsigned conversion opcode.
14583   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14584                           PPCISD::FP_TO_SINT_IN_VSR :
14585                           PPCISD::FP_TO_UINT_IN_VSR;
14586 
14587   Val = DAG.getNode(ConvOpcode,
14588                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14589   DCI.AddToWorklist(Val.getNode());
14590 
14591   // Set number of bytes being converted.
14592   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14593   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14594                     DAG.getIntPtrConstant(ByteSize, dl, false),
14595                     DAG.getValueType(Op1VT) };
14596 
14597   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14598           DAG.getVTList(MVT::Other), Ops,
14599           cast<StoreSDNode>(N)->getMemoryVT(),
14600           cast<StoreSDNode>(N)->getMemOperand());
14601 
14602   DCI.AddToWorklist(Val.getNode());
14603   return Val;
14604 }
14605 
14606 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14607   // Check that the source of the element keeps flipping
14608   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14609   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14610   for (int i = 1, e = Mask.size(); i < e; i++) {
14611     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14612       return false;
14613     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14614       return false;
14615     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14616   }
14617   return true;
14618 }
14619 
14620 static bool isSplatBV(SDValue Op) {
14621   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14622     return false;
14623   SDValue FirstOp;
14624 
14625   // Find first non-undef input.
14626   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14627     FirstOp = Op.getOperand(i);
14628     if (!FirstOp.isUndef())
14629       break;
14630   }
14631 
14632   // All inputs are undef or the same as the first non-undef input.
14633   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14634     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14635       return false;
14636   return true;
14637 }
14638 
14639 static SDValue isScalarToVec(SDValue Op) {
14640   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14641     return Op;
14642   if (Op.getOpcode() != ISD::BITCAST)
14643     return SDValue();
14644   Op = Op.getOperand(0);
14645   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14646     return Op;
14647   return SDValue();
14648 }
14649 
14650 // Fix up the shuffle mask to account for the fact that the result of
14651 // scalar_to_vector is not in lane zero. This just takes all values in
14652 // the ranges specified by the min/max indices and adds the number of
14653 // elements required to ensure each element comes from the respective
14654 // position in the valid lane.
14655 // On little endian, that's just the corresponding element in the other
14656 // half of the vector. On big endian, it is in the same half but right
14657 // justified rather than left justified in that half.
14658 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14659                                             int LHSMaxIdx, int RHSMinIdx,
14660                                             int RHSMaxIdx, int HalfVec,
14661                                             unsigned ValidLaneWidth,
14662                                             const PPCSubtarget &Subtarget) {
14663   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14664     int Idx = ShuffV[i];
14665     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14666       ShuffV[i] +=
14667           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14668   }
14669 }
14670 
14671 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14672 // the original is:
14673 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14674 // In such a case, just change the shuffle mask to extract the element
14675 // from the permuted index.
14676 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14677                                const PPCSubtarget &Subtarget) {
14678   SDLoc dl(OrigSToV);
14679   EVT VT = OrigSToV.getValueType();
14680   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14681          "Expecting a SCALAR_TO_VECTOR here");
14682   SDValue Input = OrigSToV.getOperand(0);
14683 
14684   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14685     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14686     SDValue OrigVector = Input.getOperand(0);
14687 
14688     // Can't handle non-const element indices or different vector types
14689     // for the input to the extract and the output of the scalar_to_vector.
14690     if (Idx && VT == OrigVector.getValueType()) {
14691       unsigned NumElts = VT.getVectorNumElements();
14692       assert(
14693           NumElts > 1 &&
14694           "Cannot produce a permuted scalar_to_vector for one element vector");
14695       SmallVector<int, 16> NewMask(NumElts, -1);
14696       unsigned ResultInElt = NumElts / 2;
14697       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14698       NewMask[ResultInElt] = Idx->getZExtValue();
14699       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14700     }
14701   }
14702   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14703                      OrigSToV.getOperand(0));
14704 }
14705 
14706 // On little endian subtargets, combine shuffles such as:
14707 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14708 // into:
14709 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14710 // because the latter can be matched to a single instruction merge.
14711 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14712 // to put the value into element zero. Adjust the shuffle mask so that the
14713 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14714 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14715 // nodes with elements smaller than doubleword because all the ways
14716 // of getting scalar data into a vector register put the value in the
14717 // rightmost element of the left half of the vector.
14718 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14719                                                 SelectionDAG &DAG) const {
14720   SDValue LHS = SVN->getOperand(0);
14721   SDValue RHS = SVN->getOperand(1);
14722   auto Mask = SVN->getMask();
14723   int NumElts = LHS.getValueType().getVectorNumElements();
14724   SDValue Res(SVN, 0);
14725   SDLoc dl(SVN);
14726   bool IsLittleEndian = Subtarget.isLittleEndian();
14727 
14728   // On big endian targets this is only useful for subtargets with direct moves.
14729   // On little endian targets it would be useful for all subtargets with VSX.
14730   // However adding special handling for LE subtargets without direct moves
14731   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14732   // which includes direct moves.
14733   if (!Subtarget.hasDirectMove())
14734     return Res;
14735 
14736   // If this is not a shuffle of a shuffle and the first element comes from
14737   // the second vector, canonicalize to the commuted form. This will make it
14738   // more likely to match one of the single instruction patterns.
14739   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14740       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14741     std::swap(LHS, RHS);
14742     Res = DAG.getCommutedVectorShuffle(*SVN);
14743     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14744   }
14745 
14746   // Adjust the shuffle mask if either input vector comes from a
14747   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14748   // form (to prevent the need for a swap).
14749   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14750   SDValue SToVLHS = isScalarToVec(LHS);
14751   SDValue SToVRHS = isScalarToVec(RHS);
14752   if (SToVLHS || SToVRHS) {
14753     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14754                             : SToVRHS.getValueType().getVectorNumElements();
14755     int NumEltsOut = ShuffV.size();
14756     // The width of the "valid lane" (i.e. the lane that contains the value that
14757     // is vectorized) needs to be expressed in terms of the number of elements
14758     // of the shuffle. It is thereby the ratio of the values before and after
14759     // any bitcast.
14760     unsigned ValidLaneWidth =
14761         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14762                       LHS.getValueType().getScalarSizeInBits()
14763                 : SToVRHS.getValueType().getScalarSizeInBits() /
14764                       RHS.getValueType().getScalarSizeInBits();
14765 
14766     // Initially assume that neither input is permuted. These will be adjusted
14767     // accordingly if either input is.
14768     int LHSMaxIdx = -1;
14769     int RHSMinIdx = -1;
14770     int RHSMaxIdx = -1;
14771     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14772 
14773     // Get the permuted scalar to vector nodes for the source(s) that come from
14774     // ISD::SCALAR_TO_VECTOR.
14775     // On big endian systems, this only makes sense for element sizes smaller
14776     // than 64 bits since for 64-bit elements, all instructions already put
14777     // the value into element zero. Since scalar size of LHS and RHS may differ
14778     // after isScalarToVec, this should be checked using their own sizes.
14779     if (SToVLHS) {
14780       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14781         return Res;
14782       // Set up the values for the shuffle vector fixup.
14783       LHSMaxIdx = NumEltsOut / NumEltsIn;
14784       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14785       if (SToVLHS.getValueType() != LHS.getValueType())
14786         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14787       LHS = SToVLHS;
14788     }
14789     if (SToVRHS) {
14790       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14791         return Res;
14792       RHSMinIdx = NumEltsOut;
14793       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14794       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14795       if (SToVRHS.getValueType() != RHS.getValueType())
14796         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14797       RHS = SToVRHS;
14798     }
14799 
14800     // Fix up the shuffle mask to reflect where the desired element actually is.
14801     // The minimum and maximum indices that correspond to element zero for both
14802     // the LHS and RHS are computed and will control which shuffle mask entries
14803     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14804     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14805     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14806                                     HalfVec, ValidLaneWidth, Subtarget);
14807     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14808 
14809     // We may have simplified away the shuffle. We won't be able to do anything
14810     // further with it here.
14811     if (!isa<ShuffleVectorSDNode>(Res))
14812       return Res;
14813     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14814   }
14815 
14816   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14817   // The common case after we commuted the shuffle is that the RHS is a splat
14818   // and we have elements coming in from the splat at indices that are not
14819   // conducive to using a merge.
14820   // Example:
14821   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14822   if (!isSplatBV(TheSplat))
14823     return Res;
14824 
14825   // We are looking for a mask such that all even elements are from
14826   // one vector and all odd elements from the other.
14827   if (!isAlternatingShuffMask(Mask, NumElts))
14828     return Res;
14829 
14830   // Adjust the mask so we are pulling in the same index from the splat
14831   // as the index from the interesting vector in consecutive elements.
14832   if (IsLittleEndian) {
14833     // Example (even elements from first vector):
14834     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14835     if (Mask[0] < NumElts)
14836       for (int i = 1, e = Mask.size(); i < e; i += 2)
14837         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14838     // Example (odd elements from first vector):
14839     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14840     else
14841       for (int i = 0, e = Mask.size(); i < e; i += 2)
14842         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14843   } else {
14844     // Example (even elements from first vector):
14845     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14846     if (Mask[0] < NumElts)
14847       for (int i = 0, e = Mask.size(); i < e; i += 2)
14848         ShuffV[i] = ShuffV[i + 1] - NumElts;
14849     // Example (odd elements from first vector):
14850     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14851     else
14852       for (int i = 1, e = Mask.size(); i < e; i += 2)
14853         ShuffV[i] = ShuffV[i - 1] - NumElts;
14854   }
14855 
14856   // If the RHS has undefs, we need to remove them since we may have created
14857   // a shuffle that adds those instead of the splat value.
14858   SDValue SplatVal =
14859       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14860   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14861 
14862   if (IsLittleEndian)
14863     RHS = TheSplat;
14864   else
14865     LHS = TheSplat;
14866   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14867 }
14868 
14869 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14870                                                 LSBaseSDNode *LSBase,
14871                                                 DAGCombinerInfo &DCI) const {
14872   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14873         "Not a reverse memop pattern!");
14874 
14875   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14876     auto Mask = SVN->getMask();
14877     int i = 0;
14878     auto I = Mask.rbegin();
14879     auto E = Mask.rend();
14880 
14881     for (; I != E; ++I) {
14882       if (*I != i)
14883         return false;
14884       i++;
14885     }
14886     return true;
14887   };
14888 
14889   SelectionDAG &DAG = DCI.DAG;
14890   EVT VT = SVN->getValueType(0);
14891 
14892   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14893     return SDValue();
14894 
14895   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14896   // See comment in PPCVSXSwapRemoval.cpp.
14897   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14898   if (!Subtarget.hasP9Vector())
14899     return SDValue();
14900 
14901   if(!IsElementReverse(SVN))
14902     return SDValue();
14903 
14904   if (LSBase->getOpcode() == ISD::LOAD) {
14905     // If the load return value 0 has more than one user except the
14906     // shufflevector instruction, it is not profitable to replace the
14907     // shufflevector with a reverse load.
14908     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
14909          UI != UE; ++UI)
14910       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
14911         return SDValue();
14912 
14913     SDLoc dl(LSBase);
14914     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14915     return DAG.getMemIntrinsicNode(
14916         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14917         LSBase->getMemoryVT(), LSBase->getMemOperand());
14918   }
14919 
14920   if (LSBase->getOpcode() == ISD::STORE) {
14921     // If there are other uses of the shuffle, the swap cannot be avoided.
14922     // Forcing the use of an X-Form (since swapped stores only have
14923     // X-Forms) without removing the swap is unprofitable.
14924     if (!SVN->hasOneUse())
14925       return SDValue();
14926 
14927     SDLoc dl(LSBase);
14928     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14929                           LSBase->getBasePtr()};
14930     return DAG.getMemIntrinsicNode(
14931         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14932         LSBase->getMemoryVT(), LSBase->getMemOperand());
14933   }
14934 
14935   llvm_unreachable("Expected a load or store node here");
14936 }
14937 
14938 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14939                                              DAGCombinerInfo &DCI) const {
14940   SelectionDAG &DAG = DCI.DAG;
14941   SDLoc dl(N);
14942   switch (N->getOpcode()) {
14943   default: break;
14944   case ISD::ADD:
14945     return combineADD(N, DCI);
14946   case ISD::SHL:
14947     return combineSHL(N, DCI);
14948   case ISD::SRA:
14949     return combineSRA(N, DCI);
14950   case ISD::SRL:
14951     return combineSRL(N, DCI);
14952   case ISD::MUL:
14953     return combineMUL(N, DCI);
14954   case ISD::FMA:
14955   case PPCISD::FNMSUB:
14956     return combineFMALike(N, DCI);
14957   case PPCISD::SHL:
14958     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14959         return N->getOperand(0);
14960     break;
14961   case PPCISD::SRL:
14962     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14963         return N->getOperand(0);
14964     break;
14965   case PPCISD::SRA:
14966     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14967       if (C->isZero() ||  //  0 >>s V -> 0.
14968           C->isAllOnes()) // -1 >>s V -> -1.
14969         return N->getOperand(0);
14970     }
14971     break;
14972   case ISD::SIGN_EXTEND:
14973   case ISD::ZERO_EXTEND:
14974   case ISD::ANY_EXTEND:
14975     return DAGCombineExtBoolTrunc(N, DCI);
14976   case ISD::TRUNCATE:
14977     return combineTRUNCATE(N, DCI);
14978   case ISD::SETCC:
14979     if (SDValue CSCC = combineSetCC(N, DCI))
14980       return CSCC;
14981     LLVM_FALLTHROUGH;
14982   case ISD::SELECT_CC:
14983     return DAGCombineTruncBoolExt(N, DCI);
14984   case ISD::SINT_TO_FP:
14985   case ISD::UINT_TO_FP:
14986     return combineFPToIntToFP(N, DCI);
14987   case ISD::VECTOR_SHUFFLE:
14988     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14989       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14990       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14991     }
14992     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14993   case ISD::STORE: {
14994 
14995     EVT Op1VT = N->getOperand(1).getValueType();
14996     unsigned Opcode = N->getOperand(1).getOpcode();
14997 
14998     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14999       SDValue Val= combineStoreFPToInt(N, DCI);
15000       if (Val)
15001         return Val;
15002     }
15003 
15004     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15005       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15006       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15007       if (Val)
15008         return Val;
15009     }
15010 
15011     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15012     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15013         N->getOperand(1).getNode()->hasOneUse() &&
15014         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15015          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15016 
15017       // STBRX can only handle simple types and it makes no sense to store less
15018       // two bytes in byte-reversed order.
15019       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15020       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15021         break;
15022 
15023       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15024       // Do an any-extend to 32-bits if this is a half-word input.
15025       if (BSwapOp.getValueType() == MVT::i16)
15026         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15027 
15028       // If the type of BSWAP operand is wider than stored memory width
15029       // it need to be shifted to the right side before STBRX.
15030       if (Op1VT.bitsGT(mVT)) {
15031         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15032         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15033                               DAG.getConstant(Shift, dl, MVT::i32));
15034         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15035         if (Op1VT == MVT::i64)
15036           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15037       }
15038 
15039       SDValue Ops[] = {
15040         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15041       };
15042       return
15043         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15044                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15045                                 cast<StoreSDNode>(N)->getMemOperand());
15046     }
15047 
15048     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15049     // So it can increase the chance of CSE constant construction.
15050     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15051         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15052       // Need to sign-extended to 64-bits to handle negative values.
15053       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15054       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15055                                     MemVT.getSizeInBits());
15056       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15057 
15058       // DAG.getTruncStore() can't be used here because it doesn't accept
15059       // the general (base + offset) addressing mode.
15060       // So we use UpdateNodeOperands and setTruncatingStore instead.
15061       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15062                              N->getOperand(3));
15063       cast<StoreSDNode>(N)->setTruncatingStore(true);
15064       return SDValue(N, 0);
15065     }
15066 
15067     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15068     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15069     if (Op1VT.isSimple()) {
15070       MVT StoreVT = Op1VT.getSimpleVT();
15071       if (Subtarget.needsSwapsForVSXMemOps() &&
15072           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15073            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15074         return expandVSXStoreForLE(N, DCI);
15075     }
15076     break;
15077   }
15078   case ISD::LOAD: {
15079     LoadSDNode *LD = cast<LoadSDNode>(N);
15080     EVT VT = LD->getValueType(0);
15081 
15082     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15083     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15084     if (VT.isSimple()) {
15085       MVT LoadVT = VT.getSimpleVT();
15086       if (Subtarget.needsSwapsForVSXMemOps() &&
15087           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15088            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15089         return expandVSXLoadForLE(N, DCI);
15090     }
15091 
15092     // We sometimes end up with a 64-bit integer load, from which we extract
15093     // two single-precision floating-point numbers. This happens with
15094     // std::complex<float>, and other similar structures, because of the way we
15095     // canonicalize structure copies. However, if we lack direct moves,
15096     // then the final bitcasts from the extracted integer values to the
15097     // floating-point numbers turn into store/load pairs. Even with direct moves,
15098     // just loading the two floating-point numbers is likely better.
15099     auto ReplaceTwoFloatLoad = [&]() {
15100       if (VT != MVT::i64)
15101         return false;
15102 
15103       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15104           LD->isVolatile())
15105         return false;
15106 
15107       //  We're looking for a sequence like this:
15108       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15109       //      t16: i64 = srl t13, Constant:i32<32>
15110       //    t17: i32 = truncate t16
15111       //  t18: f32 = bitcast t17
15112       //    t19: i32 = truncate t13
15113       //  t20: f32 = bitcast t19
15114 
15115       if (!LD->hasNUsesOfValue(2, 0))
15116         return false;
15117 
15118       auto UI = LD->use_begin();
15119       while (UI.getUse().getResNo() != 0) ++UI;
15120       SDNode *Trunc = *UI++;
15121       while (UI.getUse().getResNo() != 0) ++UI;
15122       SDNode *RightShift = *UI;
15123       if (Trunc->getOpcode() != ISD::TRUNCATE)
15124         std::swap(Trunc, RightShift);
15125 
15126       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15127           Trunc->getValueType(0) != MVT::i32 ||
15128           !Trunc->hasOneUse())
15129         return false;
15130       if (RightShift->getOpcode() != ISD::SRL ||
15131           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15132           RightShift->getConstantOperandVal(1) != 32 ||
15133           !RightShift->hasOneUse())
15134         return false;
15135 
15136       SDNode *Trunc2 = *RightShift->use_begin();
15137       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15138           Trunc2->getValueType(0) != MVT::i32 ||
15139           !Trunc2->hasOneUse())
15140         return false;
15141 
15142       SDNode *Bitcast = *Trunc->use_begin();
15143       SDNode *Bitcast2 = *Trunc2->use_begin();
15144 
15145       if (Bitcast->getOpcode() != ISD::BITCAST ||
15146           Bitcast->getValueType(0) != MVT::f32)
15147         return false;
15148       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15149           Bitcast2->getValueType(0) != MVT::f32)
15150         return false;
15151 
15152       if (Subtarget.isLittleEndian())
15153         std::swap(Bitcast, Bitcast2);
15154 
15155       // Bitcast has the second float (in memory-layout order) and Bitcast2
15156       // has the first one.
15157 
15158       SDValue BasePtr = LD->getBasePtr();
15159       if (LD->isIndexed()) {
15160         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15161                "Non-pre-inc AM on PPC?");
15162         BasePtr =
15163           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15164                       LD->getOffset());
15165       }
15166 
15167       auto MMOFlags =
15168           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15169       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15170                                       LD->getPointerInfo(), LD->getAlignment(),
15171                                       MMOFlags, LD->getAAInfo());
15172       SDValue AddPtr =
15173         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15174                     BasePtr, DAG.getIntPtrConstant(4, dl));
15175       SDValue FloatLoad2 = DAG.getLoad(
15176           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15177           LD->getPointerInfo().getWithOffset(4),
15178           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15179 
15180       if (LD->isIndexed()) {
15181         // Note that DAGCombine should re-form any pre-increment load(s) from
15182         // what is produced here if that makes sense.
15183         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15184       }
15185 
15186       DCI.CombineTo(Bitcast2, FloatLoad);
15187       DCI.CombineTo(Bitcast, FloatLoad2);
15188 
15189       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15190                                     SDValue(FloatLoad2.getNode(), 1));
15191       return true;
15192     };
15193 
15194     if (ReplaceTwoFloatLoad())
15195       return SDValue(N, 0);
15196 
15197     EVT MemVT = LD->getMemoryVT();
15198     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15199     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15200     if (LD->isUnindexed() && VT.isVector() &&
15201         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15202           // P8 and later hardware should just use LOAD.
15203           !Subtarget.hasP8Vector() &&
15204           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15205            VT == MVT::v4f32))) &&
15206         LD->getAlign() < ABIAlignment) {
15207       // This is a type-legal unaligned Altivec load.
15208       SDValue Chain = LD->getChain();
15209       SDValue Ptr = LD->getBasePtr();
15210       bool isLittleEndian = Subtarget.isLittleEndian();
15211 
15212       // This implements the loading of unaligned vectors as described in
15213       // the venerable Apple Velocity Engine overview. Specifically:
15214       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15215       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15216       //
15217       // The general idea is to expand a sequence of one or more unaligned
15218       // loads into an alignment-based permutation-control instruction (lvsl
15219       // or lvsr), a series of regular vector loads (which always truncate
15220       // their input address to an aligned address), and a series of
15221       // permutations.  The results of these permutations are the requested
15222       // loaded values.  The trick is that the last "extra" load is not taken
15223       // from the address you might suspect (sizeof(vector) bytes after the
15224       // last requested load), but rather sizeof(vector) - 1 bytes after the
15225       // last requested vector. The point of this is to avoid a page fault if
15226       // the base address happened to be aligned. This works because if the
15227       // base address is aligned, then adding less than a full vector length
15228       // will cause the last vector in the sequence to be (re)loaded.
15229       // Otherwise, the next vector will be fetched as you might suspect was
15230       // necessary.
15231 
15232       // We might be able to reuse the permutation generation from
15233       // a different base address offset from this one by an aligned amount.
15234       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15235       // optimization later.
15236       Intrinsic::ID Intr, IntrLD, IntrPerm;
15237       MVT PermCntlTy, PermTy, LDTy;
15238       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15239                             : Intrinsic::ppc_altivec_lvsl;
15240       IntrLD = Intrinsic::ppc_altivec_lvx;
15241       IntrPerm = Intrinsic::ppc_altivec_vperm;
15242       PermCntlTy = MVT::v16i8;
15243       PermTy = MVT::v4i32;
15244       LDTy = MVT::v4i32;
15245 
15246       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15247 
15248       // Create the new MMO for the new base load. It is like the original MMO,
15249       // but represents an area in memory almost twice the vector size centered
15250       // on the original address. If the address is unaligned, we might start
15251       // reading up to (sizeof(vector)-1) bytes below the address of the
15252       // original unaligned load.
15253       MachineFunction &MF = DAG.getMachineFunction();
15254       MachineMemOperand *BaseMMO =
15255         MF.getMachineMemOperand(LD->getMemOperand(),
15256                                 -(long)MemVT.getStoreSize()+1,
15257                                 2*MemVT.getStoreSize()-1);
15258 
15259       // Create the new base load.
15260       SDValue LDXIntID =
15261           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15262       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15263       SDValue BaseLoad =
15264         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15265                                 DAG.getVTList(PermTy, MVT::Other),
15266                                 BaseLoadOps, LDTy, BaseMMO);
15267 
15268       // Note that the value of IncOffset (which is provided to the next
15269       // load's pointer info offset value, and thus used to calculate the
15270       // alignment), and the value of IncValue (which is actually used to
15271       // increment the pointer value) are different! This is because we
15272       // require the next load to appear to be aligned, even though it
15273       // is actually offset from the base pointer by a lesser amount.
15274       int IncOffset = VT.getSizeInBits() / 8;
15275       int IncValue = IncOffset;
15276 
15277       // Walk (both up and down) the chain looking for another load at the real
15278       // (aligned) offset (the alignment of the other load does not matter in
15279       // this case). If found, then do not use the offset reduction trick, as
15280       // that will prevent the loads from being later combined (as they would
15281       // otherwise be duplicates).
15282       if (!findConsecutiveLoad(LD, DAG))
15283         --IncValue;
15284 
15285       SDValue Increment =
15286           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15287       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15288 
15289       MachineMemOperand *ExtraMMO =
15290         MF.getMachineMemOperand(LD->getMemOperand(),
15291                                 1, 2*MemVT.getStoreSize()-1);
15292       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15293       SDValue ExtraLoad =
15294         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15295                                 DAG.getVTList(PermTy, MVT::Other),
15296                                 ExtraLoadOps, LDTy, ExtraMMO);
15297 
15298       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15299         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15300 
15301       // Because vperm has a big-endian bias, we must reverse the order
15302       // of the input vectors and complement the permute control vector
15303       // when generating little endian code.  We have already handled the
15304       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15305       // and ExtraLoad here.
15306       SDValue Perm;
15307       if (isLittleEndian)
15308         Perm = BuildIntrinsicOp(IntrPerm,
15309                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15310       else
15311         Perm = BuildIntrinsicOp(IntrPerm,
15312                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15313 
15314       if (VT != PermTy)
15315         Perm = Subtarget.hasAltivec()
15316                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15317                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15318                                  DAG.getTargetConstant(1, dl, MVT::i64));
15319                                // second argument is 1 because this rounding
15320                                // is always exact.
15321 
15322       // The output of the permutation is our loaded result, the TokenFactor is
15323       // our new chain.
15324       DCI.CombineTo(N, Perm, TF);
15325       return SDValue(N, 0);
15326     }
15327     }
15328     break;
15329     case ISD::INTRINSIC_WO_CHAIN: {
15330       bool isLittleEndian = Subtarget.isLittleEndian();
15331       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15332       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15333                                            : Intrinsic::ppc_altivec_lvsl);
15334       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15335         SDValue Add = N->getOperand(1);
15336 
15337         int Bits = 4 /* 16 byte alignment */;
15338 
15339         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15340                                   APInt::getAllOnes(Bits /* alignment */)
15341                                       .zext(Add.getScalarValueSizeInBits()))) {
15342           SDNode *BasePtr = Add->getOperand(0).getNode();
15343           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15344                                     UE = BasePtr->use_end();
15345                UI != UE; ++UI) {
15346             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15347                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15348                     IID) {
15349               // We've found another LVSL/LVSR, and this address is an aligned
15350               // multiple of that one. The results will be the same, so use the
15351               // one we've just found instead.
15352 
15353               return SDValue(*UI, 0);
15354             }
15355           }
15356         }
15357 
15358         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15359           SDNode *BasePtr = Add->getOperand(0).getNode();
15360           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15361                UE = BasePtr->use_end(); UI != UE; ++UI) {
15362             if (UI->getOpcode() == ISD::ADD &&
15363                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15364                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15365                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15366                 (1ULL << Bits) == 0) {
15367               SDNode *OtherAdd = *UI;
15368               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15369                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15370                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15371                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15372                   return SDValue(*VI, 0);
15373                 }
15374               }
15375             }
15376           }
15377         }
15378       }
15379 
15380       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15381       // Expose the vabsduw/h/b opportunity for down stream
15382       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15383           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15384            IID == Intrinsic::ppc_altivec_vmaxsh ||
15385            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15386         SDValue V1 = N->getOperand(1);
15387         SDValue V2 = N->getOperand(2);
15388         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15389              V1.getSimpleValueType() == MVT::v8i16 ||
15390              V1.getSimpleValueType() == MVT::v16i8) &&
15391             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15392           // (0-a, a)
15393           if (V1.getOpcode() == ISD::SUB &&
15394               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15395               V1.getOperand(1) == V2) {
15396             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15397           }
15398           // (a, 0-a)
15399           if (V2.getOpcode() == ISD::SUB &&
15400               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15401               V2.getOperand(1) == V1) {
15402             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15403           }
15404           // (x-y, y-x)
15405           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15406               V1.getOperand(0) == V2.getOperand(1) &&
15407               V1.getOperand(1) == V2.getOperand(0)) {
15408             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15409           }
15410         }
15411       }
15412     }
15413 
15414     break;
15415   case ISD::INTRINSIC_W_CHAIN:
15416     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15417     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15418     if (Subtarget.needsSwapsForVSXMemOps()) {
15419       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15420       default:
15421         break;
15422       case Intrinsic::ppc_vsx_lxvw4x:
15423       case Intrinsic::ppc_vsx_lxvd2x:
15424         return expandVSXLoadForLE(N, DCI);
15425       }
15426     }
15427     break;
15428   case ISD::INTRINSIC_VOID:
15429     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15430     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15431     if (Subtarget.needsSwapsForVSXMemOps()) {
15432       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15433       default:
15434         break;
15435       case Intrinsic::ppc_vsx_stxvw4x:
15436       case Intrinsic::ppc_vsx_stxvd2x:
15437         return expandVSXStoreForLE(N, DCI);
15438       }
15439     }
15440     break;
15441   case ISD::BSWAP: {
15442     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15443     // For subtargets without LDBRX, we can still do better than the default
15444     // expansion even for 64-bit BSWAP (LOAD).
15445     bool Is64BitBswapOn64BitTgt =
15446         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15447     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15448                                N->getOperand(0).hasOneUse();
15449     if (IsSingleUseNormalLd &&
15450         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15451          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15452       SDValue Load = N->getOperand(0);
15453       LoadSDNode *LD = cast<LoadSDNode>(Load);
15454       // Create the byte-swapping load.
15455       SDValue Ops[] = {
15456         LD->getChain(),    // Chain
15457         LD->getBasePtr(),  // Ptr
15458         DAG.getValueType(N->getValueType(0)) // VT
15459       };
15460       SDValue BSLoad =
15461         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15462                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15463                                               MVT::i64 : MVT::i32, MVT::Other),
15464                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15465 
15466       // If this is an i16 load, insert the truncate.
15467       SDValue ResVal = BSLoad;
15468       if (N->getValueType(0) == MVT::i16)
15469         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15470 
15471       // First, combine the bswap away.  This makes the value produced by the
15472       // load dead.
15473       DCI.CombineTo(N, ResVal);
15474 
15475       // Next, combine the load away, we give it a bogus result value but a real
15476       // chain result.  The result value is dead because the bswap is dead.
15477       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15478 
15479       // Return N so it doesn't get rechecked!
15480       return SDValue(N, 0);
15481     }
15482     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15483     // before legalization so that the BUILD_PAIR is handled correctly.
15484     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15485         !IsSingleUseNormalLd)
15486       return SDValue();
15487     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15488 
15489     // Can't split volatile or atomic loads.
15490     if (!LD->isSimple())
15491       return SDValue();
15492     SDValue BasePtr = LD->getBasePtr();
15493     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15494                              LD->getPointerInfo(), LD->getAlignment());
15495     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15496     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15497                           DAG.getIntPtrConstant(4, dl));
15498     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15499         LD->getMemOperand(), 4, 4);
15500     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15501     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15502     SDValue Res;
15503     if (Subtarget.isLittleEndian())
15504       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15505     else
15506       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15507     SDValue TF =
15508         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15509                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15510     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15511     return Res;
15512   }
15513   case PPCISD::VCMP:
15514     // If a VCMP_rec node already exists with exactly the same operands as this
15515     // node, use its result instead of this node (VCMP_rec computes both a CR6
15516     // and a normal output).
15517     //
15518     if (!N->getOperand(0).hasOneUse() &&
15519         !N->getOperand(1).hasOneUse() &&
15520         !N->getOperand(2).hasOneUse()) {
15521 
15522       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15523       SDNode *VCMPrecNode = nullptr;
15524 
15525       SDNode *LHSN = N->getOperand(0).getNode();
15526       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15527            UI != E; ++UI)
15528         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15529             UI->getOperand(1) == N->getOperand(1) &&
15530             UI->getOperand(2) == N->getOperand(2) &&
15531             UI->getOperand(0) == N->getOperand(0)) {
15532           VCMPrecNode = *UI;
15533           break;
15534         }
15535 
15536       // If there is no VCMP_rec node, or if the flag value has a single use,
15537       // don't transform this.
15538       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15539         break;
15540 
15541       // Look at the (necessarily single) use of the flag value.  If it has a
15542       // chain, this transformation is more complex.  Note that multiple things
15543       // could use the value result, which we should ignore.
15544       SDNode *FlagUser = nullptr;
15545       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15546            FlagUser == nullptr; ++UI) {
15547         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15548         SDNode *User = *UI;
15549         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15550           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15551             FlagUser = User;
15552             break;
15553           }
15554         }
15555       }
15556 
15557       // If the user is a MFOCRF instruction, we know this is safe.
15558       // Otherwise we give up for right now.
15559       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15560         return SDValue(VCMPrecNode, 0);
15561     }
15562     break;
15563   case ISD::BRCOND: {
15564     SDValue Cond = N->getOperand(1);
15565     SDValue Target = N->getOperand(2);
15566 
15567     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15568         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15569           Intrinsic::loop_decrement) {
15570 
15571       // We now need to make the intrinsic dead (it cannot be instruction
15572       // selected).
15573       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15574       assert(Cond.getNode()->hasOneUse() &&
15575              "Counter decrement has more than one use");
15576 
15577       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15578                          N->getOperand(0), Target);
15579     }
15580   }
15581   break;
15582   case ISD::BR_CC: {
15583     // If this is a branch on an altivec predicate comparison, lower this so
15584     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15585     // lowering is done pre-legalize, because the legalizer lowers the predicate
15586     // compare down to code that is difficult to reassemble.
15587     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15588     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15589 
15590     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15591     // value. If so, pass-through the AND to get to the intrinsic.
15592     if (LHS.getOpcode() == ISD::AND &&
15593         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15594         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15595           Intrinsic::loop_decrement &&
15596         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15597         !isNullConstant(LHS.getOperand(1)))
15598       LHS = LHS.getOperand(0);
15599 
15600     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15601         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15602           Intrinsic::loop_decrement &&
15603         isa<ConstantSDNode>(RHS)) {
15604       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15605              "Counter decrement comparison is not EQ or NE");
15606 
15607       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15608       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15609                     (CC == ISD::SETNE && !Val);
15610 
15611       // We now need to make the intrinsic dead (it cannot be instruction
15612       // selected).
15613       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15614       assert(LHS.getNode()->hasOneUse() &&
15615              "Counter decrement has more than one use");
15616 
15617       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15618                          N->getOperand(0), N->getOperand(4));
15619     }
15620 
15621     int CompareOpc;
15622     bool isDot;
15623 
15624     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15625         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15626         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15627       assert(isDot && "Can't compare against a vector result!");
15628 
15629       // If this is a comparison against something other than 0/1, then we know
15630       // that the condition is never/always true.
15631       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15632       if (Val != 0 && Val != 1) {
15633         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15634           return N->getOperand(0);
15635         // Always !=, turn it into an unconditional branch.
15636         return DAG.getNode(ISD::BR, dl, MVT::Other,
15637                            N->getOperand(0), N->getOperand(4));
15638       }
15639 
15640       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15641 
15642       // Create the PPCISD altivec 'dot' comparison node.
15643       SDValue Ops[] = {
15644         LHS.getOperand(2),  // LHS of compare
15645         LHS.getOperand(3),  // RHS of compare
15646         DAG.getConstant(CompareOpc, dl, MVT::i32)
15647       };
15648       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15649       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15650 
15651       // Unpack the result based on how the target uses it.
15652       PPC::Predicate CompOpc;
15653       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15654       default:  // Can't happen, don't crash on invalid number though.
15655       case 0:   // Branch on the value of the EQ bit of CR6.
15656         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15657         break;
15658       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15659         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15660         break;
15661       case 2:   // Branch on the value of the LT bit of CR6.
15662         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15663         break;
15664       case 3:   // Branch on the inverted value of the LT bit of CR6.
15665         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15666         break;
15667       }
15668 
15669       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15670                          DAG.getConstant(CompOpc, dl, MVT::i32),
15671                          DAG.getRegister(PPC::CR6, MVT::i32),
15672                          N->getOperand(4), CompNode.getValue(1));
15673     }
15674     break;
15675   }
15676   case ISD::BUILD_VECTOR:
15677     return DAGCombineBuildVector(N, DCI);
15678   case ISD::ABS:
15679     return combineABS(N, DCI);
15680   case ISD::VSELECT:
15681     return combineVSelect(N, DCI);
15682   }
15683 
15684   return SDValue();
15685 }
15686 
15687 SDValue
15688 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15689                                  SelectionDAG &DAG,
15690                                  SmallVectorImpl<SDNode *> &Created) const {
15691   // fold (sdiv X, pow2)
15692   EVT VT = N->getValueType(0);
15693   if (VT == MVT::i64 && !Subtarget.isPPC64())
15694     return SDValue();
15695   if ((VT != MVT::i32 && VT != MVT::i64) ||
15696       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15697     return SDValue();
15698 
15699   SDLoc DL(N);
15700   SDValue N0 = N->getOperand(0);
15701 
15702   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15703   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15704   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15705 
15706   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15707   Created.push_back(Op.getNode());
15708 
15709   if (IsNegPow2) {
15710     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15711     Created.push_back(Op.getNode());
15712   }
15713 
15714   return Op;
15715 }
15716 
15717 //===----------------------------------------------------------------------===//
15718 // Inline Assembly Support
15719 //===----------------------------------------------------------------------===//
15720 
15721 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15722                                                       KnownBits &Known,
15723                                                       const APInt &DemandedElts,
15724                                                       const SelectionDAG &DAG,
15725                                                       unsigned Depth) const {
15726   Known.resetAll();
15727   switch (Op.getOpcode()) {
15728   default: break;
15729   case PPCISD::LBRX: {
15730     // lhbrx is known to have the top bits cleared out.
15731     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15732       Known.Zero = 0xFFFF0000;
15733     break;
15734   }
15735   case ISD::INTRINSIC_WO_CHAIN: {
15736     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15737     default: break;
15738     case Intrinsic::ppc_altivec_vcmpbfp_p:
15739     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15740     case Intrinsic::ppc_altivec_vcmpequb_p:
15741     case Intrinsic::ppc_altivec_vcmpequh_p:
15742     case Intrinsic::ppc_altivec_vcmpequw_p:
15743     case Intrinsic::ppc_altivec_vcmpequd_p:
15744     case Intrinsic::ppc_altivec_vcmpequq_p:
15745     case Intrinsic::ppc_altivec_vcmpgefp_p:
15746     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15747     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15748     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15749     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15750     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15751     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15752     case Intrinsic::ppc_altivec_vcmpgtub_p:
15753     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15754     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15755     case Intrinsic::ppc_altivec_vcmpgtud_p:
15756     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15757       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15758       break;
15759     }
15760     break;
15761   }
15762   case ISD::INTRINSIC_W_CHAIN: {
15763     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15764     default:
15765       break;
15766     case Intrinsic::ppc_load2r:
15767       // Top bits are cleared for load2r (which is the same as lhbrx).
15768       Known.Zero = 0xFFFF0000;
15769       break;
15770     }
15771     break;
15772   }
15773   }
15774 }
15775 
15776 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15777   switch (Subtarget.getCPUDirective()) {
15778   default: break;
15779   case PPC::DIR_970:
15780   case PPC::DIR_PWR4:
15781   case PPC::DIR_PWR5:
15782   case PPC::DIR_PWR5X:
15783   case PPC::DIR_PWR6:
15784   case PPC::DIR_PWR6X:
15785   case PPC::DIR_PWR7:
15786   case PPC::DIR_PWR8:
15787   case PPC::DIR_PWR9:
15788   case PPC::DIR_PWR10:
15789   case PPC::DIR_PWR_FUTURE: {
15790     if (!ML)
15791       break;
15792 
15793     if (!DisableInnermostLoopAlign32) {
15794       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15795       // so that we can decrease cache misses and branch-prediction misses.
15796       // Actual alignment of the loop will depend on the hotness check and other
15797       // logic in alignBlocks.
15798       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15799         return Align(32);
15800     }
15801 
15802     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15803 
15804     // For small loops (between 5 and 8 instructions), align to a 32-byte
15805     // boundary so that the entire loop fits in one instruction-cache line.
15806     uint64_t LoopSize = 0;
15807     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15808       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15809         LoopSize += TII->getInstSizeInBytes(*J);
15810         if (LoopSize > 32)
15811           break;
15812       }
15813 
15814     if (LoopSize > 16 && LoopSize <= 32)
15815       return Align(32);
15816 
15817     break;
15818   }
15819   }
15820 
15821   return TargetLowering::getPrefLoopAlignment(ML);
15822 }
15823 
15824 /// getConstraintType - Given a constraint, return the type of
15825 /// constraint it is for this target.
15826 PPCTargetLowering::ConstraintType
15827 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15828   if (Constraint.size() == 1) {
15829     switch (Constraint[0]) {
15830     default: break;
15831     case 'b':
15832     case 'r':
15833     case 'f':
15834     case 'd':
15835     case 'v':
15836     case 'y':
15837       return C_RegisterClass;
15838     case 'Z':
15839       // FIXME: While Z does indicate a memory constraint, it specifically
15840       // indicates an r+r address (used in conjunction with the 'y' modifier
15841       // in the replacement string). Currently, we're forcing the base
15842       // register to be r0 in the asm printer (which is interpreted as zero)
15843       // and forming the complete address in the second register. This is
15844       // suboptimal.
15845       return C_Memory;
15846     }
15847   } else if (Constraint == "wc") { // individual CR bits.
15848     return C_RegisterClass;
15849   } else if (Constraint == "wa" || Constraint == "wd" ||
15850              Constraint == "wf" || Constraint == "ws" ||
15851              Constraint == "wi" || Constraint == "ww") {
15852     return C_RegisterClass; // VSX registers.
15853   }
15854   return TargetLowering::getConstraintType(Constraint);
15855 }
15856 
15857 /// Examine constraint type and operand type and determine a weight value.
15858 /// This object must already have been set up with the operand type
15859 /// and the current alternative constraint selected.
15860 TargetLowering::ConstraintWeight
15861 PPCTargetLowering::getSingleConstraintMatchWeight(
15862     AsmOperandInfo &info, const char *constraint) const {
15863   ConstraintWeight weight = CW_Invalid;
15864   Value *CallOperandVal = info.CallOperandVal;
15865     // If we don't have a value, we can't do a match,
15866     // but allow it at the lowest weight.
15867   if (!CallOperandVal)
15868     return CW_Default;
15869   Type *type = CallOperandVal->getType();
15870 
15871   // Look at the constraint type.
15872   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15873     return CW_Register; // an individual CR bit.
15874   else if ((StringRef(constraint) == "wa" ||
15875             StringRef(constraint) == "wd" ||
15876             StringRef(constraint) == "wf") &&
15877            type->isVectorTy())
15878     return CW_Register;
15879   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15880     return CW_Register; // just hold 64-bit integers data.
15881   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15882     return CW_Register;
15883   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15884     return CW_Register;
15885 
15886   switch (*constraint) {
15887   default:
15888     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15889     break;
15890   case 'b':
15891     if (type->isIntegerTy())
15892       weight = CW_Register;
15893     break;
15894   case 'f':
15895     if (type->isFloatTy())
15896       weight = CW_Register;
15897     break;
15898   case 'd':
15899     if (type->isDoubleTy())
15900       weight = CW_Register;
15901     break;
15902   case 'v':
15903     if (type->isVectorTy())
15904       weight = CW_Register;
15905     break;
15906   case 'y':
15907     weight = CW_Register;
15908     break;
15909   case 'Z':
15910     weight = CW_Memory;
15911     break;
15912   }
15913   return weight;
15914 }
15915 
15916 std::pair<unsigned, const TargetRegisterClass *>
15917 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15918                                                 StringRef Constraint,
15919                                                 MVT VT) const {
15920   if (Constraint.size() == 1) {
15921     // GCC RS6000 Constraint Letters
15922     switch (Constraint[0]) {
15923     case 'b':   // R1-R31
15924       if (VT == MVT::i64 && Subtarget.isPPC64())
15925         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15926       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15927     case 'r':   // R0-R31
15928       if (VT == MVT::i64 && Subtarget.isPPC64())
15929         return std::make_pair(0U, &PPC::G8RCRegClass);
15930       return std::make_pair(0U, &PPC::GPRCRegClass);
15931     // 'd' and 'f' constraints are both defined to be "the floating point
15932     // registers", where one is for 32-bit and the other for 64-bit. We don't
15933     // really care overly much here so just give them all the same reg classes.
15934     case 'd':
15935     case 'f':
15936       if (Subtarget.hasSPE()) {
15937         if (VT == MVT::f32 || VT == MVT::i32)
15938           return std::make_pair(0U, &PPC::GPRCRegClass);
15939         if (VT == MVT::f64 || VT == MVT::i64)
15940           return std::make_pair(0U, &PPC::SPERCRegClass);
15941       } else {
15942         if (VT == MVT::f32 || VT == MVT::i32)
15943           return std::make_pair(0U, &PPC::F4RCRegClass);
15944         if (VT == MVT::f64 || VT == MVT::i64)
15945           return std::make_pair(0U, &PPC::F8RCRegClass);
15946       }
15947       break;
15948     case 'v':
15949       if (Subtarget.hasAltivec())
15950         return std::make_pair(0U, &PPC::VRRCRegClass);
15951       break;
15952     case 'y':   // crrc
15953       return std::make_pair(0U, &PPC::CRRCRegClass);
15954     }
15955   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15956     // An individual CR bit.
15957     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15958   } else if ((Constraint == "wa" || Constraint == "wd" ||
15959              Constraint == "wf" || Constraint == "wi") &&
15960              Subtarget.hasVSX()) {
15961     // A VSX register for either a scalar (FP) or vector. There is no
15962     // support for single precision scalars on subtargets prior to Power8.
15963     if (VT.isVector())
15964       return std::make_pair(0U, &PPC::VSRCRegClass);
15965     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15966       return std::make_pair(0U, &PPC::VSSRCRegClass);
15967     return std::make_pair(0U, &PPC::VSFRCRegClass);
15968   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15969     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15970       return std::make_pair(0U, &PPC::VSSRCRegClass);
15971     else
15972       return std::make_pair(0U, &PPC::VSFRCRegClass);
15973   } else if (Constraint == "lr") {
15974     if (VT == MVT::i64)
15975       return std::make_pair(0U, &PPC::LR8RCRegClass);
15976     else
15977       return std::make_pair(0U, &PPC::LRRCRegClass);
15978   }
15979 
15980   // Handle special cases of physical registers that are not properly handled
15981   // by the base class.
15982   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
15983     // If we name a VSX register, we can't defer to the base class because it
15984     // will not recognize the correct register (their names will be VSL{0-31}
15985     // and V{0-31} so they won't match). So we match them here.
15986     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15987       int VSNum = atoi(Constraint.data() + 3);
15988       assert(VSNum >= 0 && VSNum <= 63 &&
15989              "Attempted to access a vsr out of range");
15990       if (VSNum < 32)
15991         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15992       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15993     }
15994 
15995     // For float registers, we can't defer to the base class as it will match
15996     // the SPILLTOVSRRC class.
15997     if (Constraint.size() > 3 && Constraint[1] == 'f') {
15998       int RegNum = atoi(Constraint.data() + 2);
15999       if (RegNum > 31 || RegNum < 0)
16000         report_fatal_error("Invalid floating point register number");
16001       if (VT == MVT::f32 || VT == MVT::i32)
16002         return Subtarget.hasSPE()
16003                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16004                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16005       if (VT == MVT::f64 || VT == MVT::i64)
16006         return Subtarget.hasSPE()
16007                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16008                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16009     }
16010   }
16011 
16012   std::pair<unsigned, const TargetRegisterClass *> R =
16013       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16014 
16015   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16016   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16017   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16018   // register.
16019   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16020   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16021   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16022       PPC::GPRCRegClass.contains(R.first))
16023     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16024                             PPC::sub_32, &PPC::G8RCRegClass),
16025                           &PPC::G8RCRegClass);
16026 
16027   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16028   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16029     R.first = PPC::CR0;
16030     R.second = &PPC::CRRCRegClass;
16031   }
16032   // FIXME: This warning should ideally be emitted in the front end.
16033   const auto &TM = getTargetMachine();
16034   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16035     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16036          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16037         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16038       errs() << "warning: vector registers 20 to 32 are reserved in the "
16039                 "default AIX AltiVec ABI and cannot be used\n";
16040   }
16041 
16042   return R;
16043 }
16044 
16045 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16046 /// vector.  If it is invalid, don't add anything to Ops.
16047 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16048                                                      std::string &Constraint,
16049                                                      std::vector<SDValue>&Ops,
16050                                                      SelectionDAG &DAG) const {
16051   SDValue Result;
16052 
16053   // Only support length 1 constraints.
16054   if (Constraint.length() > 1) return;
16055 
16056   char Letter = Constraint[0];
16057   switch (Letter) {
16058   default: break;
16059   case 'I':
16060   case 'J':
16061   case 'K':
16062   case 'L':
16063   case 'M':
16064   case 'N':
16065   case 'O':
16066   case 'P': {
16067     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16068     if (!CST) return; // Must be an immediate to match.
16069     SDLoc dl(Op);
16070     int64_t Value = CST->getSExtValue();
16071     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16072                          // numbers are printed as such.
16073     switch (Letter) {
16074     default: llvm_unreachable("Unknown constraint letter!");
16075     case 'I':  // "I" is a signed 16-bit constant.
16076       if (isInt<16>(Value))
16077         Result = DAG.getTargetConstant(Value, dl, TCVT);
16078       break;
16079     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16080       if (isShiftedUInt<16, 16>(Value))
16081         Result = DAG.getTargetConstant(Value, dl, TCVT);
16082       break;
16083     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16084       if (isShiftedInt<16, 16>(Value))
16085         Result = DAG.getTargetConstant(Value, dl, TCVT);
16086       break;
16087     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16088       if (isUInt<16>(Value))
16089         Result = DAG.getTargetConstant(Value, dl, TCVT);
16090       break;
16091     case 'M':  // "M" is a constant that is greater than 31.
16092       if (Value > 31)
16093         Result = DAG.getTargetConstant(Value, dl, TCVT);
16094       break;
16095     case 'N':  // "N" is a positive constant that is an exact power of two.
16096       if (Value > 0 && isPowerOf2_64(Value))
16097         Result = DAG.getTargetConstant(Value, dl, TCVT);
16098       break;
16099     case 'O':  // "O" is the constant zero.
16100       if (Value == 0)
16101         Result = DAG.getTargetConstant(Value, dl, TCVT);
16102       break;
16103     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16104       if (isInt<16>(-Value))
16105         Result = DAG.getTargetConstant(Value, dl, TCVT);
16106       break;
16107     }
16108     break;
16109   }
16110   }
16111 
16112   if (Result.getNode()) {
16113     Ops.push_back(Result);
16114     return;
16115   }
16116 
16117   // Handle standard constraint letters.
16118   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16119 }
16120 
16121 // isLegalAddressingMode - Return true if the addressing mode represented
16122 // by AM is legal for this target, for a load/store of the specified type.
16123 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16124                                               const AddrMode &AM, Type *Ty,
16125                                               unsigned AS,
16126                                               Instruction *I) const {
16127   // Vector type r+i form is supported since power9 as DQ form. We don't check
16128   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16129   // imm form is preferred and the offset can be adjusted to use imm form later
16130   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16131   // max offset to check legal addressing mode, we should be a little aggressive
16132   // to contain other offsets for that LSRUse.
16133   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16134     return false;
16135 
16136   // PPC allows a sign-extended 16-bit immediate field.
16137   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16138     return false;
16139 
16140   // No global is ever allowed as a base.
16141   if (AM.BaseGV)
16142     return false;
16143 
16144   // PPC only support r+r,
16145   switch (AM.Scale) {
16146   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16147     break;
16148   case 1:
16149     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16150       return false;
16151     // Otherwise we have r+r or r+i.
16152     break;
16153   case 2:
16154     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16155       return false;
16156     // Allow 2*r as r+r.
16157     break;
16158   default:
16159     // No other scales are supported.
16160     return false;
16161   }
16162 
16163   return true;
16164 }
16165 
16166 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16167                                            SelectionDAG &DAG) const {
16168   MachineFunction &MF = DAG.getMachineFunction();
16169   MachineFrameInfo &MFI = MF.getFrameInfo();
16170   MFI.setReturnAddressIsTaken(true);
16171 
16172   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16173     return SDValue();
16174 
16175   SDLoc dl(Op);
16176   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16177 
16178   // Make sure the function does not optimize away the store of the RA to
16179   // the stack.
16180   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16181   FuncInfo->setLRStoreRequired();
16182   bool isPPC64 = Subtarget.isPPC64();
16183   auto PtrVT = getPointerTy(MF.getDataLayout());
16184 
16185   if (Depth > 0) {
16186     // The link register (return address) is saved in the caller's frame
16187     // not the callee's stack frame. So we must get the caller's frame
16188     // address and load the return address at the LR offset from there.
16189     SDValue FrameAddr =
16190         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16191                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16192     SDValue Offset =
16193         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16194                         isPPC64 ? MVT::i64 : MVT::i32);
16195     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16196                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16197                        MachinePointerInfo());
16198   }
16199 
16200   // Just load the return address off the stack.
16201   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16202   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16203                      MachinePointerInfo());
16204 }
16205 
16206 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16207                                           SelectionDAG &DAG) const {
16208   SDLoc dl(Op);
16209   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16210 
16211   MachineFunction &MF = DAG.getMachineFunction();
16212   MachineFrameInfo &MFI = MF.getFrameInfo();
16213   MFI.setFrameAddressIsTaken(true);
16214 
16215   EVT PtrVT = getPointerTy(MF.getDataLayout());
16216   bool isPPC64 = PtrVT == MVT::i64;
16217 
16218   // Naked functions never have a frame pointer, and so we use r1. For all
16219   // other functions, this decision must be delayed until during PEI.
16220   unsigned FrameReg;
16221   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16222     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16223   else
16224     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16225 
16226   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16227                                          PtrVT);
16228   while (Depth--)
16229     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16230                             FrameAddr, MachinePointerInfo());
16231   return FrameAddr;
16232 }
16233 
16234 // FIXME? Maybe this could be a TableGen attribute on some registers and
16235 // this table could be generated automatically from RegInfo.
16236 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16237                                               const MachineFunction &MF) const {
16238   bool isPPC64 = Subtarget.isPPC64();
16239 
16240   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16241   if (!is64Bit && VT != LLT::scalar(32))
16242     report_fatal_error("Invalid register global variable type");
16243 
16244   Register Reg = StringSwitch<Register>(RegName)
16245                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16246                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16247                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16248                      .Default(Register());
16249 
16250   if (Reg)
16251     return Reg;
16252   report_fatal_error("Invalid register name global variable");
16253 }
16254 
16255 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16256   // 32-bit SVR4 ABI access everything as got-indirect.
16257   if (Subtarget.is32BitELFABI())
16258     return true;
16259 
16260   // AIX accesses everything indirectly through the TOC, which is similar to
16261   // the GOT.
16262   if (Subtarget.isAIXABI())
16263     return true;
16264 
16265   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16266   // If it is small or large code model, module locals are accessed
16267   // indirectly by loading their address from .toc/.got.
16268   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16269     return true;
16270 
16271   // JumpTable and BlockAddress are accessed as got-indirect.
16272   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16273     return true;
16274 
16275   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16276     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16277 
16278   return false;
16279 }
16280 
16281 bool
16282 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16283   // The PowerPC target isn't yet aware of offsets.
16284   return false;
16285 }
16286 
16287 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16288                                            const CallInst &I,
16289                                            MachineFunction &MF,
16290                                            unsigned Intrinsic) const {
16291   switch (Intrinsic) {
16292   case Intrinsic::ppc_atomicrmw_xchg_i128:
16293   case Intrinsic::ppc_atomicrmw_add_i128:
16294   case Intrinsic::ppc_atomicrmw_sub_i128:
16295   case Intrinsic::ppc_atomicrmw_nand_i128:
16296   case Intrinsic::ppc_atomicrmw_and_i128:
16297   case Intrinsic::ppc_atomicrmw_or_i128:
16298   case Intrinsic::ppc_atomicrmw_xor_i128:
16299   case Intrinsic::ppc_cmpxchg_i128:
16300     Info.opc = ISD::INTRINSIC_W_CHAIN;
16301     Info.memVT = MVT::i128;
16302     Info.ptrVal = I.getArgOperand(0);
16303     Info.offset = 0;
16304     Info.align = Align(16);
16305     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16306                  MachineMemOperand::MOVolatile;
16307     return true;
16308   case Intrinsic::ppc_atomic_load_i128:
16309     Info.opc = ISD::INTRINSIC_W_CHAIN;
16310     Info.memVT = MVT::i128;
16311     Info.ptrVal = I.getArgOperand(0);
16312     Info.offset = 0;
16313     Info.align = Align(16);
16314     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16315     return true;
16316   case Intrinsic::ppc_atomic_store_i128:
16317     Info.opc = ISD::INTRINSIC_VOID;
16318     Info.memVT = MVT::i128;
16319     Info.ptrVal = I.getArgOperand(2);
16320     Info.offset = 0;
16321     Info.align = Align(16);
16322     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16323     return true;
16324   case Intrinsic::ppc_altivec_lvx:
16325   case Intrinsic::ppc_altivec_lvxl:
16326   case Intrinsic::ppc_altivec_lvebx:
16327   case Intrinsic::ppc_altivec_lvehx:
16328   case Intrinsic::ppc_altivec_lvewx:
16329   case Intrinsic::ppc_vsx_lxvd2x:
16330   case Intrinsic::ppc_vsx_lxvw4x:
16331   case Intrinsic::ppc_vsx_lxvd2x_be:
16332   case Intrinsic::ppc_vsx_lxvw4x_be:
16333   case Intrinsic::ppc_vsx_lxvl:
16334   case Intrinsic::ppc_vsx_lxvll: {
16335     EVT VT;
16336     switch (Intrinsic) {
16337     case Intrinsic::ppc_altivec_lvebx:
16338       VT = MVT::i8;
16339       break;
16340     case Intrinsic::ppc_altivec_lvehx:
16341       VT = MVT::i16;
16342       break;
16343     case Intrinsic::ppc_altivec_lvewx:
16344       VT = MVT::i32;
16345       break;
16346     case Intrinsic::ppc_vsx_lxvd2x:
16347     case Intrinsic::ppc_vsx_lxvd2x_be:
16348       VT = MVT::v2f64;
16349       break;
16350     default:
16351       VT = MVT::v4i32;
16352       break;
16353     }
16354 
16355     Info.opc = ISD::INTRINSIC_W_CHAIN;
16356     Info.memVT = VT;
16357     Info.ptrVal = I.getArgOperand(0);
16358     Info.offset = -VT.getStoreSize()+1;
16359     Info.size = 2*VT.getStoreSize()-1;
16360     Info.align = Align(1);
16361     Info.flags = MachineMemOperand::MOLoad;
16362     return true;
16363   }
16364   case Intrinsic::ppc_altivec_stvx:
16365   case Intrinsic::ppc_altivec_stvxl:
16366   case Intrinsic::ppc_altivec_stvebx:
16367   case Intrinsic::ppc_altivec_stvehx:
16368   case Intrinsic::ppc_altivec_stvewx:
16369   case Intrinsic::ppc_vsx_stxvd2x:
16370   case Intrinsic::ppc_vsx_stxvw4x:
16371   case Intrinsic::ppc_vsx_stxvd2x_be:
16372   case Intrinsic::ppc_vsx_stxvw4x_be:
16373   case Intrinsic::ppc_vsx_stxvl:
16374   case Intrinsic::ppc_vsx_stxvll: {
16375     EVT VT;
16376     switch (Intrinsic) {
16377     case Intrinsic::ppc_altivec_stvebx:
16378       VT = MVT::i8;
16379       break;
16380     case Intrinsic::ppc_altivec_stvehx:
16381       VT = MVT::i16;
16382       break;
16383     case Intrinsic::ppc_altivec_stvewx:
16384       VT = MVT::i32;
16385       break;
16386     case Intrinsic::ppc_vsx_stxvd2x:
16387     case Intrinsic::ppc_vsx_stxvd2x_be:
16388       VT = MVT::v2f64;
16389       break;
16390     default:
16391       VT = MVT::v4i32;
16392       break;
16393     }
16394 
16395     Info.opc = ISD::INTRINSIC_VOID;
16396     Info.memVT = VT;
16397     Info.ptrVal = I.getArgOperand(1);
16398     Info.offset = -VT.getStoreSize()+1;
16399     Info.size = 2*VT.getStoreSize()-1;
16400     Info.align = Align(1);
16401     Info.flags = MachineMemOperand::MOStore;
16402     return true;
16403   }
16404   default:
16405     break;
16406   }
16407 
16408   return false;
16409 }
16410 
16411 /// It returns EVT::Other if the type should be determined using generic
16412 /// target-independent logic.
16413 EVT PPCTargetLowering::getOptimalMemOpType(
16414     const MemOp &Op, const AttributeList &FuncAttributes) const {
16415   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16416     // We should use Altivec/VSX loads and stores when available. For unaligned
16417     // addresses, unaligned VSX loads are only fast starting with the P8.
16418     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16419         (Op.isAligned(Align(16)) ||
16420          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16421       return MVT::v4i32;
16422   }
16423 
16424   if (Subtarget.isPPC64()) {
16425     return MVT::i64;
16426   }
16427 
16428   return MVT::i32;
16429 }
16430 
16431 /// Returns true if it is beneficial to convert a load of a constant
16432 /// to just the constant itself.
16433 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16434                                                           Type *Ty) const {
16435   assert(Ty->isIntegerTy());
16436 
16437   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16438   return !(BitSize == 0 || BitSize > 64);
16439 }
16440 
16441 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16442   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16443     return false;
16444   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16445   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16446   return NumBits1 == 64 && NumBits2 == 32;
16447 }
16448 
16449 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16450   if (!VT1.isInteger() || !VT2.isInteger())
16451     return false;
16452   unsigned NumBits1 = VT1.getSizeInBits();
16453   unsigned NumBits2 = VT2.getSizeInBits();
16454   return NumBits1 == 64 && NumBits2 == 32;
16455 }
16456 
16457 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16458   // Generally speaking, zexts are not free, but they are free when they can be
16459   // folded with other operations.
16460   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16461     EVT MemVT = LD->getMemoryVT();
16462     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16463          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16464         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16465          LD->getExtensionType() == ISD::ZEXTLOAD))
16466       return true;
16467   }
16468 
16469   // FIXME: Add other cases...
16470   //  - 32-bit shifts with a zext to i64
16471   //  - zext after ctlz, bswap, etc.
16472   //  - zext after and by a constant mask
16473 
16474   return TargetLowering::isZExtFree(Val, VT2);
16475 }
16476 
16477 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16478   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16479          "invalid fpext types");
16480   // Extending to float128 is not free.
16481   if (DestVT == MVT::f128)
16482     return false;
16483   return true;
16484 }
16485 
16486 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16487   return isInt<16>(Imm) || isUInt<16>(Imm);
16488 }
16489 
16490 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16491   return isInt<16>(Imm) || isUInt<16>(Imm);
16492 }
16493 
16494 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16495                                                        MachineMemOperand::Flags,
16496                                                        bool *Fast) const {
16497   if (DisablePPCUnaligned)
16498     return false;
16499 
16500   // PowerPC supports unaligned memory access for simple non-vector types.
16501   // Although accessing unaligned addresses is not as efficient as accessing
16502   // aligned addresses, it is generally more efficient than manual expansion,
16503   // and generally only traps for software emulation when crossing page
16504   // boundaries.
16505 
16506   if (!VT.isSimple())
16507     return false;
16508 
16509   if (VT.isFloatingPoint() && !VT.isVector() &&
16510       !Subtarget.allowsUnalignedFPAccess())
16511     return false;
16512 
16513   if (VT.getSimpleVT().isVector()) {
16514     if (Subtarget.hasVSX()) {
16515       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16516           VT != MVT::v4f32 && VT != MVT::v4i32)
16517         return false;
16518     } else {
16519       return false;
16520     }
16521   }
16522 
16523   if (VT == MVT::ppcf128)
16524     return false;
16525 
16526   if (Fast)
16527     *Fast = true;
16528 
16529   return true;
16530 }
16531 
16532 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16533                                                SDValue C) const {
16534   // Check integral scalar types.
16535   if (!VT.isScalarInteger())
16536     return false;
16537   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16538     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16539       return false;
16540     // This transformation will generate >= 2 operations. But the following
16541     // cases will generate <= 2 instructions during ISEL. So exclude them.
16542     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16543     // HW instruction, ie. MULLI
16544     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16545     // instruction is needed than case 1, ie. MULLI and RLDICR
16546     int64_t Imm = ConstNode->getSExtValue();
16547     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16548     Imm >>= Shift;
16549     if (isInt<16>(Imm))
16550       return false;
16551     uint64_t UImm = static_cast<uint64_t>(Imm);
16552     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16553         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16554       return true;
16555   }
16556   return false;
16557 }
16558 
16559 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16560                                                    EVT VT) const {
16561   return isFMAFasterThanFMulAndFAdd(
16562       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16563 }
16564 
16565 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16566                                                    Type *Ty) const {
16567   switch (Ty->getScalarType()->getTypeID()) {
16568   case Type::FloatTyID:
16569   case Type::DoubleTyID:
16570     return true;
16571   case Type::FP128TyID:
16572     return Subtarget.hasP9Vector();
16573   default:
16574     return false;
16575   }
16576 }
16577 
16578 // FIXME: add more patterns which are not profitable to hoist.
16579 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16580   if (!I->hasOneUse())
16581     return true;
16582 
16583   Instruction *User = I->user_back();
16584   assert(User && "A single use instruction with no uses.");
16585 
16586   switch (I->getOpcode()) {
16587   case Instruction::FMul: {
16588     // Don't break FMA, PowerPC prefers FMA.
16589     if (User->getOpcode() != Instruction::FSub &&
16590         User->getOpcode() != Instruction::FAdd)
16591       return true;
16592 
16593     const TargetOptions &Options = getTargetMachine().Options;
16594     const Function *F = I->getFunction();
16595     const DataLayout &DL = F->getParent()->getDataLayout();
16596     Type *Ty = User->getOperand(0)->getType();
16597 
16598     return !(
16599         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16600         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16601         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16602   }
16603   case Instruction::Load: {
16604     // Don't break "store (load float*)" pattern, this pattern will be combined
16605     // to "store (load int32)" in later InstCombine pass. See function
16606     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16607     // cycles than loading a 32 bit integer.
16608     LoadInst *LI = cast<LoadInst>(I);
16609     // For the loads that combineLoadToOperationType does nothing, like
16610     // ordered load, it should be profitable to hoist them.
16611     // For swifterror load, it can only be used for pointer to pointer type, so
16612     // later type check should get rid of this case.
16613     if (!LI->isUnordered())
16614       return true;
16615 
16616     if (User->getOpcode() != Instruction::Store)
16617       return true;
16618 
16619     if (I->getType()->getTypeID() != Type::FloatTyID)
16620       return true;
16621 
16622     return false;
16623   }
16624   default:
16625     return true;
16626   }
16627   return true;
16628 }
16629 
16630 const MCPhysReg *
16631 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16632   // LR is a callee-save register, but we must treat it as clobbered by any call
16633   // site. Hence we include LR in the scratch registers, which are in turn added
16634   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16635   // to CTR, which is used by any indirect call.
16636   static const MCPhysReg ScratchRegs[] = {
16637     PPC::X12, PPC::LR8, PPC::CTR8, 0
16638   };
16639 
16640   return ScratchRegs;
16641 }
16642 
16643 Register PPCTargetLowering::getExceptionPointerRegister(
16644     const Constant *PersonalityFn) const {
16645   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16646 }
16647 
16648 Register PPCTargetLowering::getExceptionSelectorRegister(
16649     const Constant *PersonalityFn) const {
16650   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16651 }
16652 
16653 bool
16654 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16655                      EVT VT , unsigned DefinedValues) const {
16656   if (VT == MVT::v2i64)
16657     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16658 
16659   if (Subtarget.hasVSX())
16660     return true;
16661 
16662   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16663 }
16664 
16665 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16666   if (DisableILPPref || Subtarget.enableMachineScheduler())
16667     return TargetLowering::getSchedulingPreference(N);
16668 
16669   return Sched::ILP;
16670 }
16671 
16672 // Create a fast isel object.
16673 FastISel *
16674 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16675                                   const TargetLibraryInfo *LibInfo) const {
16676   return PPC::createFastISel(FuncInfo, LibInfo);
16677 }
16678 
16679 // 'Inverted' means the FMA opcode after negating one multiplicand.
16680 // For example, (fma -a b c) = (fnmsub a b c)
16681 static unsigned invertFMAOpcode(unsigned Opc) {
16682   switch (Opc) {
16683   default:
16684     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16685   case ISD::FMA:
16686     return PPCISD::FNMSUB;
16687   case PPCISD::FNMSUB:
16688     return ISD::FMA;
16689   }
16690 }
16691 
16692 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16693                                                 bool LegalOps, bool OptForSize,
16694                                                 NegatibleCost &Cost,
16695                                                 unsigned Depth) const {
16696   if (Depth > SelectionDAG::MaxRecursionDepth)
16697     return SDValue();
16698 
16699   unsigned Opc = Op.getOpcode();
16700   EVT VT = Op.getValueType();
16701   SDNodeFlags Flags = Op.getNode()->getFlags();
16702 
16703   switch (Opc) {
16704   case PPCISD::FNMSUB:
16705     if (!Op.hasOneUse() || !isTypeLegal(VT))
16706       break;
16707 
16708     const TargetOptions &Options = getTargetMachine().Options;
16709     SDValue N0 = Op.getOperand(0);
16710     SDValue N1 = Op.getOperand(1);
16711     SDValue N2 = Op.getOperand(2);
16712     SDLoc Loc(Op);
16713 
16714     NegatibleCost N2Cost = NegatibleCost::Expensive;
16715     SDValue NegN2 =
16716         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16717 
16718     if (!NegN2)
16719       return SDValue();
16720 
16721     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16722     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16723     // These transformations may change sign of zeroes. For example,
16724     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16725     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16726       // Try and choose the cheaper one to negate.
16727       NegatibleCost N0Cost = NegatibleCost::Expensive;
16728       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16729                                            N0Cost, Depth + 1);
16730 
16731       NegatibleCost N1Cost = NegatibleCost::Expensive;
16732       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16733                                            N1Cost, Depth + 1);
16734 
16735       if (NegN0 && N0Cost <= N1Cost) {
16736         Cost = std::min(N0Cost, N2Cost);
16737         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16738       } else if (NegN1) {
16739         Cost = std::min(N1Cost, N2Cost);
16740         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16741       }
16742     }
16743 
16744     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16745     if (isOperationLegal(ISD::FMA, VT)) {
16746       Cost = N2Cost;
16747       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16748     }
16749 
16750     break;
16751   }
16752 
16753   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16754                                               Cost, Depth);
16755 }
16756 
16757 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16758 bool PPCTargetLowering::useLoadStackGuardNode() const {
16759   if (!Subtarget.isTargetLinux())
16760     return TargetLowering::useLoadStackGuardNode();
16761   return true;
16762 }
16763 
16764 // Override to disable global variable loading on Linux and insert AIX canary
16765 // word declaration.
16766 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16767   if (Subtarget.isAIXABI()) {
16768     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16769                         Type::getInt8PtrTy(M.getContext()));
16770     return;
16771   }
16772   if (!Subtarget.isTargetLinux())
16773     return TargetLowering::insertSSPDeclarations(M);
16774 }
16775 
16776 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16777   if (Subtarget.isAIXABI())
16778     return M.getGlobalVariable(AIXSSPCanaryWordName);
16779   return TargetLowering::getSDagStackGuard(M);
16780 }
16781 
16782 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16783                                      bool ForCodeSize) const {
16784   if (!VT.isSimple() || !Subtarget.hasVSX())
16785     return false;
16786 
16787   switch(VT.getSimpleVT().SimpleTy) {
16788   default:
16789     // For FP types that are currently not supported by PPC backend, return
16790     // false. Examples: f16, f80.
16791     return false;
16792   case MVT::f32:
16793   case MVT::f64:
16794     if (Subtarget.hasPrefixInstrs()) {
16795       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16796       return true;
16797     }
16798     LLVM_FALLTHROUGH;
16799   case MVT::ppcf128:
16800     return Imm.isPosZero();
16801   }
16802 }
16803 
16804 // For vector shift operation op, fold
16805 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16806 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16807                                   SelectionDAG &DAG) {
16808   SDValue N0 = N->getOperand(0);
16809   SDValue N1 = N->getOperand(1);
16810   EVT VT = N0.getValueType();
16811   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16812   unsigned Opcode = N->getOpcode();
16813   unsigned TargetOpcode;
16814 
16815   switch (Opcode) {
16816   default:
16817     llvm_unreachable("Unexpected shift operation");
16818   case ISD::SHL:
16819     TargetOpcode = PPCISD::SHL;
16820     break;
16821   case ISD::SRL:
16822     TargetOpcode = PPCISD::SRL;
16823     break;
16824   case ISD::SRA:
16825     TargetOpcode = PPCISD::SRA;
16826     break;
16827   }
16828 
16829   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16830       N1->getOpcode() == ISD::AND)
16831     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16832       if (Mask->getZExtValue() == OpSizeInBits - 1)
16833         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16834 
16835   return SDValue();
16836 }
16837 
16838 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16839   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16840     return Value;
16841 
16842   SDValue N0 = N->getOperand(0);
16843   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16844   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16845       N0.getOpcode() != ISD::SIGN_EXTEND ||
16846       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16847       N->getValueType(0) != MVT::i64)
16848     return SDValue();
16849 
16850   // We can't save an operation here if the value is already extended, and
16851   // the existing shift is easier to combine.
16852   SDValue ExtsSrc = N0.getOperand(0);
16853   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16854       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16855     return SDValue();
16856 
16857   SDLoc DL(N0);
16858   SDValue ShiftBy = SDValue(CN1, 0);
16859   // We want the shift amount to be i32 on the extswli, but the shift could
16860   // have an i64.
16861   if (ShiftBy.getValueType() == MVT::i64)
16862     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16863 
16864   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16865                          ShiftBy);
16866 }
16867 
16868 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16869   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16870     return Value;
16871 
16872   return SDValue();
16873 }
16874 
16875 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16876   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16877     return Value;
16878 
16879   return SDValue();
16880 }
16881 
16882 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16883 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16884 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16885 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16886 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16887                                  const PPCSubtarget &Subtarget) {
16888   if (!Subtarget.isPPC64())
16889     return SDValue();
16890 
16891   SDValue LHS = N->getOperand(0);
16892   SDValue RHS = N->getOperand(1);
16893 
16894   auto isZextOfCompareWithConstant = [](SDValue Op) {
16895     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16896         Op.getValueType() != MVT::i64)
16897       return false;
16898 
16899     SDValue Cmp = Op.getOperand(0);
16900     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16901         Cmp.getOperand(0).getValueType() != MVT::i64)
16902       return false;
16903 
16904     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16905       int64_t NegConstant = 0 - Constant->getSExtValue();
16906       // Due to the limitations of the addi instruction,
16907       // -C is required to be [-32768, 32767].
16908       return isInt<16>(NegConstant);
16909     }
16910 
16911     return false;
16912   };
16913 
16914   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16915   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16916 
16917   // If there is a pattern, canonicalize a zext operand to the RHS.
16918   if (LHSHasPattern && !RHSHasPattern)
16919     std::swap(LHS, RHS);
16920   else if (!LHSHasPattern && !RHSHasPattern)
16921     return SDValue();
16922 
16923   SDLoc DL(N);
16924   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16925   SDValue Cmp = RHS.getOperand(0);
16926   SDValue Z = Cmp.getOperand(0);
16927   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
16928   int64_t NegConstant = 0 - Constant->getSExtValue();
16929 
16930   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16931   default: break;
16932   case ISD::SETNE: {
16933     //                                 when C == 0
16934     //                             --> addze X, (addic Z, -1).carry
16935     //                            /
16936     // add X, (zext(setne Z, C))--
16937     //                            \    when -32768 <= -C <= 32767 && C != 0
16938     //                             --> addze X, (addic (addi Z, -C), -1).carry
16939     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16940                               DAG.getConstant(NegConstant, DL, MVT::i64));
16941     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16942     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16943                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16944     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16945                        SDValue(Addc.getNode(), 1));
16946     }
16947   case ISD::SETEQ: {
16948     //                                 when C == 0
16949     //                             --> addze X, (subfic Z, 0).carry
16950     //                            /
16951     // add X, (zext(sete  Z, C))--
16952     //                            \    when -32768 <= -C <= 32767 && C != 0
16953     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16954     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16955                               DAG.getConstant(NegConstant, DL, MVT::i64));
16956     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16957     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16958                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16959     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16960                        SDValue(Subc.getNode(), 1));
16961     }
16962   }
16963 
16964   return SDValue();
16965 }
16966 
16967 // Transform
16968 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16969 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16970 // In this case both C1 and C2 must be known constants.
16971 // C1+C2 must fit into a 34 bit signed integer.
16972 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16973                                           const PPCSubtarget &Subtarget) {
16974   if (!Subtarget.isUsingPCRelativeCalls())
16975     return SDValue();
16976 
16977   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16978   // If we find that node try to cast the Global Address and the Constant.
16979   SDValue LHS = N->getOperand(0);
16980   SDValue RHS = N->getOperand(1);
16981 
16982   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16983     std::swap(LHS, RHS);
16984 
16985   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16986     return SDValue();
16987 
16988   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16989   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16990   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16991 
16992   // Check that both casts succeeded.
16993   if (!GSDN || !ConstNode)
16994     return SDValue();
16995 
16996   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16997   SDLoc DL(GSDN);
16998 
16999   // The signed int offset needs to fit in 34 bits.
17000   if (!isInt<34>(NewOffset))
17001     return SDValue();
17002 
17003   // The new global address is a copy of the old global address except
17004   // that it has the updated Offset.
17005   SDValue GA =
17006       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17007                                  NewOffset, GSDN->getTargetFlags());
17008   SDValue MatPCRel =
17009       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17010   return MatPCRel;
17011 }
17012 
17013 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17014   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17015     return Value;
17016 
17017   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17018     return Value;
17019 
17020   return SDValue();
17021 }
17022 
17023 // Detect TRUNCATE operations on bitcasts of float128 values.
17024 // What we are looking for here is the situtation where we extract a subset
17025 // of bits from a 128 bit float.
17026 // This can be of two forms:
17027 // 1) BITCAST of f128 feeding TRUNCATE
17028 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17029 // The reason this is required is because we do not have a legal i128 type
17030 // and so we want to prevent having to store the f128 and then reload part
17031 // of it.
17032 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17033                                            DAGCombinerInfo &DCI) const {
17034   // If we are using CRBits then try that first.
17035   if (Subtarget.useCRBits()) {
17036     // Check if CRBits did anything and return that if it did.
17037     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17038       return CRTruncValue;
17039   }
17040 
17041   SDLoc dl(N);
17042   SDValue Op0 = N->getOperand(0);
17043 
17044   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17045   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17046     EVT VT = N->getValueType(0);
17047     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17048       return SDValue();
17049     SDValue Sub = Op0.getOperand(0);
17050     if (Sub.getOpcode() == ISD::SUB) {
17051       SDValue SubOp0 = Sub.getOperand(0);
17052       SDValue SubOp1 = Sub.getOperand(1);
17053       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17054           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17055         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17056                                SubOp1.getOperand(0),
17057                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17058       }
17059     }
17060   }
17061 
17062   // Looking for a truncate of i128 to i64.
17063   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17064     return SDValue();
17065 
17066   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17067 
17068   // SRL feeding TRUNCATE.
17069   if (Op0.getOpcode() == ISD::SRL) {
17070     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17071     // The right shift has to be by 64 bits.
17072     if (!ConstNode || ConstNode->getZExtValue() != 64)
17073       return SDValue();
17074 
17075     // Switch the element number to extract.
17076     EltToExtract = EltToExtract ? 0 : 1;
17077     // Update Op0 past the SRL.
17078     Op0 = Op0.getOperand(0);
17079   }
17080 
17081   // BITCAST feeding a TRUNCATE possibly via SRL.
17082   if (Op0.getOpcode() == ISD::BITCAST &&
17083       Op0.getValueType() == MVT::i128 &&
17084       Op0.getOperand(0).getValueType() == MVT::f128) {
17085     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17086     return DCI.DAG.getNode(
17087         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17088         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17089   }
17090   return SDValue();
17091 }
17092 
17093 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17094   SelectionDAG &DAG = DCI.DAG;
17095 
17096   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17097   if (!ConstOpOrElement)
17098     return SDValue();
17099 
17100   // An imul is usually smaller than the alternative sequence for legal type.
17101   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17102       isOperationLegal(ISD::MUL, N->getValueType(0)))
17103     return SDValue();
17104 
17105   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17106     switch (this->Subtarget.getCPUDirective()) {
17107     default:
17108       // TODO: enhance the condition for subtarget before pwr8
17109       return false;
17110     case PPC::DIR_PWR8:
17111       //  type        mul     add    shl
17112       // scalar        4       1      1
17113       // vector        7       2      2
17114       return true;
17115     case PPC::DIR_PWR9:
17116     case PPC::DIR_PWR10:
17117     case PPC::DIR_PWR_FUTURE:
17118       //  type        mul     add    shl
17119       // scalar        5       2      2
17120       // vector        7       2      2
17121 
17122       // The cycle RATIO of related operations are showed as a table above.
17123       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17124       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17125       // are 4, it is always profitable; but for 3 instrs patterns
17126       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17127       // So we should only do it for vector type.
17128       return IsAddOne && IsNeg ? VT.isVector() : true;
17129     }
17130   };
17131 
17132   EVT VT = N->getValueType(0);
17133   SDLoc DL(N);
17134 
17135   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17136   bool IsNeg = MulAmt.isNegative();
17137   APInt MulAmtAbs = MulAmt.abs();
17138 
17139   if ((MulAmtAbs - 1).isPowerOf2()) {
17140     // (mul x, 2^N + 1) => (add (shl x, N), x)
17141     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17142 
17143     if (!IsProfitable(IsNeg, true, VT))
17144       return SDValue();
17145 
17146     SDValue Op0 = N->getOperand(0);
17147     SDValue Op1 =
17148         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17149                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17150     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17151 
17152     if (!IsNeg)
17153       return Res;
17154 
17155     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17156   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17157     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17158     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17159 
17160     if (!IsProfitable(IsNeg, false, VT))
17161       return SDValue();
17162 
17163     SDValue Op0 = N->getOperand(0);
17164     SDValue Op1 =
17165         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17166                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17167 
17168     if (!IsNeg)
17169       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17170     else
17171       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17172 
17173   } else {
17174     return SDValue();
17175   }
17176 }
17177 
17178 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17179 // in combiner since we need to check SD flags and other subtarget features.
17180 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17181                                           DAGCombinerInfo &DCI) const {
17182   SDValue N0 = N->getOperand(0);
17183   SDValue N1 = N->getOperand(1);
17184   SDValue N2 = N->getOperand(2);
17185   SDNodeFlags Flags = N->getFlags();
17186   EVT VT = N->getValueType(0);
17187   SelectionDAG &DAG = DCI.DAG;
17188   const TargetOptions &Options = getTargetMachine().Options;
17189   unsigned Opc = N->getOpcode();
17190   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17191   bool LegalOps = !DCI.isBeforeLegalizeOps();
17192   SDLoc Loc(N);
17193 
17194   if (!isOperationLegal(ISD::FMA, VT))
17195     return SDValue();
17196 
17197   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17198   // since (fnmsub a b c)=-0 while c-ab=+0.
17199   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17200     return SDValue();
17201 
17202   // (fma (fneg a) b c) => (fnmsub a b c)
17203   // (fnmsub (fneg a) b c) => (fma a b c)
17204   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17205     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17206 
17207   // (fma a (fneg b) c) => (fnmsub a b c)
17208   // (fnmsub a (fneg b) c) => (fma a b c)
17209   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17210     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17211 
17212   return SDValue();
17213 }
17214 
17215 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17216   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17217   if (!Subtarget.is64BitELFABI())
17218     return false;
17219 
17220   // If not a tail call then no need to proceed.
17221   if (!CI->isTailCall())
17222     return false;
17223 
17224   // If sibling calls have been disabled and tail-calls aren't guaranteed
17225   // there is no reason to duplicate.
17226   auto &TM = getTargetMachine();
17227   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17228     return false;
17229 
17230   // Can't tail call a function called indirectly, or if it has variadic args.
17231   const Function *Callee = CI->getCalledFunction();
17232   if (!Callee || Callee->isVarArg())
17233     return false;
17234 
17235   // Make sure the callee and caller calling conventions are eligible for tco.
17236   const Function *Caller = CI->getParent()->getParent();
17237   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17238                                            CI->getCallingConv()))
17239       return false;
17240 
17241   // If the function is local then we have a good chance at tail-calling it
17242   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17243 }
17244 
17245 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17246   if (!Subtarget.hasVSX())
17247     return false;
17248   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17249     return true;
17250   return VT == MVT::f32 || VT == MVT::f64 ||
17251     VT == MVT::v4f32 || VT == MVT::v2f64;
17252 }
17253 
17254 bool PPCTargetLowering::
17255 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17256   const Value *Mask = AndI.getOperand(1);
17257   // If the mask is suitable for andi. or andis. we should sink the and.
17258   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17259     // Can't handle constants wider than 64-bits.
17260     if (CI->getBitWidth() > 64)
17261       return false;
17262     int64_t ConstVal = CI->getZExtValue();
17263     return isUInt<16>(ConstVal) ||
17264       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17265   }
17266 
17267   // For non-constant masks, we can always use the record-form and.
17268   return true;
17269 }
17270 
17271 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17272 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17273 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17274 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17275 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17276 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17277   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17278   assert(Subtarget.hasP9Altivec() &&
17279          "Only combine this when P9 altivec supported!");
17280   EVT VT = N->getValueType(0);
17281   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17282     return SDValue();
17283 
17284   SelectionDAG &DAG = DCI.DAG;
17285   SDLoc dl(N);
17286   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17287     // Even for signed integers, if it's known to be positive (as signed
17288     // integer) due to zero-extended inputs.
17289     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17290     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17291     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17292          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17293         (SubOpcd1 == ISD::ZERO_EXTEND ||
17294          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17295       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17296                          N->getOperand(0)->getOperand(0),
17297                          N->getOperand(0)->getOperand(1),
17298                          DAG.getTargetConstant(0, dl, MVT::i32));
17299     }
17300 
17301     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17302     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17303         N->getOperand(0).hasOneUse()) {
17304       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17305                          N->getOperand(0)->getOperand(0),
17306                          N->getOperand(0)->getOperand(1),
17307                          DAG.getTargetConstant(1, dl, MVT::i32));
17308     }
17309   }
17310 
17311   return SDValue();
17312 }
17313 
17314 // For type v4i32/v8ii16/v16i8, transform
17315 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17316 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17317 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17318 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17319 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17320                                           DAGCombinerInfo &DCI) const {
17321   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17322   assert(Subtarget.hasP9Altivec() &&
17323          "Only combine this when P9 altivec supported!");
17324 
17325   SelectionDAG &DAG = DCI.DAG;
17326   SDLoc dl(N);
17327   SDValue Cond = N->getOperand(0);
17328   SDValue TrueOpnd = N->getOperand(1);
17329   SDValue FalseOpnd = N->getOperand(2);
17330   EVT VT = N->getOperand(1).getValueType();
17331 
17332   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17333       FalseOpnd.getOpcode() != ISD::SUB)
17334     return SDValue();
17335 
17336   // ABSD only available for type v4i32/v8i16/v16i8
17337   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17338     return SDValue();
17339 
17340   // At least to save one more dependent computation
17341   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17342     return SDValue();
17343 
17344   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17345 
17346   // Can only handle unsigned comparison here
17347   switch (CC) {
17348   default:
17349     return SDValue();
17350   case ISD::SETUGT:
17351   case ISD::SETUGE:
17352     break;
17353   case ISD::SETULT:
17354   case ISD::SETULE:
17355     std::swap(TrueOpnd, FalseOpnd);
17356     break;
17357   }
17358 
17359   SDValue CmpOpnd1 = Cond.getOperand(0);
17360   SDValue CmpOpnd2 = Cond.getOperand(1);
17361 
17362   // SETCC CmpOpnd1 CmpOpnd2 cond
17363   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17364   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17365   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17366       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17367       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17368       FalseOpnd.getOperand(1) == CmpOpnd1) {
17369     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17370                        CmpOpnd1, CmpOpnd2,
17371                        DAG.getTargetConstant(0, dl, MVT::i32));
17372   }
17373 
17374   return SDValue();
17375 }
17376 
17377 /// getAddrModeForFlags - Based on the set of address flags, select the most
17378 /// optimal instruction format to match by.
17379 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17380   // This is not a node we should be handling here.
17381   if (Flags == PPC::MOF_None)
17382     return PPC::AM_None;
17383   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17384   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17385     if ((Flags & FlagSet) == FlagSet)
17386       return PPC::AM_DForm;
17387   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17388     if ((Flags & FlagSet) == FlagSet)
17389       return PPC::AM_DSForm;
17390   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17391     if ((Flags & FlagSet) == FlagSet)
17392       return PPC::AM_DQForm;
17393   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17394     if ((Flags & FlagSet) == FlagSet)
17395       return PPC::AM_PrefixDForm;
17396   // If no other forms are selected, return an X-Form as it is the most
17397   // general addressing mode.
17398   return PPC::AM_XForm;
17399 }
17400 
17401 /// Set alignment flags based on whether or not the Frame Index is aligned.
17402 /// Utilized when computing flags for address computation when selecting
17403 /// load and store instructions.
17404 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17405                                SelectionDAG &DAG) {
17406   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17407   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17408   if (!FI)
17409     return;
17410   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17411   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17412   // If this is (add $FI, $S16Imm), the alignment flags are already set
17413   // based on the immediate. We just need to clear the alignment flags
17414   // if the FI alignment is weaker.
17415   if ((FrameIndexAlign % 4) != 0)
17416     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17417   if ((FrameIndexAlign % 16) != 0)
17418     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17419   // If the address is a plain FrameIndex, set alignment flags based on
17420   // FI alignment.
17421   if (!IsAdd) {
17422     if ((FrameIndexAlign % 4) == 0)
17423       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17424     if ((FrameIndexAlign % 16) == 0)
17425       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17426   }
17427 }
17428 
17429 /// Given a node, compute flags that are used for address computation when
17430 /// selecting load and store instructions. The flags computed are stored in
17431 /// FlagSet. This function takes into account whether the node is a constant,
17432 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17433 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17434                                               SelectionDAG &DAG) {
17435   // Set the alignment flags for the node depending on if the node is
17436   // 4-byte or 16-byte aligned.
17437   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17438     if ((Imm & 0x3) == 0)
17439       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17440     if ((Imm & 0xf) == 0)
17441       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17442   };
17443 
17444   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17445     // All 32-bit constants can be computed as LIS + Disp.
17446     const APInt &ConstImm = CN->getAPIntValue();
17447     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17448       FlagSet |= PPC::MOF_AddrIsSImm32;
17449       SetAlignFlagsForImm(ConstImm.getZExtValue());
17450       setAlignFlagsForFI(N, FlagSet, DAG);
17451     }
17452     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17453       FlagSet |= PPC::MOF_RPlusSImm34;
17454     else // Let constant materialization handle large constants.
17455       FlagSet |= PPC::MOF_NotAddNorCst;
17456   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17457     // This address can be represented as an addition of:
17458     // - Register + Imm16 (possibly a multiple of 4/16)
17459     // - Register + Imm34
17460     // - Register + PPCISD::Lo
17461     // - Register + Register
17462     // In any case, we won't have to match this as Base + Zero.
17463     SDValue RHS = N.getOperand(1);
17464     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17465       const APInt &ConstImm = CN->getAPIntValue();
17466       if (ConstImm.isSignedIntN(16)) {
17467         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17468         SetAlignFlagsForImm(ConstImm.getZExtValue());
17469         setAlignFlagsForFI(N, FlagSet, DAG);
17470       }
17471       if (ConstImm.isSignedIntN(34))
17472         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17473       else
17474         FlagSet |= PPC::MOF_RPlusR; // Register.
17475     } else if (RHS.getOpcode() == PPCISD::Lo &&
17476                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17477       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17478     else
17479       FlagSet |= PPC::MOF_RPlusR;
17480   } else { // The address computation is not a constant or an addition.
17481     setAlignFlagsForFI(N, FlagSet, DAG);
17482     FlagSet |= PPC::MOF_NotAddNorCst;
17483   }
17484 }
17485 
17486 static bool isPCRelNode(SDValue N) {
17487   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17488       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17489       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17490       isValidPCRelNode<JumpTableSDNode>(N) ||
17491       isValidPCRelNode<BlockAddressSDNode>(N));
17492 }
17493 
17494 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17495 /// the address flags of the load/store instruction that is to be matched.
17496 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17497                                            SelectionDAG &DAG) const {
17498   unsigned FlagSet = PPC::MOF_None;
17499 
17500   // Compute subtarget flags.
17501   if (!Subtarget.hasP9Vector())
17502     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17503   else {
17504     FlagSet |= PPC::MOF_SubtargetP9;
17505     if (Subtarget.hasPrefixInstrs())
17506       FlagSet |= PPC::MOF_SubtargetP10;
17507   }
17508   if (Subtarget.hasSPE())
17509     FlagSet |= PPC::MOF_SubtargetSPE;
17510 
17511   // Check if we have a PCRel node and return early.
17512   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17513     return FlagSet;
17514 
17515   // If the node is the paired load/store intrinsics, compute flags for
17516   // address computation and return early.
17517   unsigned ParentOp = Parent->getOpcode();
17518   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17519                                (ParentOp == ISD::INTRINSIC_VOID))) {
17520     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17521     assert(
17522         ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) &&
17523         "Only the paired load and store (lxvp/stxvp) intrinsics are valid.");
17524     SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) ? Parent->getOperand(2)
17525                                                        : Parent->getOperand(3);
17526     computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17527     FlagSet |= PPC::MOF_Vector;
17528     return FlagSet;
17529   }
17530 
17531   // Mark this as something we don't want to handle here if it is atomic
17532   // or pre-increment instruction.
17533   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17534     if (LSB->isIndexed())
17535       return PPC::MOF_None;
17536 
17537   // Compute in-memory type flags. This is based on if there are scalars,
17538   // floats or vectors.
17539   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17540   assert(MN && "Parent should be a MemSDNode!");
17541   EVT MemVT = MN->getMemoryVT();
17542   unsigned Size = MemVT.getSizeInBits();
17543   if (MemVT.isScalarInteger()) {
17544     assert(Size <= 128 &&
17545            "Not expecting scalar integers larger than 16 bytes!");
17546     if (Size < 32)
17547       FlagSet |= PPC::MOF_SubWordInt;
17548     else if (Size == 32)
17549       FlagSet |= PPC::MOF_WordInt;
17550     else
17551       FlagSet |= PPC::MOF_DoubleWordInt;
17552   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17553     if (Size == 128)
17554       FlagSet |= PPC::MOF_Vector;
17555     else if (Size == 256) {
17556       assert(Subtarget.pairedVectorMemops() &&
17557              "256-bit vectors are only available when paired vector memops is "
17558              "enabled!");
17559       FlagSet |= PPC::MOF_Vector;
17560     } else
17561       llvm_unreachable("Not expecting illegal vectors!");
17562   } else { // Floating point type: can be scalar, f128 or vector types.
17563     if (Size == 32 || Size == 64)
17564       FlagSet |= PPC::MOF_ScalarFloat;
17565     else if (MemVT == MVT::f128 || MemVT.isVector())
17566       FlagSet |= PPC::MOF_Vector;
17567     else
17568       llvm_unreachable("Not expecting illegal scalar floats!");
17569   }
17570 
17571   // Compute flags for address computation.
17572   computeFlagsForAddressComputation(N, FlagSet, DAG);
17573 
17574   // Compute type extension flags.
17575   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17576     switch (LN->getExtensionType()) {
17577     case ISD::SEXTLOAD:
17578       FlagSet |= PPC::MOF_SExt;
17579       break;
17580     case ISD::EXTLOAD:
17581     case ISD::ZEXTLOAD:
17582       FlagSet |= PPC::MOF_ZExt;
17583       break;
17584     case ISD::NON_EXTLOAD:
17585       FlagSet |= PPC::MOF_NoExt;
17586       break;
17587     }
17588   } else
17589     FlagSet |= PPC::MOF_NoExt;
17590 
17591   // For integers, no extension is the same as zero extension.
17592   // We set the extension mode to zero extension so we don't have
17593   // to add separate entries in AddrModesMap for loads and stores.
17594   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17595     FlagSet |= PPC::MOF_ZExt;
17596     FlagSet &= ~PPC::MOF_NoExt;
17597   }
17598 
17599   // If we don't have prefixed instructions, 34-bit constants should be
17600   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17601   bool IsNonP1034BitConst =
17602       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17603        FlagSet) == PPC::MOF_RPlusSImm34;
17604   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17605       IsNonP1034BitConst)
17606     FlagSet |= PPC::MOF_NotAddNorCst;
17607 
17608   return FlagSet;
17609 }
17610 
17611 /// SelectForceXFormMode - Given the specified address, force it to be
17612 /// represented as an indexed [r+r] operation (an XForm instruction).
17613 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17614                                                       SDValue &Base,
17615                                                       SelectionDAG &DAG) const {
17616 
17617   PPC::AddrMode Mode = PPC::AM_XForm;
17618   int16_t ForceXFormImm = 0;
17619   if (provablyDisjointOr(DAG, N) &&
17620       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17621     Disp = N.getOperand(0);
17622     Base = N.getOperand(1);
17623     return Mode;
17624   }
17625 
17626   // If the address is the result of an add, we will utilize the fact that the
17627   // address calculation includes an implicit add.  However, we can reduce
17628   // register pressure if we do not materialize a constant just for use as the
17629   // index register.  We only get rid of the add if it is not an add of a
17630   // value and a 16-bit signed constant and both have a single use.
17631   if (N.getOpcode() == ISD::ADD &&
17632       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17633        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17634     Disp = N.getOperand(0);
17635     Base = N.getOperand(1);
17636     return Mode;
17637   }
17638 
17639   // Otherwise, use R0 as the base register.
17640   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17641                          N.getValueType());
17642   Base = N;
17643 
17644   return Mode;
17645 }
17646 
17647 // If we happen to match to an aligned D-Form, check if the Frame Index is
17648 // adequately aligned. If it is not, reset the mode to match to X-Form.
17649 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17650                                    PPC::AddrMode &Mode) {
17651   if (!isa<FrameIndexSDNode>(N))
17652     return;
17653   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17654       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17655     Mode = PPC::AM_XForm;
17656 }
17657 
17658 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17659 /// compute the address flags of the node, get the optimal address mode based
17660 /// on the flags, and set the Base and Disp based on the address mode.
17661 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17662                                                        SDValue N, SDValue &Disp,
17663                                                        SDValue &Base,
17664                                                        SelectionDAG &DAG,
17665                                                        MaybeAlign Align) const {
17666   SDLoc DL(Parent);
17667 
17668   // Compute the address flags.
17669   unsigned Flags = computeMOFlags(Parent, N, DAG);
17670 
17671   // Get the optimal address mode based on the Flags.
17672   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17673 
17674   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17675   // Select an X-Form load if it is not.
17676   setXFormForUnalignedFI(N, Flags, Mode);
17677 
17678   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17679   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17680     assert(Subtarget.isUsingPCRelativeCalls() &&
17681            "Must be using PC-Relative calls when a valid PC-Relative node is "
17682            "present!");
17683     Mode = PPC::AM_PCRel;
17684   }
17685 
17686   // Set Base and Disp accordingly depending on the address mode.
17687   switch (Mode) {
17688   case PPC::AM_DForm:
17689   case PPC::AM_DSForm:
17690   case PPC::AM_DQForm: {
17691     // This is a register plus a 16-bit immediate. The base will be the
17692     // register and the displacement will be the immediate unless it
17693     // isn't sufficiently aligned.
17694     if (Flags & PPC::MOF_RPlusSImm16) {
17695       SDValue Op0 = N.getOperand(0);
17696       SDValue Op1 = N.getOperand(1);
17697       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17698       if (!Align || isAligned(*Align, Imm)) {
17699         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17700         Base = Op0;
17701         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17702           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17703           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17704         }
17705         break;
17706       }
17707     }
17708     // This is a register plus the @lo relocation. The base is the register
17709     // and the displacement is the global address.
17710     else if (Flags & PPC::MOF_RPlusLo) {
17711       Disp = N.getOperand(1).getOperand(0); // The global address.
17712       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17713              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17714              Disp.getOpcode() == ISD::TargetConstantPool ||
17715              Disp.getOpcode() == ISD::TargetJumpTable);
17716       Base = N.getOperand(0);
17717       break;
17718     }
17719     // This is a constant address at most 32 bits. The base will be
17720     // zero or load-immediate-shifted and the displacement will be
17721     // the low 16 bits of the address.
17722     else if (Flags & PPC::MOF_AddrIsSImm32) {
17723       auto *CN = cast<ConstantSDNode>(N);
17724       EVT CNType = CN->getValueType(0);
17725       uint64_t CNImm = CN->getZExtValue();
17726       // If this address fits entirely in a 16-bit sext immediate field, codegen
17727       // this as "d, 0".
17728       int16_t Imm;
17729       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17730         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17731         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17732                                CNType);
17733         break;
17734       }
17735       // Handle 32-bit sext immediate with LIS + Addr mode.
17736       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17737           (!Align || isAligned(*Align, CNImm))) {
17738         int32_t Addr = (int32_t)CNImm;
17739         // Otherwise, break this down into LIS + Disp.
17740         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17741         Base =
17742             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17743         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17744         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17745         break;
17746       }
17747     }
17748     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17749     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17750     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17751       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17752       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17753     } else
17754       Base = N;
17755     break;
17756   }
17757   case PPC::AM_PrefixDForm: {
17758     int64_t Imm34 = 0;
17759     unsigned Opcode = N.getOpcode();
17760     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17761         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17762       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17763       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17764       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17765         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17766       else
17767         Base = N.getOperand(0);
17768     } else if (isIntS34Immediate(N, Imm34)) {
17769       // The address is a 34-bit signed immediate.
17770       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17771       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
17772     }
17773     break;
17774   }
17775   case PPC::AM_PCRel: {
17776     // When selecting PC-Relative instructions, "Base" is not utilized as
17777     // we select the address as [PC+imm].
17778     Disp = N;
17779     break;
17780   }
17781   case PPC::AM_None:
17782     break;
17783   default: { // By default, X-Form is always available to be selected.
17784     // When a frame index is not aligned, we also match by XForm.
17785     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
17786     Base = FI ? N : N.getOperand(1);
17787     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17788                                 N.getValueType())
17789               : N.getOperand(0);
17790     break;
17791   }
17792   }
17793   return Mode;
17794 }
17795 
17796 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
17797                                                  bool Return,
17798                                                  bool IsVarArg) const {
17799   switch (CC) {
17800   case CallingConv::Cold:
17801     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
17802   default:
17803     return CC_PPC64_ELF_FIS;
17804   }
17805 }
17806 
17807 TargetLowering::AtomicExpansionKind
17808 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17809   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17810   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17811     return AtomicExpansionKind::MaskedIntrinsic;
17812   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
17813 }
17814 
17815 TargetLowering::AtomicExpansionKind
17816 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
17817   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
17818   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
17819     return AtomicExpansionKind::MaskedIntrinsic;
17820   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
17821 }
17822 
17823 static Intrinsic::ID
17824 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
17825   switch (BinOp) {
17826   default:
17827     llvm_unreachable("Unexpected AtomicRMW BinOp");
17828   case AtomicRMWInst::Xchg:
17829     return Intrinsic::ppc_atomicrmw_xchg_i128;
17830   case AtomicRMWInst::Add:
17831     return Intrinsic::ppc_atomicrmw_add_i128;
17832   case AtomicRMWInst::Sub:
17833     return Intrinsic::ppc_atomicrmw_sub_i128;
17834   case AtomicRMWInst::And:
17835     return Intrinsic::ppc_atomicrmw_and_i128;
17836   case AtomicRMWInst::Or:
17837     return Intrinsic::ppc_atomicrmw_or_i128;
17838   case AtomicRMWInst::Xor:
17839     return Intrinsic::ppc_atomicrmw_xor_i128;
17840   case AtomicRMWInst::Nand:
17841     return Intrinsic::ppc_atomicrmw_nand_i128;
17842   }
17843 }
17844 
17845 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
17846     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
17847     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
17848   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17849          "Only support quadword now");
17850   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17851   Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType();
17852   assert(ValTy->getPrimitiveSizeInBits() == 128);
17853   Function *RMW = Intrinsic::getDeclaration(
17854       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
17855   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17856   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
17857   Value *IncrHi =
17858       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
17859   Value *Addr =
17860       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17861   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
17862   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17863   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17864   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17865   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17866   return Builder.CreateOr(
17867       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17868 }
17869 
17870 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
17871     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
17872     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
17873   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
17874          "Only support quadword now");
17875   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17876   Type *ValTy = cast<PointerType>(AlignedAddr->getType())->getElementType();
17877   assert(ValTy->getPrimitiveSizeInBits() == 128);
17878   Function *IntCmpXchg =
17879       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
17880   Type *Int64Ty = Type::getInt64Ty(M->getContext());
17881   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
17882   Value *CmpHi =
17883       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
17884   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
17885   Value *NewHi =
17886       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
17887   Value *Addr =
17888       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
17889   emitLeadingFence(Builder, CI, Ord);
17890   Value *LoHi =
17891       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
17892   emitTrailingFence(Builder, CI, Ord);
17893   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17894   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17895   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17896   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17897   return Builder.CreateOr(
17898       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
17899 }
17900