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 // TODO - Remove this option if soft fp128 has been fully supported .
125 static cl::opt<bool>
126     EnableSoftFP128("enable-soft-fp128",
127                     cl::desc("temp option to enable soft fp128"), 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 // FIXME: Remove this once the bug has been fixed!
139 extern cl::opt<bool> ANDIGlueBug;
140 
141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
142                                      const PPCSubtarget &STI)
143     : TargetLowering(TM), Subtarget(STI) {
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       // EFPU2 APU only supports f32
155       if (!Subtarget.hasEFPU2())
156         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
157     } else {
158       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
159       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
160     }
161   }
162 
163   // Match BITREVERSE to customized fast code sequence in the td file.
164   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
165   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
166 
167   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
168   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
169 
170   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
171   for (MVT VT : MVT::integer_valuetypes()) {
172     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
173     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
174   }
175 
176   if (Subtarget.isISA3_0()) {
177     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
178     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
179     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
180     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
181   } else {
182     // No extending loads from f16 or HW conversions back and forth.
183     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
184     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
185     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
186     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
187     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
188     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
189     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
190     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
191   }
192 
193   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
194 
195   // PowerPC has pre-inc load and store's.
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
199   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
200   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
204   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
205   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
206   if (!Subtarget.hasSPE()) {
207     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
209     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
210     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
211   }
212 
213   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
214   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
215   for (MVT VT : ScalarIntVTs) {
216     setOperationAction(ISD::ADDC, VT, Legal);
217     setOperationAction(ISD::ADDE, VT, Legal);
218     setOperationAction(ISD::SUBC, VT, Legal);
219     setOperationAction(ISD::SUBE, VT, Legal);
220   }
221 
222   if (Subtarget.useCRBits()) {
223     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
224 
225     if (isPPC64 || Subtarget.hasFPCVT()) {
226       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
227       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
228                         isPPC64 ? MVT::i64 : MVT::i32);
229       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
230       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
231                         isPPC64 ? MVT::i64 : MVT::i32);
232 
233       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
234       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
235                          isPPC64 ? MVT::i64 : MVT::i32);
236       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
237       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
238                         isPPC64 ? MVT::i64 : MVT::i32);
239 
240       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
241       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
242                         isPPC64 ? MVT::i64 : MVT::i32);
243       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
244       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
245                         isPPC64 ? MVT::i64 : MVT::i32);
246 
247       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
248       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
249                         isPPC64 ? MVT::i64 : MVT::i32);
250       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
251       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
252                         isPPC64 ? MVT::i64 : MVT::i32);
253     } else {
254       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
255       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
256       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
257       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
258     }
259 
260     // PowerPC does not support direct load/store of condition registers.
261     setOperationAction(ISD::LOAD, MVT::i1, Custom);
262     setOperationAction(ISD::STORE, MVT::i1, Custom);
263 
264     // FIXME: Remove this once the ANDI glue bug is fixed:
265     if (ANDIGlueBug)
266       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
267 
268     for (MVT VT : MVT::integer_valuetypes()) {
269       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
270       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
271       setTruncStoreAction(VT, MVT::i1, Expand);
272     }
273 
274     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
275   }
276 
277   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
278   // PPC (the libcall is not available).
279   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
280   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
281   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
282   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
283 
284   // We do not currently implement these libm ops for PowerPC.
285   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
286   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
287   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
288   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
289   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
290   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
291 
292   // PowerPC has no SREM/UREM instructions unless we are on P9
293   // On P9 we may use a hardware instruction to compute the remainder.
294   // When the result of both the remainder and the division is required it is
295   // more efficient to compute the remainder from the result of the division
296   // rather than use the remainder instruction. The instructions are legalized
297   // directly because the DivRemPairsPass performs the transformation at the IR
298   // level.
299   if (Subtarget.isISA3_0()) {
300     setOperationAction(ISD::SREM, MVT::i32, Legal);
301     setOperationAction(ISD::UREM, MVT::i32, Legal);
302     setOperationAction(ISD::SREM, MVT::i64, Legal);
303     setOperationAction(ISD::UREM, MVT::i64, Legal);
304   } else {
305     setOperationAction(ISD::SREM, MVT::i32, Expand);
306     setOperationAction(ISD::UREM, MVT::i32, Expand);
307     setOperationAction(ISD::SREM, MVT::i64, Expand);
308     setOperationAction(ISD::UREM, MVT::i64, Expand);
309   }
310 
311   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
312   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
313   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
314   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
315   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
316   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
317   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
318   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
319   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
320 
321   // Handle constrained floating-point operations of scalar.
322   // TODO: Handle SPE specific operation.
323   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
324   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
325   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
326   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
327   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
328   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
329 
330   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
331   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
332   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
333   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
334   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
335   if (Subtarget.hasVSX()) {
336     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
337     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
338   }
339 
340   if (Subtarget.hasFSQRT()) {
341     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
342     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
343   }
344 
345   if (Subtarget.hasFPRND()) {
346     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
347     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
348     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
349     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
350 
351     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
352     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
353     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
354     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
355   }
356 
357   // We don't support sin/cos/sqrt/fmod/pow
358   setOperationAction(ISD::FSIN , MVT::f64, Expand);
359   setOperationAction(ISD::FCOS , MVT::f64, Expand);
360   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
361   setOperationAction(ISD::FREM , MVT::f64, Expand);
362   setOperationAction(ISD::FPOW , MVT::f64, Expand);
363   setOperationAction(ISD::FSIN , MVT::f32, Expand);
364   setOperationAction(ISD::FCOS , MVT::f32, Expand);
365   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
366   setOperationAction(ISD::FREM , MVT::f32, Expand);
367   setOperationAction(ISD::FPOW , MVT::f32, Expand);
368   if (Subtarget.hasSPE()) {
369     setOperationAction(ISD::FMA  , MVT::f64, Expand);
370     setOperationAction(ISD::FMA  , MVT::f32, Expand);
371   } else {
372     setOperationAction(ISD::FMA  , MVT::f64, Legal);
373     setOperationAction(ISD::FMA  , MVT::f32, Legal);
374   }
375 
376   if (Subtarget.hasSPE())
377     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
378 
379   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
380 
381   // If we're enabling GP optimizations, use hardware square root
382   if (!Subtarget.hasFSQRT() &&
383       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
384         Subtarget.hasFRE()))
385     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
386 
387   if (!Subtarget.hasFSQRT() &&
388       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
389         Subtarget.hasFRES()))
390     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
391 
392   if (Subtarget.hasFCPSGN()) {
393     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
394     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
395   } else {
396     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
397     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
398   }
399 
400   if (Subtarget.hasFPRND()) {
401     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
402     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
403     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
404     setOperationAction(ISD::FROUND, MVT::f64, Legal);
405 
406     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
407     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
408     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
409     setOperationAction(ISD::FROUND, MVT::f32, Legal);
410   }
411 
412   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
413   // to speed up scalar BSWAP64.
414   // CTPOP or CTTZ were introduced in P8/P9 respectively
415   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
416   if (Subtarget.hasP9Vector())
417     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
418   else
419     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
420   if (Subtarget.isISA3_0()) {
421     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
422     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
423   } else {
424     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
425     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
426   }
427 
428   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
429     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
430     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
431   } else {
432     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
433     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
434   }
435 
436   // PowerPC does not have ROTR
437   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
438   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
439 
440   if (!Subtarget.useCRBits()) {
441     // PowerPC does not have Select
442     setOperationAction(ISD::SELECT, MVT::i32, Expand);
443     setOperationAction(ISD::SELECT, MVT::i64, Expand);
444     setOperationAction(ISD::SELECT, MVT::f32, Expand);
445     setOperationAction(ISD::SELECT, MVT::f64, Expand);
446   }
447 
448   // PowerPC wants to turn select_cc of FP into fsel when possible.
449   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
450   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
451 
452   // PowerPC wants to optimize integer setcc a bit
453   if (!Subtarget.useCRBits())
454     setOperationAction(ISD::SETCC, MVT::i32, Custom);
455 
456   if (Subtarget.hasFPU()) {
457     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
458     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
459     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
460 
461     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
462     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
463     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
464   }
465 
466   // PowerPC does not have BRCOND which requires SetCC
467   if (!Subtarget.useCRBits())
468     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
469 
470   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
471 
472   if (Subtarget.hasSPE()) {
473     // SPE has built-in conversions
474     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
475     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
476     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
477     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
478     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
479     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
480   } else {
481     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
482     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
483     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
484 
485     // PowerPC does not have [U|S]INT_TO_FP
486     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
487     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
488     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
489     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
490   }
491 
492   if (Subtarget.hasDirectMove() && isPPC64) {
493     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
494     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
495     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
496     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
497     if (TM.Options.UnsafeFPMath) {
498       setOperationAction(ISD::LRINT, MVT::f64, Legal);
499       setOperationAction(ISD::LRINT, MVT::f32, Legal);
500       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
501       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
502       setOperationAction(ISD::LROUND, MVT::f64, Legal);
503       setOperationAction(ISD::LROUND, MVT::f32, Legal);
504       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
505       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
506     }
507   } else {
508     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
509     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
510     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
511     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
512   }
513 
514   // We cannot sextinreg(i1).  Expand to shifts.
515   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
516 
517   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
518   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
519   // support continuation, user-level threading, and etc.. As a result, no
520   // other SjLj exception interfaces are implemented and please don't build
521   // your own exception handling based on them.
522   // LLVM/Clang supports zero-cost DWARF exception handling.
523   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
524   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
525 
526   // We want to legalize GlobalAddress and ConstantPool nodes into the
527   // appropriate instructions to materialize the address.
528   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
529   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
530   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
531   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
532   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
533   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
534   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
535   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
536   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
537   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
538 
539   // TRAP is legal.
540   setOperationAction(ISD::TRAP, MVT::Other, Legal);
541 
542   // TRAMPOLINE is custom lowered.
543   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
544   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
545 
546   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
547   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
548 
549   if (Subtarget.is64BitELFABI()) {
550     // VAARG always uses double-word chunks, so promote anything smaller.
551     setOperationAction(ISD::VAARG, MVT::i1, Promote);
552     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
553     setOperationAction(ISD::VAARG, MVT::i8, Promote);
554     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
555     setOperationAction(ISD::VAARG, MVT::i16, Promote);
556     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
557     setOperationAction(ISD::VAARG, MVT::i32, Promote);
558     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
559     setOperationAction(ISD::VAARG, MVT::Other, Expand);
560   } else if (Subtarget.is32BitELFABI()) {
561     // VAARG is custom lowered with the 32-bit SVR4 ABI.
562     setOperationAction(ISD::VAARG, MVT::Other, Custom);
563     setOperationAction(ISD::VAARG, MVT::i64, Custom);
564   } else
565     setOperationAction(ISD::VAARG, MVT::Other, Expand);
566 
567   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
568   if (Subtarget.is32BitELFABI())
569     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
570   else
571     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
572 
573   // Use the default implementation.
574   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
575   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
576   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
577   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
578   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
579   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
580   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
581   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
582   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
583 
584   // We want to custom lower some of our intrinsics.
585   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
586 
587   // To handle counter-based loop conditions.
588   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
589 
590   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
591   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
592   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
593   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
594 
595   // Comparisons that require checking two conditions.
596   if (Subtarget.hasSPE()) {
597     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
598     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
599     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
600     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
601   }
602   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
603   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
604   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
605   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
606   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
607   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
608   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
609   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
610   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
611   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
612   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
613   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
614 
615   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
616   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
617 
618   if (Subtarget.has64BitSupport()) {
619     // They also have instructions for converting between i64 and fp.
620     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
621     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
622     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
623     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
624     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
625     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
626     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
627     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
628     // This is just the low 32 bits of a (signed) fp->i64 conversion.
629     // We cannot do this with Promote because i64 is not a legal type.
630     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
631     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
632 
633     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
634       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
635       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
636     }
637   } else {
638     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
639     if (Subtarget.hasSPE()) {
640       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
641       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
642     } else {
643       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
644       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
645     }
646   }
647 
648   // With the instructions enabled under FPCVT, we can do everything.
649   if (Subtarget.hasFPCVT()) {
650     if (Subtarget.has64BitSupport()) {
651       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
652       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
653       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
654       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
655       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
656       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
657       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
658       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
659     }
660 
661     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
662     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
663     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
664     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
665     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
666     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
667     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
668     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
669   }
670 
671   if (Subtarget.use64BitRegs()) {
672     // 64-bit PowerPC implementations can support i64 types directly
673     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
674     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
675     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
676     // 64-bit PowerPC wants to expand i128 shifts itself.
677     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
678     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
679     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
680   } else {
681     // 32-bit PowerPC wants to expand i64 shifts itself.
682     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
683     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
684     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
685   }
686 
687   // PowerPC has better expansions for funnel shifts than the generic
688   // TargetLowering::expandFunnelShift.
689   if (Subtarget.has64BitSupport()) {
690     setOperationAction(ISD::FSHL, MVT::i64, Custom);
691     setOperationAction(ISD::FSHR, MVT::i64, Custom);
692   }
693   setOperationAction(ISD::FSHL, MVT::i32, Custom);
694   setOperationAction(ISD::FSHR, MVT::i32, Custom);
695 
696   if (Subtarget.hasVSX()) {
697     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
698     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
699     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
700     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
701   }
702 
703   if (Subtarget.hasAltivec()) {
704     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
705       setOperationAction(ISD::SADDSAT, VT, Legal);
706       setOperationAction(ISD::SSUBSAT, VT, Legal);
707       setOperationAction(ISD::UADDSAT, VT, Legal);
708       setOperationAction(ISD::USUBSAT, VT, Legal);
709     }
710     // First set operation action for all vector types to expand. Then we
711     // will selectively turn on ones that can be effectively codegen'd.
712     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
713       // add/sub are legal for all supported vector VT's.
714       setOperationAction(ISD::ADD, VT, Legal);
715       setOperationAction(ISD::SUB, VT, Legal);
716 
717       // For v2i64, these are only valid with P8Vector. This is corrected after
718       // the loop.
719       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
720         setOperationAction(ISD::SMAX, VT, Legal);
721         setOperationAction(ISD::SMIN, VT, Legal);
722         setOperationAction(ISD::UMAX, VT, Legal);
723         setOperationAction(ISD::UMIN, VT, Legal);
724       }
725       else {
726         setOperationAction(ISD::SMAX, VT, Expand);
727         setOperationAction(ISD::SMIN, VT, Expand);
728         setOperationAction(ISD::UMAX, VT, Expand);
729         setOperationAction(ISD::UMIN, VT, Expand);
730       }
731 
732       if (Subtarget.hasVSX()) {
733         setOperationAction(ISD::FMAXNUM, VT, Legal);
734         setOperationAction(ISD::FMINNUM, VT, Legal);
735       }
736 
737       // Vector instructions introduced in P8
738       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
739         setOperationAction(ISD::CTPOP, VT, Legal);
740         setOperationAction(ISD::CTLZ, VT, Legal);
741       }
742       else {
743         setOperationAction(ISD::CTPOP, VT, Expand);
744         setOperationAction(ISD::CTLZ, VT, Expand);
745       }
746 
747       // Vector instructions introduced in P9
748       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
749         setOperationAction(ISD::CTTZ, VT, Legal);
750       else
751         setOperationAction(ISD::CTTZ, VT, Expand);
752 
753       // We promote all shuffles to v16i8.
754       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
755       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
756 
757       // We promote all non-typed operations to v4i32.
758       setOperationAction(ISD::AND   , VT, Promote);
759       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
760       setOperationAction(ISD::OR    , VT, Promote);
761       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
762       setOperationAction(ISD::XOR   , VT, Promote);
763       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
764       setOperationAction(ISD::LOAD  , VT, Promote);
765       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
766       setOperationAction(ISD::SELECT, VT, Promote);
767       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
768       setOperationAction(ISD::VSELECT, VT, Legal);
769       setOperationAction(ISD::SELECT_CC, VT, Promote);
770       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
771       setOperationAction(ISD::STORE, VT, Promote);
772       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
773 
774       // No other operations are legal.
775       setOperationAction(ISD::MUL , VT, Expand);
776       setOperationAction(ISD::SDIV, VT, Expand);
777       setOperationAction(ISD::SREM, VT, Expand);
778       setOperationAction(ISD::UDIV, VT, Expand);
779       setOperationAction(ISD::UREM, VT, Expand);
780       setOperationAction(ISD::FDIV, VT, Expand);
781       setOperationAction(ISD::FREM, VT, Expand);
782       setOperationAction(ISD::FNEG, VT, Expand);
783       setOperationAction(ISD::FSQRT, VT, Expand);
784       setOperationAction(ISD::FLOG, VT, Expand);
785       setOperationAction(ISD::FLOG10, VT, Expand);
786       setOperationAction(ISD::FLOG2, VT, Expand);
787       setOperationAction(ISD::FEXP, VT, Expand);
788       setOperationAction(ISD::FEXP2, VT, Expand);
789       setOperationAction(ISD::FSIN, VT, Expand);
790       setOperationAction(ISD::FCOS, VT, Expand);
791       setOperationAction(ISD::FABS, VT, Expand);
792       setOperationAction(ISD::FFLOOR, VT, Expand);
793       setOperationAction(ISD::FCEIL,  VT, Expand);
794       setOperationAction(ISD::FTRUNC, VT, Expand);
795       setOperationAction(ISD::FRINT,  VT, Expand);
796       setOperationAction(ISD::FNEARBYINT, VT, Expand);
797       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
798       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
799       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
800       setOperationAction(ISD::MULHU, VT, Expand);
801       setOperationAction(ISD::MULHS, VT, Expand);
802       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
803       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
804       setOperationAction(ISD::UDIVREM, VT, Expand);
805       setOperationAction(ISD::SDIVREM, VT, Expand);
806       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
807       setOperationAction(ISD::FPOW, VT, Expand);
808       setOperationAction(ISD::BSWAP, VT, Expand);
809       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
810       setOperationAction(ISD::ROTL, VT, Expand);
811       setOperationAction(ISD::ROTR, VT, Expand);
812 
813       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
814         setTruncStoreAction(VT, InnerVT, Expand);
815         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
816         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
817         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
818       }
819     }
820     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
821     if (!Subtarget.hasP8Vector()) {
822       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
823       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
824       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
825       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
826     }
827 
828     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
829     // with merges, splats, etc.
830     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
831 
832     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
833     // are cheap, so handle them before they get expanded to scalar.
834     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
835     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
836     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
837     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
838     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
839 
840     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
841     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
842     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
843     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
844     setOperationAction(ISD::SELECT, MVT::v4i32,
845                        Subtarget.useCRBits() ? Legal : Expand);
846     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
847     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
848     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
849     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
850     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
851     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
852     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
853     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
854     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
855     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
856     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
857     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
858     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
859 
860     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
861     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
862     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
863     if (Subtarget.hasAltivec())
864       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
865         setOperationAction(ISD::ROTL, VT, Legal);
866     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
867     if (Subtarget.hasP8Altivec())
868       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
869 
870     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
871     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
872     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
873     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
874 
875     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
876     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
877 
878     if (Subtarget.hasVSX()) {
879       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
880       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
881     }
882 
883     if (Subtarget.hasP8Altivec())
884       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
885     else
886       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
887 
888     if (Subtarget.isISA3_1()) {
889       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
890       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
891       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
892       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
893       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
894       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
895       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
896       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
897       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
898       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
899       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
900       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
901       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
902       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
903       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
904       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
905       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
906       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
907     }
908 
909     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
910     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
911 
912     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
913     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
914 
915     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
916     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
917     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
918     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
919 
920     // Altivec does not contain unordered floating-point compare instructions
921     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
922     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
923     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
924     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
925 
926     if (Subtarget.hasVSX()) {
927       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
928       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
929       if (Subtarget.hasP8Vector()) {
930         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
931         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
932       }
933       if (Subtarget.hasDirectMove() && isPPC64) {
934         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
935         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
936         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
937         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
938         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
939         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
940         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
941         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
942       }
943       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
944 
945       // The nearbyint variants are not allowed to raise the inexact exception
946       // so we can only code-gen them with unsafe math.
947       if (TM.Options.UnsafeFPMath) {
948         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
949         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
950       }
951 
952       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
953       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
954       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
955       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
956       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
957       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
958       setOperationAction(ISD::FROUND, MVT::f64, Legal);
959       setOperationAction(ISD::FRINT, MVT::f64, Legal);
960 
961       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
962       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
963       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
964       setOperationAction(ISD::FROUND, MVT::f32, Legal);
965       setOperationAction(ISD::FRINT, MVT::f32, Legal);
966 
967       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
968       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
969 
970       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
971       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
972 
973       // Share the Altivec comparison restrictions.
974       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
975       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
976       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
977       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
978 
979       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
980       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
981 
982       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
983 
984       if (Subtarget.hasP8Vector())
985         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
986 
987       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
988 
989       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
990       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
991       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
992 
993       if (Subtarget.hasP8Altivec()) {
994         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
995         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
996         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
997 
998         // 128 bit shifts can be accomplished via 3 instructions for SHL and
999         // SRL, but not for SRA because of the instructions available:
1000         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1001         // doing
1002         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1003         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1004         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1005 
1006         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1007       }
1008       else {
1009         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1010         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1011         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1012 
1013         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1014 
1015         // VSX v2i64 only supports non-arithmetic operations.
1016         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1017         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1018       }
1019 
1020       if (Subtarget.isISA3_1())
1021         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1022       else
1023         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1024 
1025       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1026       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1027       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1028       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1029 
1030       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1031 
1032       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1033       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1034       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1035       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1036       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1037       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1038       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1039       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1040 
1041       // Custom handling for partial vectors of integers converted to
1042       // floating point. We already have optimal handling for v2i32 through
1043       // the DAG combine, so those aren't necessary.
1044       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1045       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1046       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1047       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1048       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1049       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1050       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1051       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1052       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1053       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1054       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1055       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1056       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1057       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1058       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1059       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1060 
1061       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1062       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1063       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1064       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1065       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1066       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1067 
1068       if (Subtarget.hasDirectMove())
1069         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1070       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1071 
1072       // Handle constrained floating-point operations of vector.
1073       // The predictor is `hasVSX` because altivec instruction has
1074       // no exception but VSX vector instruction has.
1075       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1076       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1077       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1078       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1079       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1080       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1081       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1082       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1083       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1084       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1085       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1086       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1087       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1088 
1089       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1090       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1091       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1092       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1093       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1094       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1095       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1096       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1097       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1098       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1099       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1100       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1101       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1102 
1103       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1104     }
1105 
1106     if (Subtarget.hasP8Altivec()) {
1107       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1108       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1109     }
1110 
1111     if (Subtarget.hasP9Vector()) {
1112       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1113       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1114 
1115       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1116       // SRL, but not for SRA because of the instructions available:
1117       // VS{RL} and VS{RL}O.
1118       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1119       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1120       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1121 
1122       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1123       setOperationAction(ISD::FADD, MVT::f128, Legal);
1124       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1125       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1126       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1127       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1128       // No extending loads to f128 on PPC.
1129       for (MVT FPT : MVT::fp_valuetypes())
1130         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1131       setOperationAction(ISD::FMA, MVT::f128, Legal);
1132       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1133       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1134       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1135       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1136       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1137       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1138 
1139       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1140       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1141       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1142       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1143       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1144       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1145 
1146       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1147       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1148       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1149       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1150       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1151       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1152       // No implementation for these ops for PowerPC.
1153       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1154       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1155       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1156       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1157       setOperationAction(ISD::FREM, MVT::f128, Expand);
1158 
1159       // Handle constrained floating-point operations of fp128
1160       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1161       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1162       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1163       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1164       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1165       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1166       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1167       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1168       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1169       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1170       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1171       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1172       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1173       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1174       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1175       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1176       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1177       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1178       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1179       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1180     } else if (Subtarget.hasAltivec() && EnableSoftFP128) {
1181       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1182 
1183       for (MVT FPT : MVT::fp_valuetypes())
1184         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1185 
1186       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1187       setOperationAction(ISD::STORE, MVT::f128, Promote);
1188 
1189       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1190       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1191 
1192       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1193       // fp_to_uint and int_to_fp.
1194       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1195       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1196 
1197       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1198       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1199       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1200       setOperationAction(ISD::FABS, MVT::f128, Expand);
1201       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1202       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1203       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1204       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1205       setOperationAction(ISD::FREM, MVT::f128, Expand);
1206       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1207       setOperationAction(ISD::FMA, MVT::f128, Expand);
1208       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1209 
1210       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1211       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1212 
1213       // Expand the fp_extend if the target type is fp128.
1214       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1215       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1216 
1217       // Expand the fp_round if the source type is fp128.
1218       for (MVT VT : {MVT::f32, MVT::f64}) {
1219         setOperationAction(ISD::FP_ROUND, VT, Custom);
1220         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1221       }
1222     }
1223 
1224     if (Subtarget.hasP9Altivec()) {
1225       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1226       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1227 
1228       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1229       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1230       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1231       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1232       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1233       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1234       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1235     }
1236 
1237     if (Subtarget.isISA3_1()) {
1238       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1239       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1240     }
1241   }
1242 
1243   if (Subtarget.pairedVectorMemops()) {
1244     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1245     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1246     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1247   }
1248   if (Subtarget.hasMMA()) {
1249     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1250     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1251     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1252     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1253   }
1254 
1255   if (Subtarget.has64BitSupport())
1256     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1257 
1258   if (Subtarget.isISA3_1())
1259     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1260 
1261   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1262 
1263   if (!isPPC64) {
1264     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1265     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1266   }
1267 
1268   setBooleanContents(ZeroOrOneBooleanContent);
1269 
1270   if (Subtarget.hasAltivec()) {
1271     // Altivec instructions set fields to all zeros or all ones.
1272     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1273   }
1274 
1275   if (!isPPC64) {
1276     // These libcalls are not available in 32-bit.
1277     setLibcallName(RTLIB::SHL_I128, nullptr);
1278     setLibcallName(RTLIB::SRL_I128, nullptr);
1279     setLibcallName(RTLIB::SRA_I128, nullptr);
1280   }
1281 
1282   if (!isPPC64)
1283     setMaxAtomicSizeInBitsSupported(32);
1284 
1285   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1286 
1287   // We have target-specific dag combine patterns for the following nodes:
1288   setTargetDAGCombine(ISD::ADD);
1289   setTargetDAGCombine(ISD::SHL);
1290   setTargetDAGCombine(ISD::SRA);
1291   setTargetDAGCombine(ISD::SRL);
1292   setTargetDAGCombine(ISD::MUL);
1293   setTargetDAGCombine(ISD::FMA);
1294   setTargetDAGCombine(ISD::SINT_TO_FP);
1295   setTargetDAGCombine(ISD::BUILD_VECTOR);
1296   if (Subtarget.hasFPCVT())
1297     setTargetDAGCombine(ISD::UINT_TO_FP);
1298   setTargetDAGCombine(ISD::LOAD);
1299   setTargetDAGCombine(ISD::STORE);
1300   setTargetDAGCombine(ISD::BR_CC);
1301   if (Subtarget.useCRBits())
1302     setTargetDAGCombine(ISD::BRCOND);
1303   setTargetDAGCombine(ISD::BSWAP);
1304   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1305   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1306   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1307 
1308   setTargetDAGCombine(ISD::SIGN_EXTEND);
1309   setTargetDAGCombine(ISD::ZERO_EXTEND);
1310   setTargetDAGCombine(ISD::ANY_EXTEND);
1311 
1312   setTargetDAGCombine(ISD::TRUNCATE);
1313   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1314 
1315 
1316   if (Subtarget.useCRBits()) {
1317     setTargetDAGCombine(ISD::TRUNCATE);
1318     setTargetDAGCombine(ISD::SETCC);
1319     setTargetDAGCombine(ISD::SELECT_CC);
1320   }
1321 
1322   if (Subtarget.hasP9Altivec()) {
1323     setTargetDAGCombine(ISD::ABS);
1324     setTargetDAGCombine(ISD::VSELECT);
1325   }
1326 
1327   setLibcallName(RTLIB::LOG_F128, "logf128");
1328   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1329   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1330   setLibcallName(RTLIB::EXP_F128, "expf128");
1331   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1332   setLibcallName(RTLIB::SIN_F128, "sinf128");
1333   setLibcallName(RTLIB::COS_F128, "cosf128");
1334   setLibcallName(RTLIB::POW_F128, "powf128");
1335   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1336   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1337   setLibcallName(RTLIB::REM_F128, "fmodf128");
1338   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1339   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1340   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1341   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1342   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1343   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1344   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1345   setLibcallName(RTLIB::RINT_F128, "rintf128");
1346   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1347   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1348   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1349   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1350 
1351   // With 32 condition bits, we don't need to sink (and duplicate) compares
1352   // aggressively in CodeGenPrep.
1353   if (Subtarget.useCRBits()) {
1354     setHasMultipleConditionRegisters();
1355     setJumpIsExpensive();
1356   }
1357 
1358   setMinFunctionAlignment(Align(4));
1359 
1360   switch (Subtarget.getCPUDirective()) {
1361   default: break;
1362   case PPC::DIR_970:
1363   case PPC::DIR_A2:
1364   case PPC::DIR_E500:
1365   case PPC::DIR_E500mc:
1366   case PPC::DIR_E5500:
1367   case PPC::DIR_PWR4:
1368   case PPC::DIR_PWR5:
1369   case PPC::DIR_PWR5X:
1370   case PPC::DIR_PWR6:
1371   case PPC::DIR_PWR6X:
1372   case PPC::DIR_PWR7:
1373   case PPC::DIR_PWR8:
1374   case PPC::DIR_PWR9:
1375   case PPC::DIR_PWR10:
1376   case PPC::DIR_PWR_FUTURE:
1377     setPrefLoopAlignment(Align(16));
1378     setPrefFunctionAlignment(Align(16));
1379     break;
1380   }
1381 
1382   if (Subtarget.enableMachineScheduler())
1383     setSchedulingPreference(Sched::Source);
1384   else
1385     setSchedulingPreference(Sched::Hybrid);
1386 
1387   computeRegisterProperties(STI.getRegisterInfo());
1388 
1389   // The Freescale cores do better with aggressive inlining of memcpy and
1390   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1391   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1392       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1393     MaxStoresPerMemset = 32;
1394     MaxStoresPerMemsetOptSize = 16;
1395     MaxStoresPerMemcpy = 32;
1396     MaxStoresPerMemcpyOptSize = 8;
1397     MaxStoresPerMemmove = 32;
1398     MaxStoresPerMemmoveOptSize = 8;
1399   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1400     // The A2 also benefits from (very) aggressive inlining of memcpy and
1401     // friends. The overhead of a the function call, even when warm, can be
1402     // over one hundred cycles.
1403     MaxStoresPerMemset = 128;
1404     MaxStoresPerMemcpy = 128;
1405     MaxStoresPerMemmove = 128;
1406     MaxLoadsPerMemcmp = 128;
1407   } else {
1408     MaxLoadsPerMemcmp = 8;
1409     MaxLoadsPerMemcmpOptSize = 4;
1410   }
1411 
1412   IsStrictFPEnabled = true;
1413 
1414   // Let the subtarget (CPU) decide if a predictable select is more expensive
1415   // than the corresponding branch. This information is used in CGP to decide
1416   // when to convert selects into branches.
1417   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1418 }
1419 
1420 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1421 /// the desired ByVal argument alignment.
1422 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1423   if (MaxAlign == MaxMaxAlign)
1424     return;
1425   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1426     if (MaxMaxAlign >= 32 &&
1427         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1428       MaxAlign = Align(32);
1429     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1430              MaxAlign < 16)
1431       MaxAlign = Align(16);
1432   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1433     Align EltAlign;
1434     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1435     if (EltAlign > MaxAlign)
1436       MaxAlign = EltAlign;
1437   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1438     for (auto *EltTy : STy->elements()) {
1439       Align EltAlign;
1440       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1441       if (EltAlign > MaxAlign)
1442         MaxAlign = EltAlign;
1443       if (MaxAlign == MaxMaxAlign)
1444         break;
1445     }
1446   }
1447 }
1448 
1449 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1450 /// function arguments in the caller parameter area.
1451 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1452                                                   const DataLayout &DL) const {
1453   // 16byte and wider vectors are passed on 16byte boundary.
1454   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1455   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1456   if (Subtarget.hasAltivec())
1457     getMaxByValAlign(Ty, Alignment, Align(16));
1458   return Alignment.value();
1459 }
1460 
1461 bool PPCTargetLowering::useSoftFloat() const {
1462   return Subtarget.useSoftFloat();
1463 }
1464 
1465 bool PPCTargetLowering::hasSPE() const {
1466   return Subtarget.hasSPE();
1467 }
1468 
1469 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1470   return VT.isScalarInteger();
1471 }
1472 
1473 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1474   switch ((PPCISD::NodeType)Opcode) {
1475   case PPCISD::FIRST_NUMBER:    break;
1476   case PPCISD::FSEL:            return "PPCISD::FSEL";
1477   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1478   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1479   case PPCISD::FCFID:           return "PPCISD::FCFID";
1480   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1481   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1482   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1483   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1484   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1485   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1486   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1487   case PPCISD::FP_TO_UINT_IN_VSR:
1488                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1489   case PPCISD::FP_TO_SINT_IN_VSR:
1490                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1491   case PPCISD::FRE:             return "PPCISD::FRE";
1492   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1493   case PPCISD::FTSQRT:
1494     return "PPCISD::FTSQRT";
1495   case PPCISD::FSQRT:
1496     return "PPCISD::FSQRT";
1497   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1498   case PPCISD::VPERM:           return "PPCISD::VPERM";
1499   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1500   case PPCISD::XXSPLTI_SP_TO_DP:
1501     return "PPCISD::XXSPLTI_SP_TO_DP";
1502   case PPCISD::XXSPLTI32DX:
1503     return "PPCISD::XXSPLTI32DX";
1504   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1505   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1506   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1507   case PPCISD::CMPB:            return "PPCISD::CMPB";
1508   case PPCISD::Hi:              return "PPCISD::Hi";
1509   case PPCISD::Lo:              return "PPCISD::Lo";
1510   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1511   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1512   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1513   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1514   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1515   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1516   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1517   case PPCISD::SRL:             return "PPCISD::SRL";
1518   case PPCISD::SRA:             return "PPCISD::SRA";
1519   case PPCISD::SHL:             return "PPCISD::SHL";
1520   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1521   case PPCISD::CALL:            return "PPCISD::CALL";
1522   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1523   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1524   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1525   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1526   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1527   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1528   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1529   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1530   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1531   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1532   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1533   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1534   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1535   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1536   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1537   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1538     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1539   case PPCISD::ANDI_rec_1_EQ_BIT:
1540     return "PPCISD::ANDI_rec_1_EQ_BIT";
1541   case PPCISD::ANDI_rec_1_GT_BIT:
1542     return "PPCISD::ANDI_rec_1_GT_BIT";
1543   case PPCISD::VCMP:            return "PPCISD::VCMP";
1544   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1545   case PPCISD::LBRX:            return "PPCISD::LBRX";
1546   case PPCISD::STBRX:           return "PPCISD::STBRX";
1547   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1548   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1549   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1550   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1551   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1552   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1553   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1554   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1555   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1556   case PPCISD::ST_VSR_SCAL_INT:
1557                                 return "PPCISD::ST_VSR_SCAL_INT";
1558   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1559   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1560   case PPCISD::BDZ:             return "PPCISD::BDZ";
1561   case PPCISD::MFFS:            return "PPCISD::MFFS";
1562   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1563   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1564   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1565   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1566   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1567   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1568   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1569   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1570   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1571   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1572   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1573   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1574   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1575   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1576   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1577   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1578   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1579   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1580   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1581   case PPCISD::PADDI_DTPREL:
1582     return "PPCISD::PADDI_DTPREL";
1583   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1584   case PPCISD::SC:              return "PPCISD::SC";
1585   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1586   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1587   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1588   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1589   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1590   case PPCISD::VABSD:           return "PPCISD::VABSD";
1591   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1592   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1593   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1594   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1595   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1596   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1597   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1598   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1599     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1600   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1601     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1602   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1603   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1604   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1605   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1606   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1607   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1608   case PPCISD::STRICT_FADDRTZ:
1609     return "PPCISD::STRICT_FADDRTZ";
1610   case PPCISD::STRICT_FCTIDZ:
1611     return "PPCISD::STRICT_FCTIDZ";
1612   case PPCISD::STRICT_FCTIWZ:
1613     return "PPCISD::STRICT_FCTIWZ";
1614   case PPCISD::STRICT_FCTIDUZ:
1615     return "PPCISD::STRICT_FCTIDUZ";
1616   case PPCISD::STRICT_FCTIWUZ:
1617     return "PPCISD::STRICT_FCTIWUZ";
1618   case PPCISD::STRICT_FCFID:
1619     return "PPCISD::STRICT_FCFID";
1620   case PPCISD::STRICT_FCFIDU:
1621     return "PPCISD::STRICT_FCFIDU";
1622   case PPCISD::STRICT_FCFIDS:
1623     return "PPCISD::STRICT_FCFIDS";
1624   case PPCISD::STRICT_FCFIDUS:
1625     return "PPCISD::STRICT_FCFIDUS";
1626   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1627   }
1628   return nullptr;
1629 }
1630 
1631 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1632                                           EVT VT) const {
1633   if (!VT.isVector())
1634     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1635 
1636   return VT.changeVectorElementTypeToInteger();
1637 }
1638 
1639 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1640   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1641   return true;
1642 }
1643 
1644 //===----------------------------------------------------------------------===//
1645 // Node matching predicates, for use by the tblgen matching code.
1646 //===----------------------------------------------------------------------===//
1647 
1648 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1649 static bool isFloatingPointZero(SDValue Op) {
1650   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1651     return CFP->getValueAPF().isZero();
1652   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1653     // Maybe this has already been legalized into the constant pool?
1654     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1655       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1656         return CFP->getValueAPF().isZero();
1657   }
1658   return false;
1659 }
1660 
1661 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1662 /// true if Op is undef or if it matches the specified value.
1663 static bool isConstantOrUndef(int Op, int Val) {
1664   return Op < 0 || Op == Val;
1665 }
1666 
1667 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1668 /// VPKUHUM instruction.
1669 /// The ShuffleKind distinguishes between big-endian operations with
1670 /// two different inputs (0), either-endian operations with two identical
1671 /// inputs (1), and little-endian operations with two different inputs (2).
1672 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1673 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1674                                SelectionDAG &DAG) {
1675   bool IsLE = DAG.getDataLayout().isLittleEndian();
1676   if (ShuffleKind == 0) {
1677     if (IsLE)
1678       return false;
1679     for (unsigned i = 0; i != 16; ++i)
1680       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1681         return false;
1682   } else if (ShuffleKind == 2) {
1683     if (!IsLE)
1684       return false;
1685     for (unsigned i = 0; i != 16; ++i)
1686       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1687         return false;
1688   } else if (ShuffleKind == 1) {
1689     unsigned j = IsLE ? 0 : 1;
1690     for (unsigned i = 0; i != 8; ++i)
1691       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1692           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1693         return false;
1694   }
1695   return true;
1696 }
1697 
1698 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1699 /// VPKUWUM instruction.
1700 /// The ShuffleKind distinguishes between big-endian operations with
1701 /// two different inputs (0), either-endian operations with two identical
1702 /// inputs (1), and little-endian operations with two different inputs (2).
1703 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1704 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1705                                SelectionDAG &DAG) {
1706   bool IsLE = DAG.getDataLayout().isLittleEndian();
1707   if (ShuffleKind == 0) {
1708     if (IsLE)
1709       return false;
1710     for (unsigned i = 0; i != 16; i += 2)
1711       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1712           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1713         return false;
1714   } else if (ShuffleKind == 2) {
1715     if (!IsLE)
1716       return false;
1717     for (unsigned i = 0; i != 16; i += 2)
1718       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1719           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1720         return false;
1721   } else if (ShuffleKind == 1) {
1722     unsigned j = IsLE ? 0 : 2;
1723     for (unsigned i = 0; i != 8; i += 2)
1724       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1725           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1726           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1727           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1728         return false;
1729   }
1730   return true;
1731 }
1732 
1733 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1734 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1735 /// current subtarget.
1736 ///
1737 /// The ShuffleKind distinguishes between big-endian operations with
1738 /// two different inputs (0), either-endian operations with two identical
1739 /// inputs (1), and little-endian operations with two different inputs (2).
1740 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1741 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1742                                SelectionDAG &DAG) {
1743   const PPCSubtarget& Subtarget =
1744       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1745   if (!Subtarget.hasP8Vector())
1746     return false;
1747 
1748   bool IsLE = DAG.getDataLayout().isLittleEndian();
1749   if (ShuffleKind == 0) {
1750     if (IsLE)
1751       return false;
1752     for (unsigned i = 0; i != 16; i += 4)
1753       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1754           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1755           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1756           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1757         return false;
1758   } else if (ShuffleKind == 2) {
1759     if (!IsLE)
1760       return false;
1761     for (unsigned i = 0; i != 16; i += 4)
1762       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1763           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1764           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1765           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1766         return false;
1767   } else if (ShuffleKind == 1) {
1768     unsigned j = IsLE ? 0 : 4;
1769     for (unsigned i = 0; i != 8; i += 4)
1770       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1771           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1772           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1773           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1774           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1775           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1776           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1777           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1778         return false;
1779   }
1780   return true;
1781 }
1782 
1783 /// isVMerge - Common function, used to match vmrg* shuffles.
1784 ///
1785 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1786                      unsigned LHSStart, unsigned RHSStart) {
1787   if (N->getValueType(0) != MVT::v16i8)
1788     return false;
1789   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1790          "Unsupported merge size!");
1791 
1792   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1793     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1794       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1795                              LHSStart+j+i*UnitSize) ||
1796           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1797                              RHSStart+j+i*UnitSize))
1798         return false;
1799     }
1800   return true;
1801 }
1802 
1803 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1804 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1805 /// The ShuffleKind distinguishes between big-endian merges with two
1806 /// different inputs (0), either-endian merges with two identical inputs (1),
1807 /// and little-endian merges with two different inputs (2).  For the latter,
1808 /// the input operands are swapped (see PPCInstrAltivec.td).
1809 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1810                              unsigned ShuffleKind, SelectionDAG &DAG) {
1811   if (DAG.getDataLayout().isLittleEndian()) {
1812     if (ShuffleKind == 1) // unary
1813       return isVMerge(N, UnitSize, 0, 0);
1814     else if (ShuffleKind == 2) // swapped
1815       return isVMerge(N, UnitSize, 0, 16);
1816     else
1817       return false;
1818   } else {
1819     if (ShuffleKind == 1) // unary
1820       return isVMerge(N, UnitSize, 8, 8);
1821     else if (ShuffleKind == 0) // normal
1822       return isVMerge(N, UnitSize, 8, 24);
1823     else
1824       return false;
1825   }
1826 }
1827 
1828 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1829 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1830 /// The ShuffleKind distinguishes between big-endian merges with two
1831 /// different inputs (0), either-endian merges with two identical inputs (1),
1832 /// and little-endian merges with two different inputs (2).  For the latter,
1833 /// the input operands are swapped (see PPCInstrAltivec.td).
1834 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1835                              unsigned ShuffleKind, SelectionDAG &DAG) {
1836   if (DAG.getDataLayout().isLittleEndian()) {
1837     if (ShuffleKind == 1) // unary
1838       return isVMerge(N, UnitSize, 8, 8);
1839     else if (ShuffleKind == 2) // swapped
1840       return isVMerge(N, UnitSize, 8, 24);
1841     else
1842       return false;
1843   } else {
1844     if (ShuffleKind == 1) // unary
1845       return isVMerge(N, UnitSize, 0, 0);
1846     else if (ShuffleKind == 0) // normal
1847       return isVMerge(N, UnitSize, 0, 16);
1848     else
1849       return false;
1850   }
1851 }
1852 
1853 /**
1854  * Common function used to match vmrgew and vmrgow shuffles
1855  *
1856  * The indexOffset determines whether to look for even or odd words in
1857  * the shuffle mask. This is based on the of the endianness of the target
1858  * machine.
1859  *   - Little Endian:
1860  *     - Use offset of 0 to check for odd elements
1861  *     - Use offset of 4 to check for even elements
1862  *   - Big Endian:
1863  *     - Use offset of 0 to check for even elements
1864  *     - Use offset of 4 to check for odd elements
1865  * A detailed description of the vector element ordering for little endian and
1866  * big endian can be found at
1867  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1868  * Targeting your applications - what little endian and big endian IBM XL C/C++
1869  * compiler differences mean to you
1870  *
1871  * The mask to the shuffle vector instruction specifies the indices of the
1872  * elements from the two input vectors to place in the result. The elements are
1873  * numbered in array-access order, starting with the first vector. These vectors
1874  * are always of type v16i8, thus each vector will contain 16 elements of size
1875  * 8. More info on the shuffle vector can be found in the
1876  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1877  * Language Reference.
1878  *
1879  * The RHSStartValue indicates whether the same input vectors are used (unary)
1880  * or two different input vectors are used, based on the following:
1881  *   - If the instruction uses the same vector for both inputs, the range of the
1882  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1883  *     be 0.
1884  *   - If the instruction has two different vectors then the range of the
1885  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1886  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1887  *     to 31 specify elements in the second vector).
1888  *
1889  * \param[in] N The shuffle vector SD Node to analyze
1890  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1891  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1892  * vector to the shuffle_vector instruction
1893  * \return true iff this shuffle vector represents an even or odd word merge
1894  */
1895 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1896                      unsigned RHSStartValue) {
1897   if (N->getValueType(0) != MVT::v16i8)
1898     return false;
1899 
1900   for (unsigned i = 0; i < 2; ++i)
1901     for (unsigned j = 0; j < 4; ++j)
1902       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1903                              i*RHSStartValue+j+IndexOffset) ||
1904           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1905                              i*RHSStartValue+j+IndexOffset+8))
1906         return false;
1907   return true;
1908 }
1909 
1910 /**
1911  * Determine if the specified shuffle mask is suitable for the vmrgew or
1912  * vmrgow instructions.
1913  *
1914  * \param[in] N The shuffle vector SD Node to analyze
1915  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1916  * \param[in] ShuffleKind Identify the type of merge:
1917  *   - 0 = big-endian merge with two different inputs;
1918  *   - 1 = either-endian merge with two identical inputs;
1919  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1920  *     little-endian merges).
1921  * \param[in] DAG The current SelectionDAG
1922  * \return true iff this shuffle mask
1923  */
1924 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1925                               unsigned ShuffleKind, SelectionDAG &DAG) {
1926   if (DAG.getDataLayout().isLittleEndian()) {
1927     unsigned indexOffset = CheckEven ? 4 : 0;
1928     if (ShuffleKind == 1) // Unary
1929       return isVMerge(N, indexOffset, 0);
1930     else if (ShuffleKind == 2) // swapped
1931       return isVMerge(N, indexOffset, 16);
1932     else
1933       return false;
1934   }
1935   else {
1936     unsigned indexOffset = CheckEven ? 0 : 4;
1937     if (ShuffleKind == 1) // Unary
1938       return isVMerge(N, indexOffset, 0);
1939     else if (ShuffleKind == 0) // Normal
1940       return isVMerge(N, indexOffset, 16);
1941     else
1942       return false;
1943   }
1944   return false;
1945 }
1946 
1947 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1948 /// amount, otherwise return -1.
1949 /// The ShuffleKind distinguishes between big-endian operations with two
1950 /// different inputs (0), either-endian operations with two identical inputs
1951 /// (1), and little-endian operations with two different inputs (2).  For the
1952 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1953 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1954                              SelectionDAG &DAG) {
1955   if (N->getValueType(0) != MVT::v16i8)
1956     return -1;
1957 
1958   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1959 
1960   // Find the first non-undef value in the shuffle mask.
1961   unsigned i;
1962   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1963     /*search*/;
1964 
1965   if (i == 16) return -1;  // all undef.
1966 
1967   // Otherwise, check to see if the rest of the elements are consecutively
1968   // numbered from this value.
1969   unsigned ShiftAmt = SVOp->getMaskElt(i);
1970   if (ShiftAmt < i) return -1;
1971 
1972   ShiftAmt -= i;
1973   bool isLE = DAG.getDataLayout().isLittleEndian();
1974 
1975   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1976     // Check the rest of the elements to see if they are consecutive.
1977     for (++i; i != 16; ++i)
1978       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1979         return -1;
1980   } else if (ShuffleKind == 1) {
1981     // Check the rest of the elements to see if they are consecutive.
1982     for (++i; i != 16; ++i)
1983       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1984         return -1;
1985   } else
1986     return -1;
1987 
1988   if (isLE)
1989     ShiftAmt = 16 - ShiftAmt;
1990 
1991   return ShiftAmt;
1992 }
1993 
1994 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1995 /// specifies a splat of a single element that is suitable for input to
1996 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1997 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1998   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1999          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2000 
2001   // The consecutive indices need to specify an element, not part of two
2002   // different elements.  So abandon ship early if this isn't the case.
2003   if (N->getMaskElt(0) % EltSize != 0)
2004     return false;
2005 
2006   // This is a splat operation if each element of the permute is the same, and
2007   // if the value doesn't reference the second vector.
2008   unsigned ElementBase = N->getMaskElt(0);
2009 
2010   // FIXME: Handle UNDEF elements too!
2011   if (ElementBase >= 16)
2012     return false;
2013 
2014   // Check that the indices are consecutive, in the case of a multi-byte element
2015   // splatted with a v16i8 mask.
2016   for (unsigned i = 1; i != EltSize; ++i)
2017     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2018       return false;
2019 
2020   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2021     if (N->getMaskElt(i) < 0) continue;
2022     for (unsigned j = 0; j != EltSize; ++j)
2023       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2024         return false;
2025   }
2026   return true;
2027 }
2028 
2029 /// Check that the mask is shuffling N byte elements. Within each N byte
2030 /// element of the mask, the indices could be either in increasing or
2031 /// decreasing order as long as they are consecutive.
2032 /// \param[in] N the shuffle vector SD Node to analyze
2033 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2034 /// Word/DoubleWord/QuadWord).
2035 /// \param[in] StepLen the delta indices number among the N byte element, if
2036 /// the mask is in increasing/decreasing order then it is 1/-1.
2037 /// \return true iff the mask is shuffling N byte elements.
2038 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2039                                    int StepLen) {
2040   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2041          "Unexpected element width.");
2042   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2043 
2044   unsigned NumOfElem = 16 / Width;
2045   unsigned MaskVal[16]; //  Width is never greater than 16
2046   for (unsigned i = 0; i < NumOfElem; ++i) {
2047     MaskVal[0] = N->getMaskElt(i * Width);
2048     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2049       return false;
2050     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2051       return false;
2052     }
2053 
2054     for (unsigned int j = 1; j < Width; ++j) {
2055       MaskVal[j] = N->getMaskElt(i * Width + j);
2056       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2057         return false;
2058       }
2059     }
2060   }
2061 
2062   return true;
2063 }
2064 
2065 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2066                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2067   if (!isNByteElemShuffleMask(N, 4, 1))
2068     return false;
2069 
2070   // Now we look at mask elements 0,4,8,12
2071   unsigned M0 = N->getMaskElt(0) / 4;
2072   unsigned M1 = N->getMaskElt(4) / 4;
2073   unsigned M2 = N->getMaskElt(8) / 4;
2074   unsigned M3 = N->getMaskElt(12) / 4;
2075   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2076   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2077 
2078   // Below, let H and L be arbitrary elements of the shuffle mask
2079   // where H is in the range [4,7] and L is in the range [0,3].
2080   // H, 1, 2, 3 or L, 5, 6, 7
2081   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2082       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2083     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2084     InsertAtByte = IsLE ? 12 : 0;
2085     Swap = M0 < 4;
2086     return true;
2087   }
2088   // 0, H, 2, 3 or 4, L, 6, 7
2089   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2090       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2091     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2092     InsertAtByte = IsLE ? 8 : 4;
2093     Swap = M1 < 4;
2094     return true;
2095   }
2096   // 0, 1, H, 3 or 4, 5, L, 7
2097   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2098       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2099     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2100     InsertAtByte = IsLE ? 4 : 8;
2101     Swap = M2 < 4;
2102     return true;
2103   }
2104   // 0, 1, 2, H or 4, 5, 6, L
2105   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2106       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2107     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2108     InsertAtByte = IsLE ? 0 : 12;
2109     Swap = M3 < 4;
2110     return true;
2111   }
2112 
2113   // If both vector operands for the shuffle are the same vector, the mask will
2114   // contain only elements from the first one and the second one will be undef.
2115   if (N->getOperand(1).isUndef()) {
2116     ShiftElts = 0;
2117     Swap = true;
2118     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2119     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2120       InsertAtByte = IsLE ? 12 : 0;
2121       return true;
2122     }
2123     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2124       InsertAtByte = IsLE ? 8 : 4;
2125       return true;
2126     }
2127     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2128       InsertAtByte = IsLE ? 4 : 8;
2129       return true;
2130     }
2131     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2132       InsertAtByte = IsLE ? 0 : 12;
2133       return true;
2134     }
2135   }
2136 
2137   return false;
2138 }
2139 
2140 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2141                                bool &Swap, bool IsLE) {
2142   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2143   // Ensure each byte index of the word is consecutive.
2144   if (!isNByteElemShuffleMask(N, 4, 1))
2145     return false;
2146 
2147   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2148   unsigned M0 = N->getMaskElt(0) / 4;
2149   unsigned M1 = N->getMaskElt(4) / 4;
2150   unsigned M2 = N->getMaskElt(8) / 4;
2151   unsigned M3 = N->getMaskElt(12) / 4;
2152 
2153   // If both vector operands for the shuffle are the same vector, the mask will
2154   // contain only elements from the first one and the second one will be undef.
2155   if (N->getOperand(1).isUndef()) {
2156     assert(M0 < 4 && "Indexing into an undef vector?");
2157     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2158       return false;
2159 
2160     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2161     Swap = false;
2162     return true;
2163   }
2164 
2165   // Ensure each word index of the ShuffleVector Mask is consecutive.
2166   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2167     return false;
2168 
2169   if (IsLE) {
2170     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2171       // Input vectors don't need to be swapped if the leading element
2172       // of the result is one of the 3 left elements of the second vector
2173       // (or if there is no shift to be done at all).
2174       Swap = false;
2175       ShiftElts = (8 - M0) % 8;
2176     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2177       // Input vectors need to be swapped if the leading element
2178       // of the result is one of the 3 left elements of the first vector
2179       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2180       Swap = true;
2181       ShiftElts = (4 - M0) % 4;
2182     }
2183 
2184     return true;
2185   } else {                                          // BE
2186     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2187       // Input vectors don't need to be swapped if the leading element
2188       // of the result is one of the 4 elements of the first vector.
2189       Swap = false;
2190       ShiftElts = M0;
2191     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2192       // Input vectors need to be swapped if the leading element
2193       // of the result is one of the 4 elements of the right vector.
2194       Swap = true;
2195       ShiftElts = M0 - 4;
2196     }
2197 
2198     return true;
2199   }
2200 }
2201 
2202 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2203   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2204 
2205   if (!isNByteElemShuffleMask(N, Width, -1))
2206     return false;
2207 
2208   for (int i = 0; i < 16; i += Width)
2209     if (N->getMaskElt(i) != i + Width - 1)
2210       return false;
2211 
2212   return true;
2213 }
2214 
2215 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2216   return isXXBRShuffleMaskHelper(N, 2);
2217 }
2218 
2219 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2220   return isXXBRShuffleMaskHelper(N, 4);
2221 }
2222 
2223 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2224   return isXXBRShuffleMaskHelper(N, 8);
2225 }
2226 
2227 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2228   return isXXBRShuffleMaskHelper(N, 16);
2229 }
2230 
2231 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2232 /// if the inputs to the instruction should be swapped and set \p DM to the
2233 /// value for the immediate.
2234 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2235 /// AND element 0 of the result comes from the first input (LE) or second input
2236 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2237 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2238 /// mask.
2239 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2240                                bool &Swap, bool IsLE) {
2241   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2242 
2243   // Ensure each byte index of the double word is consecutive.
2244   if (!isNByteElemShuffleMask(N, 8, 1))
2245     return false;
2246 
2247   unsigned M0 = N->getMaskElt(0) / 8;
2248   unsigned M1 = N->getMaskElt(8) / 8;
2249   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2250 
2251   // If both vector operands for the shuffle are the same vector, the mask will
2252   // contain only elements from the first one and the second one will be undef.
2253   if (N->getOperand(1).isUndef()) {
2254     if ((M0 | M1) < 2) {
2255       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2256       Swap = false;
2257       return true;
2258     } else
2259       return false;
2260   }
2261 
2262   if (IsLE) {
2263     if (M0 > 1 && M1 < 2) {
2264       Swap = false;
2265     } else if (M0 < 2 && M1 > 1) {
2266       M0 = (M0 + 2) % 4;
2267       M1 = (M1 + 2) % 4;
2268       Swap = true;
2269     } else
2270       return false;
2271 
2272     // Note: if control flow comes here that means Swap is already set above
2273     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2274     return true;
2275   } else { // BE
2276     if (M0 < 2 && M1 > 1) {
2277       Swap = false;
2278     } else if (M0 > 1 && M1 < 2) {
2279       M0 = (M0 + 2) % 4;
2280       M1 = (M1 + 2) % 4;
2281       Swap = true;
2282     } else
2283       return false;
2284 
2285     // Note: if control flow comes here that means Swap is already set above
2286     DM = (M0 << 1) + (M1 & 1);
2287     return true;
2288   }
2289 }
2290 
2291 
2292 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2293 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2294 /// elements are counted from the left of the vector register).
2295 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2296                                          SelectionDAG &DAG) {
2297   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2298   assert(isSplatShuffleMask(SVOp, EltSize));
2299   if (DAG.getDataLayout().isLittleEndian())
2300     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2301   else
2302     return SVOp->getMaskElt(0) / EltSize;
2303 }
2304 
2305 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2306 /// by using a vspltis[bhw] instruction of the specified element size, return
2307 /// the constant being splatted.  The ByteSize field indicates the number of
2308 /// bytes of each element [124] -> [bhw].
2309 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2310   SDValue OpVal(nullptr, 0);
2311 
2312   // If ByteSize of the splat is bigger than the element size of the
2313   // build_vector, then we have a case where we are checking for a splat where
2314   // multiple elements of the buildvector are folded together into a single
2315   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2316   unsigned EltSize = 16/N->getNumOperands();
2317   if (EltSize < ByteSize) {
2318     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2319     SDValue UniquedVals[4];
2320     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2321 
2322     // See if all of the elements in the buildvector agree across.
2323     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2324       if (N->getOperand(i).isUndef()) continue;
2325       // If the element isn't a constant, bail fully out.
2326       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2327 
2328       if (!UniquedVals[i&(Multiple-1)].getNode())
2329         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2330       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2331         return SDValue();  // no match.
2332     }
2333 
2334     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2335     // either constant or undef values that are identical for each chunk.  See
2336     // if these chunks can form into a larger vspltis*.
2337 
2338     // Check to see if all of the leading entries are either 0 or -1.  If
2339     // neither, then this won't fit into the immediate field.
2340     bool LeadingZero = true;
2341     bool LeadingOnes = true;
2342     for (unsigned i = 0; i != Multiple-1; ++i) {
2343       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2344 
2345       LeadingZero &= isNullConstant(UniquedVals[i]);
2346       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2347     }
2348     // Finally, check the least significant entry.
2349     if (LeadingZero) {
2350       if (!UniquedVals[Multiple-1].getNode())
2351         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2352       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2353       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2354         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2355     }
2356     if (LeadingOnes) {
2357       if (!UniquedVals[Multiple-1].getNode())
2358         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2359       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2360       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2361         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2362     }
2363 
2364     return SDValue();
2365   }
2366 
2367   // Check to see if this buildvec has a single non-undef value in its elements.
2368   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2369     if (N->getOperand(i).isUndef()) continue;
2370     if (!OpVal.getNode())
2371       OpVal = N->getOperand(i);
2372     else if (OpVal != N->getOperand(i))
2373       return SDValue();
2374   }
2375 
2376   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2377 
2378   unsigned ValSizeInBytes = EltSize;
2379   uint64_t Value = 0;
2380   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2381     Value = CN->getZExtValue();
2382   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2383     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2384     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2385   }
2386 
2387   // If the splat value is larger than the element value, then we can never do
2388   // this splat.  The only case that we could fit the replicated bits into our
2389   // immediate field for would be zero, and we prefer to use vxor for it.
2390   if (ValSizeInBytes < ByteSize) return SDValue();
2391 
2392   // If the element value is larger than the splat value, check if it consists
2393   // of a repeated bit pattern of size ByteSize.
2394   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2395     return SDValue();
2396 
2397   // Properly sign extend the value.
2398   int MaskVal = SignExtend32(Value, ByteSize * 8);
2399 
2400   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2401   if (MaskVal == 0) return SDValue();
2402 
2403   // Finally, if this value fits in a 5 bit sext field, return it
2404   if (SignExtend32<5>(MaskVal) == MaskVal)
2405     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2406   return SDValue();
2407 }
2408 
2409 //===----------------------------------------------------------------------===//
2410 //  Addressing Mode Selection
2411 //===----------------------------------------------------------------------===//
2412 
2413 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2414 /// or 64-bit immediate, and if the value can be accurately represented as a
2415 /// sign extension from a 16-bit value.  If so, this returns true and the
2416 /// immediate.
2417 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2418   if (!isa<ConstantSDNode>(N))
2419     return false;
2420 
2421   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2422   if (N->getValueType(0) == MVT::i32)
2423     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2424   else
2425     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2426 }
2427 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2428   return isIntS16Immediate(Op.getNode(), Imm);
2429 }
2430 
2431 
2432 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2433 /// be represented as an indexed [r+r] operation.
2434 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2435                                                SDValue &Index,
2436                                                SelectionDAG &DAG) const {
2437   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2438       UI != E; ++UI) {
2439     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2440       if (Memop->getMemoryVT() == MVT::f64) {
2441           Base = N.getOperand(0);
2442           Index = N.getOperand(1);
2443           return true;
2444       }
2445     }
2446   }
2447   return false;
2448 }
2449 
2450 /// isIntS34Immediate - This method tests if value of node given can be
2451 /// accurately represented as a sign extension from a 34-bit value.  If so,
2452 /// this returns true and the immediate.
2453 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2454   if (!isa<ConstantSDNode>(N))
2455     return false;
2456 
2457   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2458   return isInt<34>(Imm);
2459 }
2460 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2461   return isIntS34Immediate(Op.getNode(), Imm);
2462 }
2463 
2464 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2465 /// can be represented as an indexed [r+r] operation.  Returns false if it
2466 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2467 /// non-zero and N can be represented by a base register plus a signed 16-bit
2468 /// displacement, make a more precise judgement by checking (displacement % \p
2469 /// EncodingAlignment).
2470 bool PPCTargetLowering::SelectAddressRegReg(
2471     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2472     MaybeAlign EncodingAlignment) const {
2473   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2474   // a [pc+imm].
2475   if (SelectAddressPCRel(N, Base))
2476     return false;
2477 
2478   int16_t Imm = 0;
2479   if (N.getOpcode() == ISD::ADD) {
2480     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2481     // SPE load/store can only handle 8-bit offsets.
2482     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2483         return true;
2484     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2485         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2486       return false; // r+i
2487     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2488       return false;    // r+i
2489 
2490     Base = N.getOperand(0);
2491     Index = N.getOperand(1);
2492     return true;
2493   } else if (N.getOpcode() == ISD::OR) {
2494     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2495         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2496       return false; // r+i can fold it if we can.
2497 
2498     // If this is an or of disjoint bitfields, we can codegen this as an add
2499     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2500     // disjoint.
2501     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2502 
2503     if (LHSKnown.Zero.getBoolValue()) {
2504       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2505       // If all of the bits are known zero on the LHS or RHS, the add won't
2506       // carry.
2507       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2508         Base = N.getOperand(0);
2509         Index = N.getOperand(1);
2510         return true;
2511       }
2512     }
2513   }
2514 
2515   return false;
2516 }
2517 
2518 // If we happen to be doing an i64 load or store into a stack slot that has
2519 // less than a 4-byte alignment, then the frame-index elimination may need to
2520 // use an indexed load or store instruction (because the offset may not be a
2521 // multiple of 4). The extra register needed to hold the offset comes from the
2522 // register scavenger, and it is possible that the scavenger will need to use
2523 // an emergency spill slot. As a result, we need to make sure that a spill slot
2524 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2525 // stack slot.
2526 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2527   // FIXME: This does not handle the LWA case.
2528   if (VT != MVT::i64)
2529     return;
2530 
2531   // NOTE: We'll exclude negative FIs here, which come from argument
2532   // lowering, because there are no known test cases triggering this problem
2533   // using packed structures (or similar). We can remove this exclusion if
2534   // we find such a test case. The reason why this is so test-case driven is
2535   // because this entire 'fixup' is only to prevent crashes (from the
2536   // register scavenger) on not-really-valid inputs. For example, if we have:
2537   //   %a = alloca i1
2538   //   %b = bitcast i1* %a to i64*
2539   //   store i64* a, i64 b
2540   // then the store should really be marked as 'align 1', but is not. If it
2541   // were marked as 'align 1' then the indexed form would have been
2542   // instruction-selected initially, and the problem this 'fixup' is preventing
2543   // won't happen regardless.
2544   if (FrameIdx < 0)
2545     return;
2546 
2547   MachineFunction &MF = DAG.getMachineFunction();
2548   MachineFrameInfo &MFI = MF.getFrameInfo();
2549 
2550   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2551     return;
2552 
2553   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2554   FuncInfo->setHasNonRISpills();
2555 }
2556 
2557 /// Returns true if the address N can be represented by a base register plus
2558 /// a signed 16-bit displacement [r+imm], and if it is not better
2559 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2560 /// displacements that are multiples of that value.
2561 bool PPCTargetLowering::SelectAddressRegImm(
2562     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2563     MaybeAlign EncodingAlignment) const {
2564   // FIXME dl should come from parent load or store, not from address
2565   SDLoc dl(N);
2566 
2567   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2568   // a [pc+imm].
2569   if (SelectAddressPCRel(N, Base))
2570     return false;
2571 
2572   // If this can be more profitably realized as r+r, fail.
2573   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2574     return false;
2575 
2576   if (N.getOpcode() == ISD::ADD) {
2577     int16_t imm = 0;
2578     if (isIntS16Immediate(N.getOperand(1), imm) &&
2579         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2580       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2581       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2582         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2583         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2584       } else {
2585         Base = N.getOperand(0);
2586       }
2587       return true; // [r+i]
2588     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2589       // Match LOAD (ADD (X, Lo(G))).
2590       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2591              && "Cannot handle constant offsets yet!");
2592       Disp = N.getOperand(1).getOperand(0);  // The global address.
2593       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2594              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2595              Disp.getOpcode() == ISD::TargetConstantPool ||
2596              Disp.getOpcode() == ISD::TargetJumpTable);
2597       Base = N.getOperand(0);
2598       return true;  // [&g+r]
2599     }
2600   } else if (N.getOpcode() == ISD::OR) {
2601     int16_t imm = 0;
2602     if (isIntS16Immediate(N.getOperand(1), imm) &&
2603         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2604       // If this is an or of disjoint bitfields, we can codegen this as an add
2605       // (for better address arithmetic) if the LHS and RHS of the OR are
2606       // provably disjoint.
2607       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2608 
2609       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2610         // If all of the bits are known zero on the LHS or RHS, the add won't
2611         // carry.
2612         if (FrameIndexSDNode *FI =
2613               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2614           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2615           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2616         } else {
2617           Base = N.getOperand(0);
2618         }
2619         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2620         return true;
2621       }
2622     }
2623   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2624     // Loading from a constant address.
2625 
2626     // If this address fits entirely in a 16-bit sext immediate field, codegen
2627     // this as "d, 0"
2628     int16_t Imm;
2629     if (isIntS16Immediate(CN, Imm) &&
2630         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2631       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2632       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2633                              CN->getValueType(0));
2634       return true;
2635     }
2636 
2637     // Handle 32-bit sext immediates with LIS + addr mode.
2638     if ((CN->getValueType(0) == MVT::i32 ||
2639          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2640         (!EncodingAlignment ||
2641          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2642       int Addr = (int)CN->getZExtValue();
2643 
2644       // Otherwise, break this down into an LIS + disp.
2645       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2646 
2647       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2648                                    MVT::i32);
2649       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2650       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2651       return true;
2652     }
2653   }
2654 
2655   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2656   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2657     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2658     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2659   } else
2660     Base = N;
2661   return true;      // [r+0]
2662 }
2663 
2664 /// Similar to the 16-bit case but for instructions that take a 34-bit
2665 /// displacement field (prefixed loads/stores).
2666 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2667                                               SDValue &Base,
2668                                               SelectionDAG &DAG) const {
2669   // Only on 64-bit targets.
2670   if (N.getValueType() != MVT::i64)
2671     return false;
2672 
2673   SDLoc dl(N);
2674   int64_t Imm = 0;
2675 
2676   if (N.getOpcode() == ISD::ADD) {
2677     if (!isIntS34Immediate(N.getOperand(1), Imm))
2678       return false;
2679     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2680     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2681       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2682     else
2683       Base = N.getOperand(0);
2684     return true;
2685   }
2686 
2687   if (N.getOpcode() == ISD::OR) {
2688     if (!isIntS34Immediate(N.getOperand(1), Imm))
2689       return false;
2690     // If this is an or of disjoint bitfields, we can codegen this as an add
2691     // (for better address arithmetic) if the LHS and RHS of the OR are
2692     // provably disjoint.
2693     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2694     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2695       return false;
2696     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2697       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2698     else
2699       Base = N.getOperand(0);
2700     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2701     return true;
2702   }
2703 
2704   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2705     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2706     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2707     return true;
2708   }
2709 
2710   return false;
2711 }
2712 
2713 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2714 /// represented as an indexed [r+r] operation.
2715 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2716                                                 SDValue &Index,
2717                                                 SelectionDAG &DAG) const {
2718   // Check to see if we can easily represent this as an [r+r] address.  This
2719   // will fail if it thinks that the address is more profitably represented as
2720   // reg+imm, e.g. where imm = 0.
2721   if (SelectAddressRegReg(N, Base, Index, DAG))
2722     return true;
2723 
2724   // If the address is the result of an add, we will utilize the fact that the
2725   // address calculation includes an implicit add.  However, we can reduce
2726   // register pressure if we do not materialize a constant just for use as the
2727   // index register.  We only get rid of the add if it is not an add of a
2728   // value and a 16-bit signed constant and both have a single use.
2729   int16_t imm = 0;
2730   if (N.getOpcode() == ISD::ADD &&
2731       (!isIntS16Immediate(N.getOperand(1), imm) ||
2732        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2733     Base = N.getOperand(0);
2734     Index = N.getOperand(1);
2735     return true;
2736   }
2737 
2738   // Otherwise, do it the hard way, using R0 as the base register.
2739   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2740                          N.getValueType());
2741   Index = N;
2742   return true;
2743 }
2744 
2745 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2746   Ty *PCRelCand = dyn_cast<Ty>(N);
2747   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2748 }
2749 
2750 /// Returns true if this address is a PC Relative address.
2751 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2752 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2753 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2754   // This is a materialize PC Relative node. Always select this as PC Relative.
2755   Base = N;
2756   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2757     return true;
2758   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2759       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2760       isValidPCRelNode<JumpTableSDNode>(N) ||
2761       isValidPCRelNode<BlockAddressSDNode>(N))
2762     return true;
2763   return false;
2764 }
2765 
2766 /// Returns true if we should use a direct load into vector instruction
2767 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2768 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2769 
2770   // If there are any other uses other than scalar to vector, then we should
2771   // keep it as a scalar load -> direct move pattern to prevent multiple
2772   // loads.
2773   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2774   if (!LD)
2775     return false;
2776 
2777   EVT MemVT = LD->getMemoryVT();
2778   if (!MemVT.isSimple())
2779     return false;
2780   switch(MemVT.getSimpleVT().SimpleTy) {
2781   case MVT::i64:
2782     break;
2783   case MVT::i32:
2784     if (!ST.hasP8Vector())
2785       return false;
2786     break;
2787   case MVT::i16:
2788   case MVT::i8:
2789     if (!ST.hasP9Vector())
2790       return false;
2791     break;
2792   default:
2793     return false;
2794   }
2795 
2796   SDValue LoadedVal(N, 0);
2797   if (!LoadedVal.hasOneUse())
2798     return false;
2799 
2800   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2801        UI != UE; ++UI)
2802     if (UI.getUse().get().getResNo() == 0 &&
2803         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2804         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2805       return false;
2806 
2807   return true;
2808 }
2809 
2810 /// getPreIndexedAddressParts - returns true by value, base pointer and
2811 /// offset pointer and addressing mode by reference if the node's address
2812 /// can be legally represented as pre-indexed load / store address.
2813 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2814                                                   SDValue &Offset,
2815                                                   ISD::MemIndexedMode &AM,
2816                                                   SelectionDAG &DAG) const {
2817   if (DisablePPCPreinc) return false;
2818 
2819   bool isLoad = true;
2820   SDValue Ptr;
2821   EVT VT;
2822   unsigned Alignment;
2823   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2824     Ptr = LD->getBasePtr();
2825     VT = LD->getMemoryVT();
2826     Alignment = LD->getAlignment();
2827   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2828     Ptr = ST->getBasePtr();
2829     VT  = ST->getMemoryVT();
2830     Alignment = ST->getAlignment();
2831     isLoad = false;
2832   } else
2833     return false;
2834 
2835   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2836   // instructions because we can fold these into a more efficient instruction
2837   // instead, (such as LXSD).
2838   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2839     return false;
2840   }
2841 
2842   // PowerPC doesn't have preinc load/store instructions for vectors
2843   if (VT.isVector())
2844     return false;
2845 
2846   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2847     // Common code will reject creating a pre-inc form if the base pointer
2848     // is a frame index, or if N is a store and the base pointer is either
2849     // the same as or a predecessor of the value being stored.  Check for
2850     // those situations here, and try with swapped Base/Offset instead.
2851     bool Swap = false;
2852 
2853     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2854       Swap = true;
2855     else if (!isLoad) {
2856       SDValue Val = cast<StoreSDNode>(N)->getValue();
2857       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2858         Swap = true;
2859     }
2860 
2861     if (Swap)
2862       std::swap(Base, Offset);
2863 
2864     AM = ISD::PRE_INC;
2865     return true;
2866   }
2867 
2868   // LDU/STU can only handle immediates that are a multiple of 4.
2869   if (VT != MVT::i64) {
2870     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2871       return false;
2872   } else {
2873     // LDU/STU need an address with at least 4-byte alignment.
2874     if (Alignment < 4)
2875       return false;
2876 
2877     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2878       return false;
2879   }
2880 
2881   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2882     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2883     // sext i32 to i64 when addr mode is r+i.
2884     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2885         LD->getExtensionType() == ISD::SEXTLOAD &&
2886         isa<ConstantSDNode>(Offset))
2887       return false;
2888   }
2889 
2890   AM = ISD::PRE_INC;
2891   return true;
2892 }
2893 
2894 //===----------------------------------------------------------------------===//
2895 //  LowerOperation implementation
2896 //===----------------------------------------------------------------------===//
2897 
2898 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2899 /// and LoOpFlags to the target MO flags.
2900 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2901                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2902                                const GlobalValue *GV = nullptr) {
2903   HiOpFlags = PPCII::MO_HA;
2904   LoOpFlags = PPCII::MO_LO;
2905 
2906   // Don't use the pic base if not in PIC relocation model.
2907   if (IsPIC) {
2908     HiOpFlags |= PPCII::MO_PIC_FLAG;
2909     LoOpFlags |= PPCII::MO_PIC_FLAG;
2910   }
2911 }
2912 
2913 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2914                              SelectionDAG &DAG) {
2915   SDLoc DL(HiPart);
2916   EVT PtrVT = HiPart.getValueType();
2917   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2918 
2919   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2920   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2921 
2922   // With PIC, the first instruction is actually "GR+hi(&G)".
2923   if (isPIC)
2924     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2925                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2926 
2927   // Generate non-pic code that has direct accesses to the constant pool.
2928   // The address of the global is just (hi(&g)+lo(&g)).
2929   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2930 }
2931 
2932 static void setUsesTOCBasePtr(MachineFunction &MF) {
2933   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2934   FuncInfo->setUsesTOCBasePtr();
2935 }
2936 
2937 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2938   setUsesTOCBasePtr(DAG.getMachineFunction());
2939 }
2940 
2941 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2942                                        SDValue GA) const {
2943   const bool Is64Bit = Subtarget.isPPC64();
2944   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2945   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2946                         : Subtarget.isAIXABI()
2947                               ? DAG.getRegister(PPC::R2, VT)
2948                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2949   SDValue Ops[] = { GA, Reg };
2950   return DAG.getMemIntrinsicNode(
2951       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2952       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2953       MachineMemOperand::MOLoad);
2954 }
2955 
2956 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2957                                              SelectionDAG &DAG) const {
2958   EVT PtrVT = Op.getValueType();
2959   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2960   const Constant *C = CP->getConstVal();
2961 
2962   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2963   // The actual address of the GlobalValue is stored in the TOC.
2964   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2965     if (Subtarget.isUsingPCRelativeCalls()) {
2966       SDLoc DL(CP);
2967       EVT Ty = getPointerTy(DAG.getDataLayout());
2968       SDValue ConstPool = DAG.getTargetConstantPool(
2969           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2970       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2971     }
2972     setUsesTOCBasePtr(DAG);
2973     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2974     return getTOCEntry(DAG, SDLoc(CP), GA);
2975   }
2976 
2977   unsigned MOHiFlag, MOLoFlag;
2978   bool IsPIC = isPositionIndependent();
2979   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2980 
2981   if (IsPIC && Subtarget.isSVR4ABI()) {
2982     SDValue GA =
2983         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2984     return getTOCEntry(DAG, SDLoc(CP), GA);
2985   }
2986 
2987   SDValue CPIHi =
2988       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2989   SDValue CPILo =
2990       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2991   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2992 }
2993 
2994 // For 64-bit PowerPC, prefer the more compact relative encodings.
2995 // This trades 32 bits per jump table entry for one or two instructions
2996 // on the jump site.
2997 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2998   if (isJumpTableRelative())
2999     return MachineJumpTableInfo::EK_LabelDifference32;
3000 
3001   return TargetLowering::getJumpTableEncoding();
3002 }
3003 
3004 bool PPCTargetLowering::isJumpTableRelative() const {
3005   if (UseAbsoluteJumpTables)
3006     return false;
3007   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3008     return true;
3009   return TargetLowering::isJumpTableRelative();
3010 }
3011 
3012 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3013                                                     SelectionDAG &DAG) const {
3014   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3015     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3016 
3017   switch (getTargetMachine().getCodeModel()) {
3018   case CodeModel::Small:
3019   case CodeModel::Medium:
3020     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3021   default:
3022     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3023                        getPointerTy(DAG.getDataLayout()));
3024   }
3025 }
3026 
3027 const MCExpr *
3028 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3029                                                 unsigned JTI,
3030                                                 MCContext &Ctx) const {
3031   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3032     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3033 
3034   switch (getTargetMachine().getCodeModel()) {
3035   case CodeModel::Small:
3036   case CodeModel::Medium:
3037     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3038   default:
3039     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3040   }
3041 }
3042 
3043 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3044   EVT PtrVT = Op.getValueType();
3045   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3046 
3047   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3048   if (Subtarget.isUsingPCRelativeCalls()) {
3049     SDLoc DL(JT);
3050     EVT Ty = getPointerTy(DAG.getDataLayout());
3051     SDValue GA =
3052         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3053     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3054     return MatAddr;
3055   }
3056 
3057   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3058   // The actual address of the GlobalValue is stored in the TOC.
3059   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3060     setUsesTOCBasePtr(DAG);
3061     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3062     return getTOCEntry(DAG, SDLoc(JT), GA);
3063   }
3064 
3065   unsigned MOHiFlag, MOLoFlag;
3066   bool IsPIC = isPositionIndependent();
3067   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3068 
3069   if (IsPIC && Subtarget.isSVR4ABI()) {
3070     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3071                                         PPCII::MO_PIC_FLAG);
3072     return getTOCEntry(DAG, SDLoc(GA), GA);
3073   }
3074 
3075   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3076   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3077   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3078 }
3079 
3080 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3081                                              SelectionDAG &DAG) const {
3082   EVT PtrVT = Op.getValueType();
3083   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3084   const BlockAddress *BA = BASDN->getBlockAddress();
3085 
3086   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3087   if (Subtarget.isUsingPCRelativeCalls()) {
3088     SDLoc DL(BASDN);
3089     EVT Ty = getPointerTy(DAG.getDataLayout());
3090     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3091                                            PPCII::MO_PCREL_FLAG);
3092     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3093     return MatAddr;
3094   }
3095 
3096   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3097   // The actual BlockAddress is stored in the TOC.
3098   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3099     setUsesTOCBasePtr(DAG);
3100     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3101     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3102   }
3103 
3104   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3105   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3106     return getTOCEntry(
3107         DAG, SDLoc(BASDN),
3108         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3109 
3110   unsigned MOHiFlag, MOLoFlag;
3111   bool IsPIC = isPositionIndependent();
3112   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3113   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3114   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3115   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3116 }
3117 
3118 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3119                                               SelectionDAG &DAG) const {
3120   // FIXME: TLS addresses currently use medium model code sequences,
3121   // which is the most useful form.  Eventually support for small and
3122   // large models could be added if users need it, at the cost of
3123   // additional complexity.
3124   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3125   if (DAG.getTarget().useEmulatedTLS())
3126     return LowerToTLSEmulatedModel(GA, DAG);
3127 
3128   SDLoc dl(GA);
3129   const GlobalValue *GV = GA->getGlobal();
3130   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3131   bool is64bit = Subtarget.isPPC64();
3132   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3133   PICLevel::Level picLevel = M->getPICLevel();
3134 
3135   const TargetMachine &TM = getTargetMachine();
3136   TLSModel::Model Model = TM.getTLSModel(GV);
3137 
3138   if (Model == TLSModel::LocalExec) {
3139     if (Subtarget.isUsingPCRelativeCalls()) {
3140       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3141       SDValue TGA = DAG.getTargetGlobalAddress(
3142           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3143       SDValue MatAddr =
3144           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3145       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3146     }
3147 
3148     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3149                                                PPCII::MO_TPREL_HA);
3150     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3151                                                PPCII::MO_TPREL_LO);
3152     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3153                              : DAG.getRegister(PPC::R2, MVT::i32);
3154 
3155     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3156     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3157   }
3158 
3159   if (Model == TLSModel::InitialExec) {
3160     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3161     SDValue TGA = DAG.getTargetGlobalAddress(
3162         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3163     SDValue TGATLS = DAG.getTargetGlobalAddress(
3164         GV, dl, PtrVT, 0,
3165         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3166     SDValue TPOffset;
3167     if (IsPCRel) {
3168       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3169       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3170                              MachinePointerInfo());
3171     } else {
3172       SDValue GOTPtr;
3173       if (is64bit) {
3174         setUsesTOCBasePtr(DAG);
3175         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3176         GOTPtr =
3177             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3178       } else {
3179         if (!TM.isPositionIndependent())
3180           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3181         else if (picLevel == PICLevel::SmallPIC)
3182           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3183         else
3184           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3185       }
3186       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3187     }
3188     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3189   }
3190 
3191   if (Model == TLSModel::GeneralDynamic) {
3192     if (Subtarget.isUsingPCRelativeCalls()) {
3193       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3194                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3195       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3196     }
3197 
3198     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3199     SDValue GOTPtr;
3200     if (is64bit) {
3201       setUsesTOCBasePtr(DAG);
3202       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3203       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3204                                    GOTReg, TGA);
3205     } else {
3206       if (picLevel == PICLevel::SmallPIC)
3207         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3208       else
3209         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3210     }
3211     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3212                        GOTPtr, TGA, TGA);
3213   }
3214 
3215   if (Model == TLSModel::LocalDynamic) {
3216     if (Subtarget.isUsingPCRelativeCalls()) {
3217       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3218                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3219       SDValue MatPCRel =
3220           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3221       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3222     }
3223 
3224     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3225     SDValue GOTPtr;
3226     if (is64bit) {
3227       setUsesTOCBasePtr(DAG);
3228       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3229       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3230                            GOTReg, TGA);
3231     } else {
3232       if (picLevel == PICLevel::SmallPIC)
3233         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3234       else
3235         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3236     }
3237     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3238                                   PtrVT, GOTPtr, TGA, TGA);
3239     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3240                                       PtrVT, TLSAddr, TGA);
3241     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3242   }
3243 
3244   llvm_unreachable("Unknown TLS model!");
3245 }
3246 
3247 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3248                                               SelectionDAG &DAG) const {
3249   EVT PtrVT = Op.getValueType();
3250   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3251   SDLoc DL(GSDN);
3252   const GlobalValue *GV = GSDN->getGlobal();
3253 
3254   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3255   // The actual address of the GlobalValue is stored in the TOC.
3256   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3257     if (Subtarget.isUsingPCRelativeCalls()) {
3258       EVT Ty = getPointerTy(DAG.getDataLayout());
3259       if (isAccessedAsGotIndirect(Op)) {
3260         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3261                                                 PPCII::MO_PCREL_FLAG |
3262                                                     PPCII::MO_GOT_FLAG);
3263         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3264         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3265                                    MachinePointerInfo());
3266         return Load;
3267       } else {
3268         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3269                                                 PPCII::MO_PCREL_FLAG);
3270         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3271       }
3272     }
3273     setUsesTOCBasePtr(DAG);
3274     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3275     return getTOCEntry(DAG, DL, GA);
3276   }
3277 
3278   unsigned MOHiFlag, MOLoFlag;
3279   bool IsPIC = isPositionIndependent();
3280   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3281 
3282   if (IsPIC && Subtarget.isSVR4ABI()) {
3283     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3284                                             GSDN->getOffset(),
3285                                             PPCII::MO_PIC_FLAG);
3286     return getTOCEntry(DAG, DL, GA);
3287   }
3288 
3289   SDValue GAHi =
3290     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3291   SDValue GALo =
3292     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3293 
3294   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3295 }
3296 
3297 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3298   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3299   SDLoc dl(Op);
3300 
3301   if (Op.getValueType() == MVT::v2i64) {
3302     // When the operands themselves are v2i64 values, we need to do something
3303     // special because VSX has no underlying comparison operations for these.
3304     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3305       // Equality can be handled by casting to the legal type for Altivec
3306       // comparisons, everything else needs to be expanded.
3307       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3308         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3309                  DAG.getSetCC(dl, MVT::v4i32,
3310                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3311                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3312                    CC));
3313       }
3314 
3315       return SDValue();
3316     }
3317 
3318     // We handle most of these in the usual way.
3319     return Op;
3320   }
3321 
3322   // If we're comparing for equality to zero, expose the fact that this is
3323   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3324   // fold the new nodes.
3325   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3326     return V;
3327 
3328   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3329     // Leave comparisons against 0 and -1 alone for now, since they're usually
3330     // optimized.  FIXME: revisit this when we can custom lower all setcc
3331     // optimizations.
3332     if (C->isAllOnesValue() || C->isNullValue())
3333       return SDValue();
3334   }
3335 
3336   // If we have an integer seteq/setne, turn it into a compare against zero
3337   // by xor'ing the rhs with the lhs, which is faster than setting a
3338   // condition register, reading it back out, and masking the correct bit.  The
3339   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3340   // the result to other bit-twiddling opportunities.
3341   EVT LHSVT = Op.getOperand(0).getValueType();
3342   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3343     EVT VT = Op.getValueType();
3344     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3345                                 Op.getOperand(1));
3346     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3347   }
3348   return SDValue();
3349 }
3350 
3351 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3352   SDNode *Node = Op.getNode();
3353   EVT VT = Node->getValueType(0);
3354   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3355   SDValue InChain = Node->getOperand(0);
3356   SDValue VAListPtr = Node->getOperand(1);
3357   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3358   SDLoc dl(Node);
3359 
3360   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3361 
3362   // gpr_index
3363   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3364                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3365   InChain = GprIndex.getValue(1);
3366 
3367   if (VT == MVT::i64) {
3368     // Check if GprIndex is even
3369     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3370                                  DAG.getConstant(1, dl, MVT::i32));
3371     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3372                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3373     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3374                                           DAG.getConstant(1, dl, MVT::i32));
3375     // Align GprIndex to be even if it isn't
3376     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3377                            GprIndex);
3378   }
3379 
3380   // fpr index is 1 byte after gpr
3381   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3382                                DAG.getConstant(1, dl, MVT::i32));
3383 
3384   // fpr
3385   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3386                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3387   InChain = FprIndex.getValue(1);
3388 
3389   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3390                                        DAG.getConstant(8, dl, MVT::i32));
3391 
3392   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3393                                         DAG.getConstant(4, dl, MVT::i32));
3394 
3395   // areas
3396   SDValue OverflowArea =
3397       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3398   InChain = OverflowArea.getValue(1);
3399 
3400   SDValue RegSaveArea =
3401       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3402   InChain = RegSaveArea.getValue(1);
3403 
3404   // select overflow_area if index > 8
3405   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3406                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3407 
3408   // adjustment constant gpr_index * 4/8
3409   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3410                                     VT.isInteger() ? GprIndex : FprIndex,
3411                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3412                                                     MVT::i32));
3413 
3414   // OurReg = RegSaveArea + RegConstant
3415   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3416                                RegConstant);
3417 
3418   // Floating types are 32 bytes into RegSaveArea
3419   if (VT.isFloatingPoint())
3420     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3421                          DAG.getConstant(32, dl, MVT::i32));
3422 
3423   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3424   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3425                                    VT.isInteger() ? GprIndex : FprIndex,
3426                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3427                                                    MVT::i32));
3428 
3429   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3430                               VT.isInteger() ? VAListPtr : FprPtr,
3431                               MachinePointerInfo(SV), MVT::i8);
3432 
3433   // determine if we should load from reg_save_area or overflow_area
3434   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3435 
3436   // increase overflow_area by 4/8 if gpr/fpr > 8
3437   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3438                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3439                                           dl, MVT::i32));
3440 
3441   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3442                              OverflowAreaPlusN);
3443 
3444   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3445                               MachinePointerInfo(), MVT::i32);
3446 
3447   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3448 }
3449 
3450 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3451   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3452 
3453   // We have to copy the entire va_list struct:
3454   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3455   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3456                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3457                        false, true, false, MachinePointerInfo(),
3458                        MachinePointerInfo());
3459 }
3460 
3461 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3462                                                   SelectionDAG &DAG) const {
3463   if (Subtarget.isAIXABI())
3464     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3465 
3466   return Op.getOperand(0);
3467 }
3468 
3469 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3470                                                 SelectionDAG &DAG) const {
3471   if (Subtarget.isAIXABI())
3472     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3473 
3474   SDValue Chain = Op.getOperand(0);
3475   SDValue Trmp = Op.getOperand(1); // trampoline
3476   SDValue FPtr = Op.getOperand(2); // nested function
3477   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3478   SDLoc dl(Op);
3479 
3480   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3481   bool isPPC64 = (PtrVT == MVT::i64);
3482   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3483 
3484   TargetLowering::ArgListTy Args;
3485   TargetLowering::ArgListEntry Entry;
3486 
3487   Entry.Ty = IntPtrTy;
3488   Entry.Node = Trmp; Args.push_back(Entry);
3489 
3490   // TrampSize == (isPPC64 ? 48 : 40);
3491   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3492                                isPPC64 ? MVT::i64 : MVT::i32);
3493   Args.push_back(Entry);
3494 
3495   Entry.Node = FPtr; Args.push_back(Entry);
3496   Entry.Node = Nest; Args.push_back(Entry);
3497 
3498   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3499   TargetLowering::CallLoweringInfo CLI(DAG);
3500   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3501       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3502       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3503 
3504   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3505   return CallResult.second;
3506 }
3507 
3508 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3509   MachineFunction &MF = DAG.getMachineFunction();
3510   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3511   EVT PtrVT = getPointerTy(MF.getDataLayout());
3512 
3513   SDLoc dl(Op);
3514 
3515   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3516     // vastart just stores the address of the VarArgsFrameIndex slot into the
3517     // memory location argument.
3518     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3519     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3520     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3521                         MachinePointerInfo(SV));
3522   }
3523 
3524   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3525   // We suppose the given va_list is already allocated.
3526   //
3527   // typedef struct {
3528   //  char gpr;     /* index into the array of 8 GPRs
3529   //                 * stored in the register save area
3530   //                 * gpr=0 corresponds to r3,
3531   //                 * gpr=1 to r4, etc.
3532   //                 */
3533   //  char fpr;     /* index into the array of 8 FPRs
3534   //                 * stored in the register save area
3535   //                 * fpr=0 corresponds to f1,
3536   //                 * fpr=1 to f2, etc.
3537   //                 */
3538   //  char *overflow_arg_area;
3539   //                /* location on stack that holds
3540   //                 * the next overflow argument
3541   //                 */
3542   //  char *reg_save_area;
3543   //               /* where r3:r10 and f1:f8 (if saved)
3544   //                * are stored
3545   //                */
3546   // } va_list[1];
3547 
3548   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3549   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3550   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3551                                             PtrVT);
3552   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3553                                  PtrVT);
3554 
3555   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3556   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3557 
3558   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3559   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3560 
3561   uint64_t FPROffset = 1;
3562   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3563 
3564   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3565 
3566   // Store first byte : number of int regs
3567   SDValue firstStore =
3568       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3569                         MachinePointerInfo(SV), MVT::i8);
3570   uint64_t nextOffset = FPROffset;
3571   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3572                                   ConstFPROffset);
3573 
3574   // Store second byte : number of float regs
3575   SDValue secondStore =
3576       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3577                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3578   nextOffset += StackOffset;
3579   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3580 
3581   // Store second word : arguments given on stack
3582   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3583                                     MachinePointerInfo(SV, nextOffset));
3584   nextOffset += FrameOffset;
3585   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3586 
3587   // Store third word : arguments given in registers
3588   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3589                       MachinePointerInfo(SV, nextOffset));
3590 }
3591 
3592 /// FPR - The set of FP registers that should be allocated for arguments
3593 /// on Darwin and AIX.
3594 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3595                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3596                                 PPC::F11, PPC::F12, PPC::F13};
3597 
3598 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3599 /// the stack.
3600 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3601                                        unsigned PtrByteSize) {
3602   unsigned ArgSize = ArgVT.getStoreSize();
3603   if (Flags.isByVal())
3604     ArgSize = Flags.getByValSize();
3605 
3606   // Round up to multiples of the pointer size, except for array members,
3607   // which are always packed.
3608   if (!Flags.isInConsecutiveRegs())
3609     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3610 
3611   return ArgSize;
3612 }
3613 
3614 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3615 /// on the stack.
3616 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3617                                          ISD::ArgFlagsTy Flags,
3618                                          unsigned PtrByteSize) {
3619   Align Alignment(PtrByteSize);
3620 
3621   // Altivec parameters are padded to a 16 byte boundary.
3622   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3623       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3624       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3625       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3626     Alignment = Align(16);
3627 
3628   // ByVal parameters are aligned as requested.
3629   if (Flags.isByVal()) {
3630     auto BVAlign = Flags.getNonZeroByValAlign();
3631     if (BVAlign > PtrByteSize) {
3632       if (BVAlign.value() % PtrByteSize != 0)
3633         llvm_unreachable(
3634             "ByVal alignment is not a multiple of the pointer size");
3635 
3636       Alignment = BVAlign;
3637     }
3638   }
3639 
3640   // Array members are always packed to their original alignment.
3641   if (Flags.isInConsecutiveRegs()) {
3642     // If the array member was split into multiple registers, the first
3643     // needs to be aligned to the size of the full type.  (Except for
3644     // ppcf128, which is only aligned as its f64 components.)
3645     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3646       Alignment = Align(OrigVT.getStoreSize());
3647     else
3648       Alignment = Align(ArgVT.getStoreSize());
3649   }
3650 
3651   return Alignment;
3652 }
3653 
3654 /// CalculateStackSlotUsed - Return whether this argument will use its
3655 /// stack slot (instead of being passed in registers).  ArgOffset,
3656 /// AvailableFPRs, and AvailableVRs must hold the current argument
3657 /// position, and will be updated to account for this argument.
3658 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3659                                    unsigned PtrByteSize, unsigned LinkageSize,
3660                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3661                                    unsigned &AvailableFPRs,
3662                                    unsigned &AvailableVRs) {
3663   bool UseMemory = false;
3664 
3665   // Respect alignment of argument on the stack.
3666   Align Alignment =
3667       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3668   ArgOffset = alignTo(ArgOffset, Alignment);
3669   // If there's no space left in the argument save area, we must
3670   // use memory (this check also catches zero-sized arguments).
3671   if (ArgOffset >= LinkageSize + ParamAreaSize)
3672     UseMemory = true;
3673 
3674   // Allocate argument on the stack.
3675   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3676   if (Flags.isInConsecutiveRegsLast())
3677     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3678   // If we overran the argument save area, we must use memory
3679   // (this check catches arguments passed partially in memory)
3680   if (ArgOffset > LinkageSize + ParamAreaSize)
3681     UseMemory = true;
3682 
3683   // However, if the argument is actually passed in an FPR or a VR,
3684   // we don't use memory after all.
3685   if (!Flags.isByVal()) {
3686     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3687       if (AvailableFPRs > 0) {
3688         --AvailableFPRs;
3689         return false;
3690       }
3691     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3692         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3693         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3694         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3695       if (AvailableVRs > 0) {
3696         --AvailableVRs;
3697         return false;
3698       }
3699   }
3700 
3701   return UseMemory;
3702 }
3703 
3704 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3705 /// ensure minimum alignment required for target.
3706 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3707                                      unsigned NumBytes) {
3708   return alignTo(NumBytes, Lowering->getStackAlign());
3709 }
3710 
3711 SDValue PPCTargetLowering::LowerFormalArguments(
3712     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3713     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3714     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3715   if (Subtarget.isAIXABI())
3716     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3717                                     InVals);
3718   if (Subtarget.is64BitELFABI())
3719     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3720                                        InVals);
3721   assert(Subtarget.is32BitELFABI());
3722   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3723                                      InVals);
3724 }
3725 
3726 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3727     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3728     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3729     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3730 
3731   // 32-bit SVR4 ABI Stack Frame Layout:
3732   //              +-----------------------------------+
3733   //        +-->  |            Back chain             |
3734   //        |     +-----------------------------------+
3735   //        |     | Floating-point register save area |
3736   //        |     +-----------------------------------+
3737   //        |     |    General register save area     |
3738   //        |     +-----------------------------------+
3739   //        |     |          CR save word             |
3740   //        |     +-----------------------------------+
3741   //        |     |         VRSAVE save word          |
3742   //        |     +-----------------------------------+
3743   //        |     |         Alignment padding         |
3744   //        |     +-----------------------------------+
3745   //        |     |     Vector register save area     |
3746   //        |     +-----------------------------------+
3747   //        |     |       Local variable space        |
3748   //        |     +-----------------------------------+
3749   //        |     |        Parameter list area        |
3750   //        |     +-----------------------------------+
3751   //        |     |           LR save word            |
3752   //        |     +-----------------------------------+
3753   // SP-->  +---  |            Back chain             |
3754   //              +-----------------------------------+
3755   //
3756   // Specifications:
3757   //   System V Application Binary Interface PowerPC Processor Supplement
3758   //   AltiVec Technology Programming Interface Manual
3759 
3760   MachineFunction &MF = DAG.getMachineFunction();
3761   MachineFrameInfo &MFI = MF.getFrameInfo();
3762   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3763 
3764   EVT PtrVT = getPointerTy(MF.getDataLayout());
3765   // Potential tail calls could cause overwriting of argument stack slots.
3766   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3767                        (CallConv == CallingConv::Fast));
3768   const Align PtrAlign(4);
3769 
3770   // Assign locations to all of the incoming arguments.
3771   SmallVector<CCValAssign, 16> ArgLocs;
3772   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3773                  *DAG.getContext());
3774 
3775   // Reserve space for the linkage area on the stack.
3776   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3777   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3778   if (useSoftFloat())
3779     CCInfo.PreAnalyzeFormalArguments(Ins);
3780 
3781   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3782   CCInfo.clearWasPPCF128();
3783 
3784   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3785     CCValAssign &VA = ArgLocs[i];
3786 
3787     // Arguments stored in registers.
3788     if (VA.isRegLoc()) {
3789       const TargetRegisterClass *RC;
3790       EVT ValVT = VA.getValVT();
3791 
3792       switch (ValVT.getSimpleVT().SimpleTy) {
3793         default:
3794           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3795         case MVT::i1:
3796         case MVT::i32:
3797           RC = &PPC::GPRCRegClass;
3798           break;
3799         case MVT::f32:
3800           if (Subtarget.hasP8Vector())
3801             RC = &PPC::VSSRCRegClass;
3802           else if (Subtarget.hasSPE())
3803             RC = &PPC::GPRCRegClass;
3804           else
3805             RC = &PPC::F4RCRegClass;
3806           break;
3807         case MVT::f64:
3808           if (Subtarget.hasVSX())
3809             RC = &PPC::VSFRCRegClass;
3810           else if (Subtarget.hasSPE())
3811             // SPE passes doubles in GPR pairs.
3812             RC = &PPC::GPRCRegClass;
3813           else
3814             RC = &PPC::F8RCRegClass;
3815           break;
3816         case MVT::v16i8:
3817         case MVT::v8i16:
3818         case MVT::v4i32:
3819           RC = &PPC::VRRCRegClass;
3820           break;
3821         case MVT::v4f32:
3822           RC = &PPC::VRRCRegClass;
3823           break;
3824         case MVT::v2f64:
3825         case MVT::v2i64:
3826           RC = &PPC::VRRCRegClass;
3827           break;
3828       }
3829 
3830       SDValue ArgValue;
3831       // Transform the arguments stored in physical registers into
3832       // virtual ones.
3833       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3834         assert(i + 1 < e && "No second half of double precision argument");
3835         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3836         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3837         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3838         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3839         if (!Subtarget.isLittleEndian())
3840           std::swap (ArgValueLo, ArgValueHi);
3841         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3842                                ArgValueHi);
3843       } else {
3844         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3845         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3846                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3847         if (ValVT == MVT::i1)
3848           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3849       }
3850 
3851       InVals.push_back(ArgValue);
3852     } else {
3853       // Argument stored in memory.
3854       assert(VA.isMemLoc());
3855 
3856       // Get the extended size of the argument type in stack
3857       unsigned ArgSize = VA.getLocVT().getStoreSize();
3858       // Get the actual size of the argument type
3859       unsigned ObjSize = VA.getValVT().getStoreSize();
3860       unsigned ArgOffset = VA.getLocMemOffset();
3861       // Stack objects in PPC32 are right justified.
3862       ArgOffset += ArgSize - ObjSize;
3863       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3864 
3865       // Create load nodes to retrieve arguments from the stack.
3866       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3867       InVals.push_back(
3868           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3869     }
3870   }
3871 
3872   // Assign locations to all of the incoming aggregate by value arguments.
3873   // Aggregates passed by value are stored in the local variable space of the
3874   // caller's stack frame, right above the parameter list area.
3875   SmallVector<CCValAssign, 16> ByValArgLocs;
3876   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3877                       ByValArgLocs, *DAG.getContext());
3878 
3879   // Reserve stack space for the allocations in CCInfo.
3880   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3881 
3882   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3883 
3884   // Area that is at least reserved in the caller of this function.
3885   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3886   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3887 
3888   // Set the size that is at least reserved in caller of this function.  Tail
3889   // call optimized function's reserved stack space needs to be aligned so that
3890   // taking the difference between two stack areas will result in an aligned
3891   // stack.
3892   MinReservedArea =
3893       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3894   FuncInfo->setMinReservedArea(MinReservedArea);
3895 
3896   SmallVector<SDValue, 8> MemOps;
3897 
3898   // If the function takes variable number of arguments, make a frame index for
3899   // the start of the first vararg value... for expansion of llvm.va_start.
3900   if (isVarArg) {
3901     static const MCPhysReg GPArgRegs[] = {
3902       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3903       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3904     };
3905     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3906 
3907     static const MCPhysReg FPArgRegs[] = {
3908       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3909       PPC::F8
3910     };
3911     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3912 
3913     if (useSoftFloat() || hasSPE())
3914        NumFPArgRegs = 0;
3915 
3916     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3917     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3918 
3919     // Make room for NumGPArgRegs and NumFPArgRegs.
3920     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3921                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3922 
3923     FuncInfo->setVarArgsStackOffset(
3924       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3925                             CCInfo.getNextStackOffset(), true));
3926 
3927     FuncInfo->setVarArgsFrameIndex(
3928         MFI.CreateStackObject(Depth, Align(8), false));
3929     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3930 
3931     // The fixed integer arguments of a variadic function are stored to the
3932     // VarArgsFrameIndex on the stack so that they may be loaded by
3933     // dereferencing the result of va_next.
3934     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3935       // Get an existing live-in vreg, or add a new one.
3936       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3937       if (!VReg)
3938         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3939 
3940       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3941       SDValue Store =
3942           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3943       MemOps.push_back(Store);
3944       // Increment the address by four for the next argument to store
3945       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3946       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3947     }
3948 
3949     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3950     // is set.
3951     // The double arguments are stored to the VarArgsFrameIndex
3952     // on the stack.
3953     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3954       // Get an existing live-in vreg, or add a new one.
3955       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3956       if (!VReg)
3957         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3958 
3959       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3960       SDValue Store =
3961           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3962       MemOps.push_back(Store);
3963       // Increment the address by eight for the next argument to store
3964       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3965                                          PtrVT);
3966       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3967     }
3968   }
3969 
3970   if (!MemOps.empty())
3971     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3972 
3973   return Chain;
3974 }
3975 
3976 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3977 // value to MVT::i64 and then truncate to the correct register size.
3978 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3979                                              EVT ObjectVT, SelectionDAG &DAG,
3980                                              SDValue ArgVal,
3981                                              const SDLoc &dl) const {
3982   if (Flags.isSExt())
3983     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3984                          DAG.getValueType(ObjectVT));
3985   else if (Flags.isZExt())
3986     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3987                          DAG.getValueType(ObjectVT));
3988 
3989   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3990 }
3991 
3992 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3993     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3994     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3995     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3996   // TODO: add description of PPC stack frame format, or at least some docs.
3997   //
3998   bool isELFv2ABI = Subtarget.isELFv2ABI();
3999   bool isLittleEndian = Subtarget.isLittleEndian();
4000   MachineFunction &MF = DAG.getMachineFunction();
4001   MachineFrameInfo &MFI = MF.getFrameInfo();
4002   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4003 
4004   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4005          "fastcc not supported on varargs functions");
4006 
4007   EVT PtrVT = getPointerTy(MF.getDataLayout());
4008   // Potential tail calls could cause overwriting of argument stack slots.
4009   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4010                        (CallConv == CallingConv::Fast));
4011   unsigned PtrByteSize = 8;
4012   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4013 
4014   static const MCPhysReg GPR[] = {
4015     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4016     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4017   };
4018   static const MCPhysReg VR[] = {
4019     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4020     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4021   };
4022 
4023   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4024   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4025   const unsigned Num_VR_Regs  = array_lengthof(VR);
4026 
4027   // Do a first pass over the arguments to determine whether the ABI
4028   // guarantees that our caller has allocated the parameter save area
4029   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4030   // in the ELFv2 ABI, it is true if this is a vararg function or if
4031   // any parameter is located in a stack slot.
4032 
4033   bool HasParameterArea = !isELFv2ABI || isVarArg;
4034   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4035   unsigned NumBytes = LinkageSize;
4036   unsigned AvailableFPRs = Num_FPR_Regs;
4037   unsigned AvailableVRs = Num_VR_Regs;
4038   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4039     if (Ins[i].Flags.isNest())
4040       continue;
4041 
4042     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4043                                PtrByteSize, LinkageSize, ParamAreaSize,
4044                                NumBytes, AvailableFPRs, AvailableVRs))
4045       HasParameterArea = true;
4046   }
4047 
4048   // Add DAG nodes to load the arguments or copy them out of registers.  On
4049   // entry to a function on PPC, the arguments start after the linkage area,
4050   // although the first ones are often in registers.
4051 
4052   unsigned ArgOffset = LinkageSize;
4053   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4054   SmallVector<SDValue, 8> MemOps;
4055   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4056   unsigned CurArgIdx = 0;
4057   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4058     SDValue ArgVal;
4059     bool needsLoad = false;
4060     EVT ObjectVT = Ins[ArgNo].VT;
4061     EVT OrigVT = Ins[ArgNo].ArgVT;
4062     unsigned ObjSize = ObjectVT.getStoreSize();
4063     unsigned ArgSize = ObjSize;
4064     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4065     if (Ins[ArgNo].isOrigArg()) {
4066       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4067       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4068     }
4069     // We re-align the argument offset for each argument, except when using the
4070     // fast calling convention, when we need to make sure we do that only when
4071     // we'll actually use a stack slot.
4072     unsigned CurArgOffset;
4073     Align Alignment;
4074     auto ComputeArgOffset = [&]() {
4075       /* Respect alignment of argument on the stack.  */
4076       Alignment =
4077           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4078       ArgOffset = alignTo(ArgOffset, Alignment);
4079       CurArgOffset = ArgOffset;
4080     };
4081 
4082     if (CallConv != CallingConv::Fast) {
4083       ComputeArgOffset();
4084 
4085       /* Compute GPR index associated with argument offset.  */
4086       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4087       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4088     }
4089 
4090     // FIXME the codegen can be much improved in some cases.
4091     // We do not have to keep everything in memory.
4092     if (Flags.isByVal()) {
4093       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4094 
4095       if (CallConv == CallingConv::Fast)
4096         ComputeArgOffset();
4097 
4098       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4099       ObjSize = Flags.getByValSize();
4100       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4101       // Empty aggregate parameters do not take up registers.  Examples:
4102       //   struct { } a;
4103       //   union  { } b;
4104       //   int c[0];
4105       // etc.  However, we have to provide a place-holder in InVals, so
4106       // pretend we have an 8-byte item at the current address for that
4107       // purpose.
4108       if (!ObjSize) {
4109         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4110         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4111         InVals.push_back(FIN);
4112         continue;
4113       }
4114 
4115       // Create a stack object covering all stack doublewords occupied
4116       // by the argument.  If the argument is (fully or partially) on
4117       // the stack, or if the argument is fully in registers but the
4118       // caller has allocated the parameter save anyway, we can refer
4119       // directly to the caller's stack frame.  Otherwise, create a
4120       // local copy in our own frame.
4121       int FI;
4122       if (HasParameterArea ||
4123           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4124         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4125       else
4126         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4127       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4128 
4129       // Handle aggregates smaller than 8 bytes.
4130       if (ObjSize < PtrByteSize) {
4131         // The value of the object is its address, which differs from the
4132         // address of the enclosing doubleword on big-endian systems.
4133         SDValue Arg = FIN;
4134         if (!isLittleEndian) {
4135           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4136           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4137         }
4138         InVals.push_back(Arg);
4139 
4140         if (GPR_idx != Num_GPR_Regs) {
4141           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4142           FuncInfo->addLiveInAttr(VReg, Flags);
4143           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4144           SDValue Store;
4145 
4146           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4147             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4148                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4149             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4150                                       MachinePointerInfo(&*FuncArg), ObjType);
4151           } else {
4152             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4153             // store the whole register as-is to the parameter save area
4154             // slot.
4155             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4156                                  MachinePointerInfo(&*FuncArg));
4157           }
4158 
4159           MemOps.push_back(Store);
4160         }
4161         // Whether we copied from a register or not, advance the offset
4162         // into the parameter save area by a full doubleword.
4163         ArgOffset += PtrByteSize;
4164         continue;
4165       }
4166 
4167       // The value of the object is its address, which is the address of
4168       // its first stack doubleword.
4169       InVals.push_back(FIN);
4170 
4171       // Store whatever pieces of the object are in registers to memory.
4172       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4173         if (GPR_idx == Num_GPR_Regs)
4174           break;
4175 
4176         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4177         FuncInfo->addLiveInAttr(VReg, Flags);
4178         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4179         SDValue Addr = FIN;
4180         if (j) {
4181           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4182           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4183         }
4184         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4185                                      MachinePointerInfo(&*FuncArg, j));
4186         MemOps.push_back(Store);
4187         ++GPR_idx;
4188       }
4189       ArgOffset += ArgSize;
4190       continue;
4191     }
4192 
4193     switch (ObjectVT.getSimpleVT().SimpleTy) {
4194     default: llvm_unreachable("Unhandled argument type!");
4195     case MVT::i1:
4196     case MVT::i32:
4197     case MVT::i64:
4198       if (Flags.isNest()) {
4199         // The 'nest' parameter, if any, is passed in R11.
4200         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4201         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4202 
4203         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4204           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4205 
4206         break;
4207       }
4208 
4209       // These can be scalar arguments or elements of an integer array type
4210       // passed directly.  Clang may use those instead of "byval" aggregate
4211       // types to avoid forcing arguments to memory unnecessarily.
4212       if (GPR_idx != Num_GPR_Regs) {
4213         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4214         FuncInfo->addLiveInAttr(VReg, Flags);
4215         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4216 
4217         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4218           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4219           // value to MVT::i64 and then truncate to the correct register size.
4220           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4221       } else {
4222         if (CallConv == CallingConv::Fast)
4223           ComputeArgOffset();
4224 
4225         needsLoad = true;
4226         ArgSize = PtrByteSize;
4227       }
4228       if (CallConv != CallingConv::Fast || needsLoad)
4229         ArgOffset += 8;
4230       break;
4231 
4232     case MVT::f32:
4233     case MVT::f64:
4234       // These can be scalar arguments or elements of a float array type
4235       // passed directly.  The latter are used to implement ELFv2 homogenous
4236       // float aggregates.
4237       if (FPR_idx != Num_FPR_Regs) {
4238         unsigned VReg;
4239 
4240         if (ObjectVT == MVT::f32)
4241           VReg = MF.addLiveIn(FPR[FPR_idx],
4242                               Subtarget.hasP8Vector()
4243                                   ? &PPC::VSSRCRegClass
4244                                   : &PPC::F4RCRegClass);
4245         else
4246           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4247                                                 ? &PPC::VSFRCRegClass
4248                                                 : &PPC::F8RCRegClass);
4249 
4250         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4251         ++FPR_idx;
4252       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4253         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4254         // once we support fp <-> gpr moves.
4255 
4256         // This can only ever happen in the presence of f32 array types,
4257         // since otherwise we never run out of FPRs before running out
4258         // of GPRs.
4259         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4260         FuncInfo->addLiveInAttr(VReg, Flags);
4261         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4262 
4263         if (ObjectVT == MVT::f32) {
4264           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4265             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4266                                  DAG.getConstant(32, dl, MVT::i32));
4267           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4268         }
4269 
4270         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4271       } else {
4272         if (CallConv == CallingConv::Fast)
4273           ComputeArgOffset();
4274 
4275         needsLoad = true;
4276       }
4277 
4278       // When passing an array of floats, the array occupies consecutive
4279       // space in the argument area; only round up to the next doubleword
4280       // at the end of the array.  Otherwise, each float takes 8 bytes.
4281       if (CallConv != CallingConv::Fast || needsLoad) {
4282         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4283         ArgOffset += ArgSize;
4284         if (Flags.isInConsecutiveRegsLast())
4285           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4286       }
4287       break;
4288     case MVT::v4f32:
4289     case MVT::v4i32:
4290     case MVT::v8i16:
4291     case MVT::v16i8:
4292     case MVT::v2f64:
4293     case MVT::v2i64:
4294     case MVT::v1i128:
4295     case MVT::f128:
4296       // These can be scalar arguments or elements of a vector array type
4297       // passed directly.  The latter are used to implement ELFv2 homogenous
4298       // vector aggregates.
4299       if (VR_idx != Num_VR_Regs) {
4300         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4301         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4302         ++VR_idx;
4303       } else {
4304         if (CallConv == CallingConv::Fast)
4305           ComputeArgOffset();
4306         needsLoad = true;
4307       }
4308       if (CallConv != CallingConv::Fast || needsLoad)
4309         ArgOffset += 16;
4310       break;
4311     }
4312 
4313     // We need to load the argument to a virtual register if we determined
4314     // above that we ran out of physical registers of the appropriate type.
4315     if (needsLoad) {
4316       if (ObjSize < ArgSize && !isLittleEndian)
4317         CurArgOffset += ArgSize - ObjSize;
4318       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4319       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4320       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4321     }
4322 
4323     InVals.push_back(ArgVal);
4324   }
4325 
4326   // Area that is at least reserved in the caller of this function.
4327   unsigned MinReservedArea;
4328   if (HasParameterArea)
4329     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4330   else
4331     MinReservedArea = LinkageSize;
4332 
4333   // Set the size that is at least reserved in caller of this function.  Tail
4334   // call optimized functions' reserved stack space needs to be aligned so that
4335   // taking the difference between two stack areas will result in an aligned
4336   // stack.
4337   MinReservedArea =
4338       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4339   FuncInfo->setMinReservedArea(MinReservedArea);
4340 
4341   // If the function takes variable number of arguments, make a frame index for
4342   // the start of the first vararg value... for expansion of llvm.va_start.
4343   // On ELFv2ABI spec, it writes:
4344   // C programs that are intended to be *portable* across different compilers
4345   // and architectures must use the header file <stdarg.h> to deal with variable
4346   // argument lists.
4347   if (isVarArg && MFI.hasVAStart()) {
4348     int Depth = ArgOffset;
4349 
4350     FuncInfo->setVarArgsFrameIndex(
4351       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4352     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4353 
4354     // If this function is vararg, store any remaining integer argument regs
4355     // to their spots on the stack so that they may be loaded by dereferencing
4356     // the result of va_next.
4357     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4358          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4359       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4360       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4361       SDValue Store =
4362           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4363       MemOps.push_back(Store);
4364       // Increment the address by four for the next argument to store
4365       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4366       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4367     }
4368   }
4369 
4370   if (!MemOps.empty())
4371     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4372 
4373   return Chain;
4374 }
4375 
4376 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4377 /// adjusted to accommodate the arguments for the tailcall.
4378 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4379                                    unsigned ParamSize) {
4380 
4381   if (!isTailCall) return 0;
4382 
4383   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4384   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4385   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4386   // Remember only if the new adjustment is bigger.
4387   if (SPDiff < FI->getTailCallSPDelta())
4388     FI->setTailCallSPDelta(SPDiff);
4389 
4390   return SPDiff;
4391 }
4392 
4393 static bool isFunctionGlobalAddress(SDValue Callee);
4394 
4395 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4396                               const TargetMachine &TM) {
4397   // It does not make sense to call callsShareTOCBase() with a caller that
4398   // is PC Relative since PC Relative callers do not have a TOC.
4399 #ifndef NDEBUG
4400   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4401   assert(!STICaller->isUsingPCRelativeCalls() &&
4402          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4403 #endif
4404 
4405   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4406   // don't have enough information to determine if the caller and callee share
4407   // the same  TOC base, so we have to pessimistically assume they don't for
4408   // correctness.
4409   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4410   if (!G)
4411     return false;
4412 
4413   const GlobalValue *GV = G->getGlobal();
4414 
4415   // If the callee is preemptable, then the static linker will use a plt-stub
4416   // which saves the toc to the stack, and needs a nop after the call
4417   // instruction to convert to a toc-restore.
4418   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4419     return false;
4420 
4421   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4422   // We may need a TOC restore in the situation where the caller requires a
4423   // valid TOC but the callee is PC Relative and does not.
4424   const Function *F = dyn_cast<Function>(GV);
4425   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4426 
4427   // If we have an Alias we can try to get the function from there.
4428   if (Alias) {
4429     const GlobalObject *GlobalObj = Alias->getBaseObject();
4430     F = dyn_cast<Function>(GlobalObj);
4431   }
4432 
4433   // If we still have no valid function pointer we do not have enough
4434   // information to determine if the callee uses PC Relative calls so we must
4435   // assume that it does.
4436   if (!F)
4437     return false;
4438 
4439   // If the callee uses PC Relative we cannot guarantee that the callee won't
4440   // clobber the TOC of the caller and so we must assume that the two
4441   // functions do not share a TOC base.
4442   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4443   if (STICallee->isUsingPCRelativeCalls())
4444     return false;
4445 
4446   // If the GV is not a strong definition then we need to assume it can be
4447   // replaced by another function at link time. The function that replaces
4448   // it may not share the same TOC as the caller since the callee may be
4449   // replaced by a PC Relative version of the same function.
4450   if (!GV->isStrongDefinitionForLinker())
4451     return false;
4452 
4453   // The medium and large code models are expected to provide a sufficiently
4454   // large TOC to provide all data addressing needs of a module with a
4455   // single TOC.
4456   if (CodeModel::Medium == TM.getCodeModel() ||
4457       CodeModel::Large == TM.getCodeModel())
4458     return true;
4459 
4460   // Any explicitly-specified sections and section prefixes must also match.
4461   // Also, if we're using -ffunction-sections, then each function is always in
4462   // a different section (the same is true for COMDAT functions).
4463   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4464       GV->getSection() != Caller->getSection())
4465     return false;
4466   if (const auto *F = dyn_cast<Function>(GV)) {
4467     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4468       return false;
4469   }
4470 
4471   return true;
4472 }
4473 
4474 static bool
4475 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4476                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4477   assert(Subtarget.is64BitELFABI());
4478 
4479   const unsigned PtrByteSize = 8;
4480   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4481 
4482   static const MCPhysReg GPR[] = {
4483     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4484     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4485   };
4486   static const MCPhysReg VR[] = {
4487     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4488     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4489   };
4490 
4491   const unsigned NumGPRs = array_lengthof(GPR);
4492   const unsigned NumFPRs = 13;
4493   const unsigned NumVRs = array_lengthof(VR);
4494   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4495 
4496   unsigned NumBytes = LinkageSize;
4497   unsigned AvailableFPRs = NumFPRs;
4498   unsigned AvailableVRs = NumVRs;
4499 
4500   for (const ISD::OutputArg& Param : Outs) {
4501     if (Param.Flags.isNest()) continue;
4502 
4503     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4504                                LinkageSize, ParamAreaSize, NumBytes,
4505                                AvailableFPRs, AvailableVRs))
4506       return true;
4507   }
4508   return false;
4509 }
4510 
4511 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4512   if (CB.arg_size() != CallerFn->arg_size())
4513     return false;
4514 
4515   auto CalleeArgIter = CB.arg_begin();
4516   auto CalleeArgEnd = CB.arg_end();
4517   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4518 
4519   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4520     const Value* CalleeArg = *CalleeArgIter;
4521     const Value* CallerArg = &(*CallerArgIter);
4522     if (CalleeArg == CallerArg)
4523       continue;
4524 
4525     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4526     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4527     //      }
4528     // 1st argument of callee is undef and has the same type as caller.
4529     if (CalleeArg->getType() == CallerArg->getType() &&
4530         isa<UndefValue>(CalleeArg))
4531       continue;
4532 
4533     return false;
4534   }
4535 
4536   return true;
4537 }
4538 
4539 // Returns true if TCO is possible between the callers and callees
4540 // calling conventions.
4541 static bool
4542 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4543                                     CallingConv::ID CalleeCC) {
4544   // Tail calls are possible with fastcc and ccc.
4545   auto isTailCallableCC  = [] (CallingConv::ID CC){
4546       return  CC == CallingConv::C || CC == CallingConv::Fast;
4547   };
4548   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4549     return false;
4550 
4551   // We can safely tail call both fastcc and ccc callees from a c calling
4552   // convention caller. If the caller is fastcc, we may have less stack space
4553   // than a non-fastcc caller with the same signature so disable tail-calls in
4554   // that case.
4555   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4556 }
4557 
4558 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4559     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4560     const SmallVectorImpl<ISD::OutputArg> &Outs,
4561     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4562   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4563 
4564   if (DisableSCO && !TailCallOpt) return false;
4565 
4566   // Variadic argument functions are not supported.
4567   if (isVarArg) return false;
4568 
4569   auto &Caller = DAG.getMachineFunction().getFunction();
4570   // Check that the calling conventions are compatible for tco.
4571   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4572     return false;
4573 
4574   // Caller contains any byval parameter is not supported.
4575   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4576     return false;
4577 
4578   // Callee contains any byval parameter is not supported, too.
4579   // Note: This is a quick work around, because in some cases, e.g.
4580   // caller's stack size > callee's stack size, we are still able to apply
4581   // sibling call optimization. For example, gcc is able to do SCO for caller1
4582   // in the following example, but not for caller2.
4583   //   struct test {
4584   //     long int a;
4585   //     char ary[56];
4586   //   } gTest;
4587   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4588   //     b->a = v.a;
4589   //     return 0;
4590   //   }
4591   //   void caller1(struct test a, struct test c, struct test *b) {
4592   //     callee(gTest, b); }
4593   //   void caller2(struct test *b) { callee(gTest, b); }
4594   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4595     return false;
4596 
4597   // If callee and caller use different calling conventions, we cannot pass
4598   // parameters on stack since offsets for the parameter area may be different.
4599   if (Caller.getCallingConv() != CalleeCC &&
4600       needStackSlotPassParameters(Subtarget, Outs))
4601     return false;
4602 
4603   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4604   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4605   // callee potentially have different TOC bases then we cannot tail call since
4606   // we need to restore the TOC pointer after the call.
4607   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4608   // We cannot guarantee this for indirect calls or calls to external functions.
4609   // When PC-Relative addressing is used, the concept of the TOC is no longer
4610   // applicable so this check is not required.
4611   // Check first for indirect calls.
4612   if (!Subtarget.isUsingPCRelativeCalls() &&
4613       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4614     return false;
4615 
4616   // Check if we share the TOC base.
4617   if (!Subtarget.isUsingPCRelativeCalls() &&
4618       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4619     return false;
4620 
4621   // TCO allows altering callee ABI, so we don't have to check further.
4622   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4623     return true;
4624 
4625   if (DisableSCO) return false;
4626 
4627   // If callee use the same argument list that caller is using, then we can
4628   // apply SCO on this case. If it is not, then we need to check if callee needs
4629   // stack for passing arguments.
4630   // PC Relative tail calls may not have a CallBase.
4631   // If there is no CallBase we cannot verify if we have the same argument
4632   // list so assume that we don't have the same argument list.
4633   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4634       needStackSlotPassParameters(Subtarget, Outs))
4635     return false;
4636   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4637     return false;
4638 
4639   return true;
4640 }
4641 
4642 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4643 /// for tail call optimization. Targets which want to do tail call
4644 /// optimization should implement this function.
4645 bool
4646 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4647                                                      CallingConv::ID CalleeCC,
4648                                                      bool isVarArg,
4649                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4650                                                      SelectionDAG& DAG) const {
4651   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4652     return false;
4653 
4654   // Variable argument functions are not supported.
4655   if (isVarArg)
4656     return false;
4657 
4658   MachineFunction &MF = DAG.getMachineFunction();
4659   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4660   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4661     // Functions containing by val parameters are not supported.
4662     for (unsigned i = 0; i != Ins.size(); i++) {
4663        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4664        if (Flags.isByVal()) return false;
4665     }
4666 
4667     // Non-PIC/GOT tail calls are supported.
4668     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4669       return true;
4670 
4671     // At the moment we can only do local tail calls (in same module, hidden
4672     // or protected) if we are generating PIC.
4673     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4674       return G->getGlobal()->hasHiddenVisibility()
4675           || G->getGlobal()->hasProtectedVisibility();
4676   }
4677 
4678   return false;
4679 }
4680 
4681 /// isCallCompatibleAddress - Return the immediate to use if the specified
4682 /// 32-bit value is representable in the immediate field of a BxA instruction.
4683 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4684   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4685   if (!C) return nullptr;
4686 
4687   int Addr = C->getZExtValue();
4688   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4689       SignExtend32<26>(Addr) != Addr)
4690     return nullptr;  // Top 6 bits have to be sext of immediate.
4691 
4692   return DAG
4693       .getConstant(
4694           (int)C->getZExtValue() >> 2, SDLoc(Op),
4695           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4696       .getNode();
4697 }
4698 
4699 namespace {
4700 
4701 struct TailCallArgumentInfo {
4702   SDValue Arg;
4703   SDValue FrameIdxOp;
4704   int FrameIdx = 0;
4705 
4706   TailCallArgumentInfo() = default;
4707 };
4708 
4709 } // end anonymous namespace
4710 
4711 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4712 static void StoreTailCallArgumentsToStackSlot(
4713     SelectionDAG &DAG, SDValue Chain,
4714     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4715     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4716   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4717     SDValue Arg = TailCallArgs[i].Arg;
4718     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4719     int FI = TailCallArgs[i].FrameIdx;
4720     // Store relative to framepointer.
4721     MemOpChains.push_back(DAG.getStore(
4722         Chain, dl, Arg, FIN,
4723         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4724   }
4725 }
4726 
4727 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4728 /// the appropriate stack slot for the tail call optimized function call.
4729 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4730                                              SDValue OldRetAddr, SDValue OldFP,
4731                                              int SPDiff, const SDLoc &dl) {
4732   if (SPDiff) {
4733     // Calculate the new stack slot for the return address.
4734     MachineFunction &MF = DAG.getMachineFunction();
4735     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4736     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4737     bool isPPC64 = Subtarget.isPPC64();
4738     int SlotSize = isPPC64 ? 8 : 4;
4739     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4740     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4741                                                          NewRetAddrLoc, true);
4742     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4743     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4744     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4745                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4746   }
4747   return Chain;
4748 }
4749 
4750 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4751 /// the position of the argument.
4752 static void
4753 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4754                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4755                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4756   int Offset = ArgOffset + SPDiff;
4757   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4758   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4759   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4760   SDValue FIN = DAG.getFrameIndex(FI, VT);
4761   TailCallArgumentInfo Info;
4762   Info.Arg = Arg;
4763   Info.FrameIdxOp = FIN;
4764   Info.FrameIdx = FI;
4765   TailCallArguments.push_back(Info);
4766 }
4767 
4768 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4769 /// stack slot. Returns the chain as result and the loaded frame pointers in
4770 /// LROpOut/FPOpout. Used when tail calling.
4771 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4772     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4773     SDValue &FPOpOut, const SDLoc &dl) const {
4774   if (SPDiff) {
4775     // Load the LR and FP stack slot for later adjusting.
4776     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4777     LROpOut = getReturnAddrFrameIndex(DAG);
4778     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4779     Chain = SDValue(LROpOut.getNode(), 1);
4780   }
4781   return Chain;
4782 }
4783 
4784 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4785 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4786 /// specified by the specific parameter attribute. The copy will be passed as
4787 /// a byval function parameter.
4788 /// Sometimes what we are copying is the end of a larger object, the part that
4789 /// does not fit in registers.
4790 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4791                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4792                                          SelectionDAG &DAG, const SDLoc &dl) {
4793   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4794   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4795                        Flags.getNonZeroByValAlign(), false, false, false,
4796                        MachinePointerInfo(), MachinePointerInfo());
4797 }
4798 
4799 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4800 /// tail calls.
4801 static void LowerMemOpCallTo(
4802     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4803     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4804     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4805     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4806   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4807   if (!isTailCall) {
4808     if (isVector) {
4809       SDValue StackPtr;
4810       if (isPPC64)
4811         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4812       else
4813         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4814       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4815                            DAG.getConstant(ArgOffset, dl, PtrVT));
4816     }
4817     MemOpChains.push_back(
4818         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4819     // Calculate and remember argument location.
4820   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4821                                   TailCallArguments);
4822 }
4823 
4824 static void
4825 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4826                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4827                 SDValue FPOp,
4828                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4829   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4830   // might overwrite each other in case of tail call optimization.
4831   SmallVector<SDValue, 8> MemOpChains2;
4832   // Do not flag preceding copytoreg stuff together with the following stuff.
4833   InFlag = SDValue();
4834   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4835                                     MemOpChains2, dl);
4836   if (!MemOpChains2.empty())
4837     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4838 
4839   // Store the return address to the appropriate stack slot.
4840   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4841 
4842   // Emit callseq_end just before tailcall node.
4843   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4844                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4845   InFlag = Chain.getValue(1);
4846 }
4847 
4848 // Is this global address that of a function that can be called by name? (as
4849 // opposed to something that must hold a descriptor for an indirect call).
4850 static bool isFunctionGlobalAddress(SDValue Callee) {
4851   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4852     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4853         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4854       return false;
4855 
4856     return G->getGlobal()->getValueType()->isFunctionTy();
4857   }
4858 
4859   return false;
4860 }
4861 
4862 SDValue PPCTargetLowering::LowerCallResult(
4863     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4864     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4865     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4866   SmallVector<CCValAssign, 16> RVLocs;
4867   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4868                     *DAG.getContext());
4869 
4870   CCRetInfo.AnalyzeCallResult(
4871       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4872                ? RetCC_PPC_Cold
4873                : RetCC_PPC);
4874 
4875   // Copy all of the result registers out of their specified physreg.
4876   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4877     CCValAssign &VA = RVLocs[i];
4878     assert(VA.isRegLoc() && "Can only return in registers!");
4879 
4880     SDValue Val;
4881 
4882     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4883       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4884                                       InFlag);
4885       Chain = Lo.getValue(1);
4886       InFlag = Lo.getValue(2);
4887       VA = RVLocs[++i]; // skip ahead to next loc
4888       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4889                                       InFlag);
4890       Chain = Hi.getValue(1);
4891       InFlag = Hi.getValue(2);
4892       if (!Subtarget.isLittleEndian())
4893         std::swap (Lo, Hi);
4894       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4895     } else {
4896       Val = DAG.getCopyFromReg(Chain, dl,
4897                                VA.getLocReg(), VA.getLocVT(), InFlag);
4898       Chain = Val.getValue(1);
4899       InFlag = Val.getValue(2);
4900     }
4901 
4902     switch (VA.getLocInfo()) {
4903     default: llvm_unreachable("Unknown loc info!");
4904     case CCValAssign::Full: break;
4905     case CCValAssign::AExt:
4906       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4907       break;
4908     case CCValAssign::ZExt:
4909       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4910                         DAG.getValueType(VA.getValVT()));
4911       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4912       break;
4913     case CCValAssign::SExt:
4914       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4915                         DAG.getValueType(VA.getValVT()));
4916       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4917       break;
4918     }
4919 
4920     InVals.push_back(Val);
4921   }
4922 
4923   return Chain;
4924 }
4925 
4926 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
4927                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
4928   // PatchPoint calls are not indirect.
4929   if (isPatchPoint)
4930     return false;
4931 
4932   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
4933     return false;
4934 
4935   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
4936   // becuase the immediate function pointer points to a descriptor instead of
4937   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
4938   // pointer immediate points to the global entry point, while the BLA would
4939   // need to jump to the local entry point (see rL211174).
4940   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
4941       isBLACompatibleAddress(Callee, DAG))
4942     return false;
4943 
4944   return true;
4945 }
4946 
4947 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
4948 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
4949   return Subtarget.isAIXABI() ||
4950          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
4951 }
4952 
4953 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
4954                               const Function &Caller,
4955                               const SDValue &Callee,
4956                               const PPCSubtarget &Subtarget,
4957                               const TargetMachine &TM) {
4958   if (CFlags.IsTailCall)
4959     return PPCISD::TC_RETURN;
4960 
4961   // This is a call through a function pointer.
4962   if (CFlags.IsIndirect) {
4963     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
4964     // indirect calls. The save of the caller's TOC pointer to the stack will be
4965     // inserted into the DAG as part of call lowering. The restore of the TOC
4966     // pointer is modeled by using a pseudo instruction for the call opcode that
4967     // represents the 2 instruction sequence of an indirect branch and link,
4968     // immediately followed by a load of the TOC pointer from the the stack save
4969     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
4970     // as it is not saved or used.
4971     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
4972                                                : PPCISD::BCTRL;
4973   }
4974 
4975   if (Subtarget.isUsingPCRelativeCalls()) {
4976     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
4977     return PPCISD::CALL_NOTOC;
4978   }
4979 
4980   // The ABIs that maintain a TOC pointer accross calls need to have a nop
4981   // immediately following the call instruction if the caller and callee may
4982   // have different TOC bases. At link time if the linker determines the calls
4983   // may not share a TOC base, the call is redirected to a trampoline inserted
4984   // by the linker. The trampoline will (among other things) save the callers
4985   // TOC pointer at an ABI designated offset in the linkage area and the linker
4986   // will rewrite the nop to be a load of the TOC pointer from the linkage area
4987   // into gpr2.
4988   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
4989     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
4990                                                   : PPCISD::CALL_NOP;
4991 
4992   return PPCISD::CALL;
4993 }
4994 
4995 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
4996                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
4997   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
4998     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
4999       return SDValue(Dest, 0);
5000 
5001   // Returns true if the callee is local, and false otherwise.
5002   auto isLocalCallee = [&]() {
5003     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5004     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5005     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5006 
5007     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5008            !dyn_cast_or_null<GlobalIFunc>(GV);
5009   };
5010 
5011   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5012   // a static relocation model causes some versions of GNU LD (2.17.50, at
5013   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5014   // built with secure-PLT.
5015   bool UsePlt =
5016       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5017       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5018 
5019   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5020     const TargetMachine &TM = Subtarget.getTargetMachine();
5021     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5022     MCSymbolXCOFF *S =
5023         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5024 
5025     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5026     return DAG.getMCSymbol(S, PtrVT);
5027   };
5028 
5029   if (isFunctionGlobalAddress(Callee)) {
5030     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5031 
5032     if (Subtarget.isAIXABI()) {
5033       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5034       return getAIXFuncEntryPointSymbolSDNode(GV);
5035     }
5036     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5037                                       UsePlt ? PPCII::MO_PLT : 0);
5038   }
5039 
5040   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5041     const char *SymName = S->getSymbol();
5042     if (Subtarget.isAIXABI()) {
5043       // If there exists a user-declared function whose name is the same as the
5044       // ExternalSymbol's, then we pick up the user-declared version.
5045       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5046       if (const Function *F =
5047               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5048         return getAIXFuncEntryPointSymbolSDNode(F);
5049 
5050       // On AIX, direct function calls reference the symbol for the function's
5051       // entry point, which is named by prepending a "." before the function's
5052       // C-linkage name. A Qualname is returned here because an external
5053       // function entry point is a csect with XTY_ER property.
5054       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5055         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5056         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5057             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5058             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5059         return Sec->getQualNameSymbol();
5060       };
5061 
5062       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5063     }
5064     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5065                                        UsePlt ? PPCII::MO_PLT : 0);
5066   }
5067 
5068   // No transformation needed.
5069   assert(Callee.getNode() && "What no callee?");
5070   return Callee;
5071 }
5072 
5073 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5074   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5075          "Expected a CALLSEQ_STARTSDNode.");
5076 
5077   // The last operand is the chain, except when the node has glue. If the node
5078   // has glue, then the last operand is the glue, and the chain is the second
5079   // last operand.
5080   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5081   if (LastValue.getValueType() != MVT::Glue)
5082     return LastValue;
5083 
5084   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5085 }
5086 
5087 // Creates the node that moves a functions address into the count register
5088 // to prepare for an indirect call instruction.
5089 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5090                                 SDValue &Glue, SDValue &Chain,
5091                                 const SDLoc &dl) {
5092   SDValue MTCTROps[] = {Chain, Callee, Glue};
5093   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5094   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5095                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5096   // The glue is the second value produced.
5097   Glue = Chain.getValue(1);
5098 }
5099 
5100 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5101                                           SDValue &Glue, SDValue &Chain,
5102                                           SDValue CallSeqStart,
5103                                           const CallBase *CB, const SDLoc &dl,
5104                                           bool hasNest,
5105                                           const PPCSubtarget &Subtarget) {
5106   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5107   // entry point, but to the function descriptor (the function entry point
5108   // address is part of the function descriptor though).
5109   // The function descriptor is a three doubleword structure with the
5110   // following fields: function entry point, TOC base address and
5111   // environment pointer.
5112   // Thus for a call through a function pointer, the following actions need
5113   // to be performed:
5114   //   1. Save the TOC of the caller in the TOC save area of its stack
5115   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5116   //   2. Load the address of the function entry point from the function
5117   //      descriptor.
5118   //   3. Load the TOC of the callee from the function descriptor into r2.
5119   //   4. Load the environment pointer from the function descriptor into
5120   //      r11.
5121   //   5. Branch to the function entry point address.
5122   //   6. On return of the callee, the TOC of the caller needs to be
5123   //      restored (this is done in FinishCall()).
5124   //
5125   // The loads are scheduled at the beginning of the call sequence, and the
5126   // register copies are flagged together to ensure that no other
5127   // operations can be scheduled in between. E.g. without flagging the
5128   // copies together, a TOC access in the caller could be scheduled between
5129   // the assignment of the callee TOC and the branch to the callee, which leads
5130   // to incorrect code.
5131 
5132   // Start by loading the function address from the descriptor.
5133   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5134   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5135                       ? (MachineMemOperand::MODereferenceable |
5136                          MachineMemOperand::MOInvariant)
5137                       : MachineMemOperand::MONone;
5138 
5139   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5140 
5141   // Registers used in building the DAG.
5142   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5143   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5144 
5145   // Offsets of descriptor members.
5146   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5147   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5148 
5149   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5150   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5151 
5152   // One load for the functions entry point address.
5153   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5154                                     Alignment, MMOFlags);
5155 
5156   // One for loading the TOC anchor for the module that contains the called
5157   // function.
5158   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5159   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5160   SDValue TOCPtr =
5161       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5162                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5163 
5164   // One for loading the environment pointer.
5165   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5166   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5167   SDValue LoadEnvPtr =
5168       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5169                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5170 
5171 
5172   // Then copy the newly loaded TOC anchor to the TOC pointer.
5173   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5174   Chain = TOCVal.getValue(0);
5175   Glue = TOCVal.getValue(1);
5176 
5177   // If the function call has an explicit 'nest' parameter, it takes the
5178   // place of the environment pointer.
5179   assert((!hasNest || !Subtarget.isAIXABI()) &&
5180          "Nest parameter is not supported on AIX.");
5181   if (!hasNest) {
5182     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5183     Chain = EnvVal.getValue(0);
5184     Glue = EnvVal.getValue(1);
5185   }
5186 
5187   // The rest of the indirect call sequence is the same as the non-descriptor
5188   // DAG.
5189   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5190 }
5191 
5192 static void
5193 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5194                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5195                   SelectionDAG &DAG,
5196                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5197                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5198                   const PPCSubtarget &Subtarget) {
5199   const bool IsPPC64 = Subtarget.isPPC64();
5200   // MVT for a general purpose register.
5201   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5202 
5203   // First operand is always the chain.
5204   Ops.push_back(Chain);
5205 
5206   // If it's a direct call pass the callee as the second operand.
5207   if (!CFlags.IsIndirect)
5208     Ops.push_back(Callee);
5209   else {
5210     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5211 
5212     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5213     // on the stack (this would have been done in `LowerCall_64SVR4` or
5214     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5215     // represents both the indirect branch and a load that restores the TOC
5216     // pointer from the linkage area. The operand for the TOC restore is an add
5217     // of the TOC save offset to the stack pointer. This must be the second
5218     // operand: after the chain input but before any other variadic arguments.
5219     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5220     // saved or used.
5221     if (isTOCSaveRestoreRequired(Subtarget)) {
5222       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5223 
5224       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5225       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5226       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5227       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5228       Ops.push_back(AddTOC);
5229     }
5230 
5231     // Add the register used for the environment pointer.
5232     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5233       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5234                                     RegVT));
5235 
5236 
5237     // Add CTR register as callee so a bctr can be emitted later.
5238     if (CFlags.IsTailCall)
5239       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5240   }
5241 
5242   // If this is a tail call add stack pointer delta.
5243   if (CFlags.IsTailCall)
5244     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5245 
5246   // Add argument registers to the end of the list so that they are known live
5247   // into the call.
5248   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5249     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5250                                   RegsToPass[i].second.getValueType()));
5251 
5252   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5253   // no way to mark dependencies as implicit here.
5254   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5255   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5256        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5257     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5258 
5259   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5260   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5261     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5262 
5263   // Add a register mask operand representing the call-preserved registers.
5264   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5265   const uint32_t *Mask =
5266       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5267   assert(Mask && "Missing call preserved mask for calling convention");
5268   Ops.push_back(DAG.getRegisterMask(Mask));
5269 
5270   // If the glue is valid, it is the last operand.
5271   if (Glue.getNode())
5272     Ops.push_back(Glue);
5273 }
5274 
5275 SDValue PPCTargetLowering::FinishCall(
5276     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5277     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5278     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5279     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5280     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5281 
5282   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5283       Subtarget.isAIXABI())
5284     setUsesTOCBasePtr(DAG);
5285 
5286   unsigned CallOpc =
5287       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5288                     Subtarget, DAG.getTarget());
5289 
5290   if (!CFlags.IsIndirect)
5291     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5292   else if (Subtarget.usesFunctionDescriptors())
5293     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5294                                   dl, CFlags.HasNest, Subtarget);
5295   else
5296     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5297 
5298   // Build the operand list for the call instruction.
5299   SmallVector<SDValue, 8> Ops;
5300   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5301                     SPDiff, Subtarget);
5302 
5303   // Emit tail call.
5304   if (CFlags.IsTailCall) {
5305     // Indirect tail call when using PC Relative calls do not have the same
5306     // constraints.
5307     assert(((Callee.getOpcode() == ISD::Register &&
5308              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5309             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5310             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5311             isa<ConstantSDNode>(Callee) ||
5312             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5313            "Expecting a global address, external symbol, absolute value, "
5314            "register or an indirect tail call when PC Relative calls are "
5315            "used.");
5316     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5317     assert(CallOpc == PPCISD::TC_RETURN &&
5318            "Unexpected call opcode for a tail call.");
5319     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5320     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5321   }
5322 
5323   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5324   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5325   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5326   Glue = Chain.getValue(1);
5327 
5328   // When performing tail call optimization the callee pops its arguments off
5329   // the stack. Account for this here so these bytes can be pushed back on in
5330   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5331   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5332                          getTargetMachine().Options.GuaranteedTailCallOpt)
5333                             ? NumBytes
5334                             : 0;
5335 
5336   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5337                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5338                              Glue, dl);
5339   Glue = Chain.getValue(1);
5340 
5341   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5342                          DAG, InVals);
5343 }
5344 
5345 SDValue
5346 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5347                              SmallVectorImpl<SDValue> &InVals) const {
5348   SelectionDAG &DAG                     = CLI.DAG;
5349   SDLoc &dl                             = CLI.DL;
5350   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5351   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5352   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5353   SDValue Chain                         = CLI.Chain;
5354   SDValue Callee                        = CLI.Callee;
5355   bool &isTailCall                      = CLI.IsTailCall;
5356   CallingConv::ID CallConv              = CLI.CallConv;
5357   bool isVarArg                         = CLI.IsVarArg;
5358   bool isPatchPoint                     = CLI.IsPatchPoint;
5359   const CallBase *CB                    = CLI.CB;
5360 
5361   if (isTailCall) {
5362     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5363       isTailCall = false;
5364     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5365       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5366           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5367     else
5368       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5369                                                      Ins, DAG);
5370     if (isTailCall) {
5371       ++NumTailCalls;
5372       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5373         ++NumSiblingCalls;
5374 
5375       // PC Relative calls no longer guarantee that the callee is a Global
5376       // Address Node. The callee could be an indirect tail call in which
5377       // case the SDValue for the callee could be a load (to load the address
5378       // of a function pointer) or it may be a register copy (to move the
5379       // address of the callee from a function parameter into a virtual
5380       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5381       assert((Subtarget.isUsingPCRelativeCalls() ||
5382               isa<GlobalAddressSDNode>(Callee)) &&
5383              "Callee should be an llvm::Function object.");
5384 
5385       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5386                         << "\nTCO callee: ");
5387       LLVM_DEBUG(Callee.dump());
5388     }
5389   }
5390 
5391   if (!isTailCall && CB && CB->isMustTailCall())
5392     report_fatal_error("failed to perform tail call elimination on a call "
5393                        "site marked musttail");
5394 
5395   // When long calls (i.e. indirect calls) are always used, calls are always
5396   // made via function pointer. If we have a function name, first translate it
5397   // into a pointer.
5398   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5399       !isTailCall)
5400     Callee = LowerGlobalAddress(Callee, DAG);
5401 
5402   CallFlags CFlags(
5403       CallConv, isTailCall, isVarArg, isPatchPoint,
5404       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5405       // hasNest
5406       Subtarget.is64BitELFABI() &&
5407           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5408       CLI.NoMerge);
5409 
5410   if (Subtarget.isAIXABI())
5411     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5412                          InVals, CB);
5413 
5414   assert(Subtarget.isSVR4ABI());
5415   if (Subtarget.isPPC64())
5416     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5417                             InVals, CB);
5418   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5419                           InVals, CB);
5420 }
5421 
5422 SDValue PPCTargetLowering::LowerCall_32SVR4(
5423     SDValue Chain, SDValue Callee, CallFlags CFlags,
5424     const SmallVectorImpl<ISD::OutputArg> &Outs,
5425     const SmallVectorImpl<SDValue> &OutVals,
5426     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5427     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5428     const CallBase *CB) const {
5429   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5430   // of the 32-bit SVR4 ABI stack frame layout.
5431 
5432   const CallingConv::ID CallConv = CFlags.CallConv;
5433   const bool IsVarArg = CFlags.IsVarArg;
5434   const bool IsTailCall = CFlags.IsTailCall;
5435 
5436   assert((CallConv == CallingConv::C ||
5437           CallConv == CallingConv::Cold ||
5438           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5439 
5440   const Align PtrAlign(4);
5441 
5442   MachineFunction &MF = DAG.getMachineFunction();
5443 
5444   // Mark this function as potentially containing a function that contains a
5445   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5446   // and restoring the callers stack pointer in this functions epilog. This is
5447   // done because by tail calling the called function might overwrite the value
5448   // in this function's (MF) stack pointer stack slot 0(SP).
5449   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5450       CallConv == CallingConv::Fast)
5451     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5452 
5453   // Count how many bytes are to be pushed on the stack, including the linkage
5454   // area, parameter list area and the part of the local variable space which
5455   // contains copies of aggregates which are passed by value.
5456 
5457   // Assign locations to all of the outgoing arguments.
5458   SmallVector<CCValAssign, 16> ArgLocs;
5459   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5460 
5461   // Reserve space for the linkage area on the stack.
5462   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5463                        PtrAlign);
5464   if (useSoftFloat())
5465     CCInfo.PreAnalyzeCallOperands(Outs);
5466 
5467   if (IsVarArg) {
5468     // Handle fixed and variable vector arguments differently.
5469     // Fixed vector arguments go into registers as long as registers are
5470     // available. Variable vector arguments always go into memory.
5471     unsigned NumArgs = Outs.size();
5472 
5473     for (unsigned i = 0; i != NumArgs; ++i) {
5474       MVT ArgVT = Outs[i].VT;
5475       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5476       bool Result;
5477 
5478       if (Outs[i].IsFixed) {
5479         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5480                                CCInfo);
5481       } else {
5482         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5483                                       ArgFlags, CCInfo);
5484       }
5485 
5486       if (Result) {
5487 #ifndef NDEBUG
5488         errs() << "Call operand #" << i << " has unhandled type "
5489              << EVT(ArgVT).getEVTString() << "\n";
5490 #endif
5491         llvm_unreachable(nullptr);
5492       }
5493     }
5494   } else {
5495     // All arguments are treated the same.
5496     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5497   }
5498   CCInfo.clearWasPPCF128();
5499 
5500   // Assign locations to all of the outgoing aggregate by value arguments.
5501   SmallVector<CCValAssign, 16> ByValArgLocs;
5502   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5503 
5504   // Reserve stack space for the allocations in CCInfo.
5505   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5506 
5507   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5508 
5509   // Size of the linkage area, parameter list area and the part of the local
5510   // space variable where copies of aggregates which are passed by value are
5511   // stored.
5512   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5513 
5514   // Calculate by how many bytes the stack has to be adjusted in case of tail
5515   // call optimization.
5516   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5517 
5518   // Adjust the stack pointer for the new arguments...
5519   // These operations are automatically eliminated by the prolog/epilog pass
5520   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5521   SDValue CallSeqStart = Chain;
5522 
5523   // Load the return address and frame pointer so it can be moved somewhere else
5524   // later.
5525   SDValue LROp, FPOp;
5526   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5527 
5528   // Set up a copy of the stack pointer for use loading and storing any
5529   // arguments that may not fit in the registers available for argument
5530   // passing.
5531   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5532 
5533   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5534   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5535   SmallVector<SDValue, 8> MemOpChains;
5536 
5537   bool seenFloatArg = false;
5538   // Walk the register/memloc assignments, inserting copies/loads.
5539   // i - Tracks the index into the list of registers allocated for the call
5540   // RealArgIdx - Tracks the index into the list of actual function arguments
5541   // j - Tracks the index into the list of byval arguments
5542   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5543        i != e;
5544        ++i, ++RealArgIdx) {
5545     CCValAssign &VA = ArgLocs[i];
5546     SDValue Arg = OutVals[RealArgIdx];
5547     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5548 
5549     if (Flags.isByVal()) {
5550       // Argument is an aggregate which is passed by value, thus we need to
5551       // create a copy of it in the local variable space of the current stack
5552       // frame (which is the stack frame of the caller) and pass the address of
5553       // this copy to the callee.
5554       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5555       CCValAssign &ByValVA = ByValArgLocs[j++];
5556       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5557 
5558       // Memory reserved in the local variable space of the callers stack frame.
5559       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5560 
5561       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5562       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5563                            StackPtr, PtrOff);
5564 
5565       // Create a copy of the argument in the local area of the current
5566       // stack frame.
5567       SDValue MemcpyCall =
5568         CreateCopyOfByValArgument(Arg, PtrOff,
5569                                   CallSeqStart.getNode()->getOperand(0),
5570                                   Flags, DAG, dl);
5571 
5572       // This must go outside the CALLSEQ_START..END.
5573       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5574                                                      SDLoc(MemcpyCall));
5575       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5576                              NewCallSeqStart.getNode());
5577       Chain = CallSeqStart = NewCallSeqStart;
5578 
5579       // Pass the address of the aggregate copy on the stack either in a
5580       // physical register or in the parameter list area of the current stack
5581       // frame to the callee.
5582       Arg = PtrOff;
5583     }
5584 
5585     // When useCRBits() is true, there can be i1 arguments.
5586     // It is because getRegisterType(MVT::i1) => MVT::i1,
5587     // and for other integer types getRegisterType() => MVT::i32.
5588     // Extend i1 and ensure callee will get i32.
5589     if (Arg.getValueType() == MVT::i1)
5590       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5591                         dl, MVT::i32, Arg);
5592 
5593     if (VA.isRegLoc()) {
5594       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5595       // Put argument in a physical register.
5596       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5597         bool IsLE = Subtarget.isLittleEndian();
5598         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5599                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5600         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5601         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5602                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5603         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5604                              SVal.getValue(0)));
5605       } else
5606         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5607     } else {
5608       // Put argument in the parameter list area of the current stack frame.
5609       assert(VA.isMemLoc());
5610       unsigned LocMemOffset = VA.getLocMemOffset();
5611 
5612       if (!IsTailCall) {
5613         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5614         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5615                              StackPtr, PtrOff);
5616 
5617         MemOpChains.push_back(
5618             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5619       } else {
5620         // Calculate and remember argument location.
5621         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5622                                  TailCallArguments);
5623       }
5624     }
5625   }
5626 
5627   if (!MemOpChains.empty())
5628     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5629 
5630   // Build a sequence of copy-to-reg nodes chained together with token chain
5631   // and flag operands which copy the outgoing args into the appropriate regs.
5632   SDValue InFlag;
5633   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5634     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5635                              RegsToPass[i].second, InFlag);
5636     InFlag = Chain.getValue(1);
5637   }
5638 
5639   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5640   // registers.
5641   if (IsVarArg) {
5642     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5643     SDValue Ops[] = { Chain, InFlag };
5644 
5645     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5646                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5647 
5648     InFlag = Chain.getValue(1);
5649   }
5650 
5651   if (IsTailCall)
5652     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5653                     TailCallArguments);
5654 
5655   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5656                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5657 }
5658 
5659 // Copy an argument into memory, being careful to do this outside the
5660 // call sequence for the call to which the argument belongs.
5661 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5662     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5663     SelectionDAG &DAG, const SDLoc &dl) const {
5664   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5665                         CallSeqStart.getNode()->getOperand(0),
5666                         Flags, DAG, dl);
5667   // The MEMCPY must go outside the CALLSEQ_START..END.
5668   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5669   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5670                                                  SDLoc(MemcpyCall));
5671   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5672                          NewCallSeqStart.getNode());
5673   return NewCallSeqStart;
5674 }
5675 
5676 SDValue PPCTargetLowering::LowerCall_64SVR4(
5677     SDValue Chain, SDValue Callee, CallFlags CFlags,
5678     const SmallVectorImpl<ISD::OutputArg> &Outs,
5679     const SmallVectorImpl<SDValue> &OutVals,
5680     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5681     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5682     const CallBase *CB) const {
5683   bool isELFv2ABI = Subtarget.isELFv2ABI();
5684   bool isLittleEndian = Subtarget.isLittleEndian();
5685   unsigned NumOps = Outs.size();
5686   bool IsSibCall = false;
5687   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5688 
5689   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5690   unsigned PtrByteSize = 8;
5691 
5692   MachineFunction &MF = DAG.getMachineFunction();
5693 
5694   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5695     IsSibCall = true;
5696 
5697   // Mark this function as potentially containing a function that contains a
5698   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5699   // and restoring the callers stack pointer in this functions epilog. This is
5700   // done because by tail calling the called function might overwrite the value
5701   // in this function's (MF) stack pointer stack slot 0(SP).
5702   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5703     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5704 
5705   assert(!(IsFastCall && CFlags.IsVarArg) &&
5706          "fastcc not supported on varargs functions");
5707 
5708   // Count how many bytes are to be pushed on the stack, including the linkage
5709   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5710   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5711   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5712   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5713   unsigned NumBytes = LinkageSize;
5714   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5715 
5716   static const MCPhysReg GPR[] = {
5717     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5718     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5719   };
5720   static const MCPhysReg VR[] = {
5721     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5722     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5723   };
5724 
5725   const unsigned NumGPRs = array_lengthof(GPR);
5726   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5727   const unsigned NumVRs  = array_lengthof(VR);
5728 
5729   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5730   // can be passed to the callee in registers.
5731   // For the fast calling convention, there is another check below.
5732   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5733   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5734   if (!HasParameterArea) {
5735     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5736     unsigned AvailableFPRs = NumFPRs;
5737     unsigned AvailableVRs = NumVRs;
5738     unsigned NumBytesTmp = NumBytes;
5739     for (unsigned i = 0; i != NumOps; ++i) {
5740       if (Outs[i].Flags.isNest()) continue;
5741       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5742                                  PtrByteSize, LinkageSize, ParamAreaSize,
5743                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5744         HasParameterArea = true;
5745     }
5746   }
5747 
5748   // When using the fast calling convention, we don't provide backing for
5749   // arguments that will be in registers.
5750   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5751 
5752   // Avoid allocating parameter area for fastcc functions if all the arguments
5753   // can be passed in the registers.
5754   if (IsFastCall)
5755     HasParameterArea = false;
5756 
5757   // Add up all the space actually used.
5758   for (unsigned i = 0; i != NumOps; ++i) {
5759     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5760     EVT ArgVT = Outs[i].VT;
5761     EVT OrigVT = Outs[i].ArgVT;
5762 
5763     if (Flags.isNest())
5764       continue;
5765 
5766     if (IsFastCall) {
5767       if (Flags.isByVal()) {
5768         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5769         if (NumGPRsUsed > NumGPRs)
5770           HasParameterArea = true;
5771       } else {
5772         switch (ArgVT.getSimpleVT().SimpleTy) {
5773         default: llvm_unreachable("Unexpected ValueType for argument!");
5774         case MVT::i1:
5775         case MVT::i32:
5776         case MVT::i64:
5777           if (++NumGPRsUsed <= NumGPRs)
5778             continue;
5779           break;
5780         case MVT::v4i32:
5781         case MVT::v8i16:
5782         case MVT::v16i8:
5783         case MVT::v2f64:
5784         case MVT::v2i64:
5785         case MVT::v1i128:
5786         case MVT::f128:
5787           if (++NumVRsUsed <= NumVRs)
5788             continue;
5789           break;
5790         case MVT::v4f32:
5791           if (++NumVRsUsed <= NumVRs)
5792             continue;
5793           break;
5794         case MVT::f32:
5795         case MVT::f64:
5796           if (++NumFPRsUsed <= NumFPRs)
5797             continue;
5798           break;
5799         }
5800         HasParameterArea = true;
5801       }
5802     }
5803 
5804     /* Respect alignment of argument on the stack.  */
5805     auto Alignement =
5806         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5807     NumBytes = alignTo(NumBytes, Alignement);
5808 
5809     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5810     if (Flags.isInConsecutiveRegsLast())
5811       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5812   }
5813 
5814   unsigned NumBytesActuallyUsed = NumBytes;
5815 
5816   // In the old ELFv1 ABI,
5817   // the prolog code of the callee may store up to 8 GPR argument registers to
5818   // the stack, allowing va_start to index over them in memory if its varargs.
5819   // Because we cannot tell if this is needed on the caller side, we have to
5820   // conservatively assume that it is needed.  As such, make sure we have at
5821   // least enough stack space for the caller to store the 8 GPRs.
5822   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5823   // really requires memory operands, e.g. a vararg function.
5824   if (HasParameterArea)
5825     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5826   else
5827     NumBytes = LinkageSize;
5828 
5829   // Tail call needs the stack to be aligned.
5830   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5831     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5832 
5833   int SPDiff = 0;
5834 
5835   // Calculate by how many bytes the stack has to be adjusted in case of tail
5836   // call optimization.
5837   if (!IsSibCall)
5838     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5839 
5840   // To protect arguments on the stack from being clobbered in a tail call,
5841   // force all the loads to happen before doing any other lowering.
5842   if (CFlags.IsTailCall)
5843     Chain = DAG.getStackArgumentTokenFactor(Chain);
5844 
5845   // Adjust the stack pointer for the new arguments...
5846   // These operations are automatically eliminated by the prolog/epilog pass
5847   if (!IsSibCall)
5848     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5849   SDValue CallSeqStart = Chain;
5850 
5851   // Load the return address and frame pointer so it can be move somewhere else
5852   // later.
5853   SDValue LROp, FPOp;
5854   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5855 
5856   // Set up a copy of the stack pointer for use loading and storing any
5857   // arguments that may not fit in the registers available for argument
5858   // passing.
5859   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5860 
5861   // Figure out which arguments are going to go in registers, and which in
5862   // memory.  Also, if this is a vararg function, floating point operations
5863   // must be stored to our stack, and loaded into integer regs as well, if
5864   // any integer regs are available for argument passing.
5865   unsigned ArgOffset = LinkageSize;
5866 
5867   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5868   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5869 
5870   SmallVector<SDValue, 8> MemOpChains;
5871   for (unsigned i = 0; i != NumOps; ++i) {
5872     SDValue Arg = OutVals[i];
5873     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5874     EVT ArgVT = Outs[i].VT;
5875     EVT OrigVT = Outs[i].ArgVT;
5876 
5877     // PtrOff will be used to store the current argument to the stack if a
5878     // register cannot be found for it.
5879     SDValue PtrOff;
5880 
5881     // We re-align the argument offset for each argument, except when using the
5882     // fast calling convention, when we need to make sure we do that only when
5883     // we'll actually use a stack slot.
5884     auto ComputePtrOff = [&]() {
5885       /* Respect alignment of argument on the stack.  */
5886       auto Alignment =
5887           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5888       ArgOffset = alignTo(ArgOffset, Alignment);
5889 
5890       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5891 
5892       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5893     };
5894 
5895     if (!IsFastCall) {
5896       ComputePtrOff();
5897 
5898       /* Compute GPR index associated with argument offset.  */
5899       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5900       GPR_idx = std::min(GPR_idx, NumGPRs);
5901     }
5902 
5903     // Promote integers to 64-bit values.
5904     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5905       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5906       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5907       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5908     }
5909 
5910     // FIXME memcpy is used way more than necessary.  Correctness first.
5911     // Note: "by value" is code for passing a structure by value, not
5912     // basic types.
5913     if (Flags.isByVal()) {
5914       // Note: Size includes alignment padding, so
5915       //   struct x { short a; char b; }
5916       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5917       // These are the proper values we need for right-justifying the
5918       // aggregate in a parameter register.
5919       unsigned Size = Flags.getByValSize();
5920 
5921       // An empty aggregate parameter takes up no storage and no
5922       // registers.
5923       if (Size == 0)
5924         continue;
5925 
5926       if (IsFastCall)
5927         ComputePtrOff();
5928 
5929       // All aggregates smaller than 8 bytes must be passed right-justified.
5930       if (Size==1 || Size==2 || Size==4) {
5931         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5932         if (GPR_idx != NumGPRs) {
5933           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5934                                         MachinePointerInfo(), VT);
5935           MemOpChains.push_back(Load.getValue(1));
5936           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5937 
5938           ArgOffset += PtrByteSize;
5939           continue;
5940         }
5941       }
5942 
5943       if (GPR_idx == NumGPRs && Size < 8) {
5944         SDValue AddPtr = PtrOff;
5945         if (!isLittleEndian) {
5946           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5947                                           PtrOff.getValueType());
5948           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5949         }
5950         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5951                                                           CallSeqStart,
5952                                                           Flags, DAG, dl);
5953         ArgOffset += PtrByteSize;
5954         continue;
5955       }
5956       // Copy entire object into memory.  There are cases where gcc-generated
5957       // code assumes it is there, even if it could be put entirely into
5958       // registers.  (This is not what the doc says.)
5959 
5960       // FIXME: The above statement is likely due to a misunderstanding of the
5961       // documents.  All arguments must be copied into the parameter area BY
5962       // THE CALLEE in the event that the callee takes the address of any
5963       // formal argument.  That has not yet been implemented.  However, it is
5964       // reasonable to use the stack area as a staging area for the register
5965       // load.
5966 
5967       // Skip this for small aggregates, as we will use the same slot for a
5968       // right-justified copy, below.
5969       if (Size >= 8)
5970         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5971                                                           CallSeqStart,
5972                                                           Flags, DAG, dl);
5973 
5974       // When a register is available, pass a small aggregate right-justified.
5975       if (Size < 8 && GPR_idx != NumGPRs) {
5976         // The easiest way to get this right-justified in a register
5977         // is to copy the structure into the rightmost portion of a
5978         // local variable slot, then load the whole slot into the
5979         // register.
5980         // FIXME: The memcpy seems to produce pretty awful code for
5981         // small aggregates, particularly for packed ones.
5982         // FIXME: It would be preferable to use the slot in the
5983         // parameter save area instead of a new local variable.
5984         SDValue AddPtr = PtrOff;
5985         if (!isLittleEndian) {
5986           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5987           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5988         }
5989         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5990                                                           CallSeqStart,
5991                                                           Flags, DAG, dl);
5992 
5993         // Load the slot into the register.
5994         SDValue Load =
5995             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5996         MemOpChains.push_back(Load.getValue(1));
5997         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5998 
5999         // Done with this argument.
6000         ArgOffset += PtrByteSize;
6001         continue;
6002       }
6003 
6004       // For aggregates larger than PtrByteSize, copy the pieces of the
6005       // object that fit into registers from the parameter save area.
6006       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6007         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6008         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6009         if (GPR_idx != NumGPRs) {
6010           SDValue Load =
6011               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6012           MemOpChains.push_back(Load.getValue(1));
6013           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6014           ArgOffset += PtrByteSize;
6015         } else {
6016           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6017           break;
6018         }
6019       }
6020       continue;
6021     }
6022 
6023     switch (Arg.getSimpleValueType().SimpleTy) {
6024     default: llvm_unreachable("Unexpected ValueType for argument!");
6025     case MVT::i1:
6026     case MVT::i32:
6027     case MVT::i64:
6028       if (Flags.isNest()) {
6029         // The 'nest' parameter, if any, is passed in R11.
6030         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6031         break;
6032       }
6033 
6034       // These can be scalar arguments or elements of an integer array type
6035       // passed directly.  Clang may use those instead of "byval" aggregate
6036       // types to avoid forcing arguments to memory unnecessarily.
6037       if (GPR_idx != NumGPRs) {
6038         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6039       } else {
6040         if (IsFastCall)
6041           ComputePtrOff();
6042 
6043         assert(HasParameterArea &&
6044                "Parameter area must exist to pass an argument in memory.");
6045         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6046                          true, CFlags.IsTailCall, false, MemOpChains,
6047                          TailCallArguments, dl);
6048         if (IsFastCall)
6049           ArgOffset += PtrByteSize;
6050       }
6051       if (!IsFastCall)
6052         ArgOffset += PtrByteSize;
6053       break;
6054     case MVT::f32:
6055     case MVT::f64: {
6056       // These can be scalar arguments or elements of a float array type
6057       // passed directly.  The latter are used to implement ELFv2 homogenous
6058       // float aggregates.
6059 
6060       // Named arguments go into FPRs first, and once they overflow, the
6061       // remaining arguments go into GPRs and then the parameter save area.
6062       // Unnamed arguments for vararg functions always go to GPRs and
6063       // then the parameter save area.  For now, put all arguments to vararg
6064       // routines always in both locations (FPR *and* GPR or stack slot).
6065       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6066       bool NeededLoad = false;
6067 
6068       // First load the argument into the next available FPR.
6069       if (FPR_idx != NumFPRs)
6070         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6071 
6072       // Next, load the argument into GPR or stack slot if needed.
6073       if (!NeedGPROrStack)
6074         ;
6075       else if (GPR_idx != NumGPRs && !IsFastCall) {
6076         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6077         // once we support fp <-> gpr moves.
6078 
6079         // In the non-vararg case, this can only ever happen in the
6080         // presence of f32 array types, since otherwise we never run
6081         // out of FPRs before running out of GPRs.
6082         SDValue ArgVal;
6083 
6084         // Double values are always passed in a single GPR.
6085         if (Arg.getValueType() != MVT::f32) {
6086           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6087 
6088         // Non-array float values are extended and passed in a GPR.
6089         } else if (!Flags.isInConsecutiveRegs()) {
6090           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6091           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6092 
6093         // If we have an array of floats, we collect every odd element
6094         // together with its predecessor into one GPR.
6095         } else if (ArgOffset % PtrByteSize != 0) {
6096           SDValue Lo, Hi;
6097           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6098           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6099           if (!isLittleEndian)
6100             std::swap(Lo, Hi);
6101           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6102 
6103         // The final element, if even, goes into the first half of a GPR.
6104         } else if (Flags.isInConsecutiveRegsLast()) {
6105           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6106           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6107           if (!isLittleEndian)
6108             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6109                                  DAG.getConstant(32, dl, MVT::i32));
6110 
6111         // Non-final even elements are skipped; they will be handled
6112         // together the with subsequent argument on the next go-around.
6113         } else
6114           ArgVal = SDValue();
6115 
6116         if (ArgVal.getNode())
6117           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6118       } else {
6119         if (IsFastCall)
6120           ComputePtrOff();
6121 
6122         // Single-precision floating-point values are mapped to the
6123         // second (rightmost) word of the stack doubleword.
6124         if (Arg.getValueType() == MVT::f32 &&
6125             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6126           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6127           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6128         }
6129 
6130         assert(HasParameterArea &&
6131                "Parameter area must exist to pass an argument in memory.");
6132         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6133                          true, CFlags.IsTailCall, false, MemOpChains,
6134                          TailCallArguments, dl);
6135 
6136         NeededLoad = true;
6137       }
6138       // When passing an array of floats, the array occupies consecutive
6139       // space in the argument area; only round up to the next doubleword
6140       // at the end of the array.  Otherwise, each float takes 8 bytes.
6141       if (!IsFastCall || NeededLoad) {
6142         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6143                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6144         if (Flags.isInConsecutiveRegsLast())
6145           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6146       }
6147       break;
6148     }
6149     case MVT::v4f32:
6150     case MVT::v4i32:
6151     case MVT::v8i16:
6152     case MVT::v16i8:
6153     case MVT::v2f64:
6154     case MVT::v2i64:
6155     case MVT::v1i128:
6156     case MVT::f128:
6157       // These can be scalar arguments or elements of a vector array type
6158       // passed directly.  The latter are used to implement ELFv2 homogenous
6159       // vector aggregates.
6160 
6161       // For a varargs call, named arguments go into VRs or on the stack as
6162       // usual; unnamed arguments always go to the stack or the corresponding
6163       // GPRs when within range.  For now, we always put the value in both
6164       // locations (or even all three).
6165       if (CFlags.IsVarArg) {
6166         assert(HasParameterArea &&
6167                "Parameter area must exist if we have a varargs call.");
6168         // We could elide this store in the case where the object fits
6169         // entirely in R registers.  Maybe later.
6170         SDValue Store =
6171             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6172         MemOpChains.push_back(Store);
6173         if (VR_idx != NumVRs) {
6174           SDValue Load =
6175               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6176           MemOpChains.push_back(Load.getValue(1));
6177           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6178         }
6179         ArgOffset += 16;
6180         for (unsigned i=0; i<16; i+=PtrByteSize) {
6181           if (GPR_idx == NumGPRs)
6182             break;
6183           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6184                                    DAG.getConstant(i, dl, PtrVT));
6185           SDValue Load =
6186               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6187           MemOpChains.push_back(Load.getValue(1));
6188           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6189         }
6190         break;
6191       }
6192 
6193       // Non-varargs Altivec params go into VRs or on the stack.
6194       if (VR_idx != NumVRs) {
6195         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6196       } else {
6197         if (IsFastCall)
6198           ComputePtrOff();
6199 
6200         assert(HasParameterArea &&
6201                "Parameter area must exist to pass an argument in memory.");
6202         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6203                          true, CFlags.IsTailCall, true, MemOpChains,
6204                          TailCallArguments, dl);
6205         if (IsFastCall)
6206           ArgOffset += 16;
6207       }
6208 
6209       if (!IsFastCall)
6210         ArgOffset += 16;
6211       break;
6212     }
6213   }
6214 
6215   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6216          "mismatch in size of parameter area");
6217   (void)NumBytesActuallyUsed;
6218 
6219   if (!MemOpChains.empty())
6220     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6221 
6222   // Check if this is an indirect call (MTCTR/BCTRL).
6223   // See prepareDescriptorIndirectCall and buildCallOperands for more
6224   // information about calls through function pointers in the 64-bit SVR4 ABI.
6225   if (CFlags.IsIndirect) {
6226     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6227     // caller in the TOC save area.
6228     if (isTOCSaveRestoreRequired(Subtarget)) {
6229       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6230       // Load r2 into a virtual register and store it to the TOC save area.
6231       setUsesTOCBasePtr(DAG);
6232       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6233       // TOC save area offset.
6234       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6235       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6236       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6237       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6238                            MachinePointerInfo::getStack(
6239                                DAG.getMachineFunction(), TOCSaveOffset));
6240     }
6241     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6242     // This does not mean the MTCTR instruction must use R12; it's easier
6243     // to model this as an extra parameter, so do that.
6244     if (isELFv2ABI && !CFlags.IsPatchPoint)
6245       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6246   }
6247 
6248   // Build a sequence of copy-to-reg nodes chained together with token chain
6249   // and flag operands which copy the outgoing args into the appropriate regs.
6250   SDValue InFlag;
6251   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6252     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6253                              RegsToPass[i].second, InFlag);
6254     InFlag = Chain.getValue(1);
6255   }
6256 
6257   if (CFlags.IsTailCall && !IsSibCall)
6258     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6259                     TailCallArguments);
6260 
6261   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6262                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6263 }
6264 
6265 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6266                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6267                    CCState &State) {
6268 
6269   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6270       State.getMachineFunction().getSubtarget());
6271   const bool IsPPC64 = Subtarget.isPPC64();
6272   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6273   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6274 
6275   if (ValVT.isVector() && !State.getMachineFunction()
6276                                .getTarget()
6277                                .Options.EnableAIXExtendedAltivecABI)
6278     report_fatal_error("the default Altivec AIX ABI is not yet supported");
6279 
6280   if (ValVT == MVT::f128)
6281     report_fatal_error("f128 is unimplemented on AIX.");
6282 
6283   if (ArgFlags.isNest())
6284     report_fatal_error("Nest arguments are unimplemented.");
6285 
6286   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6287                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6288                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6289   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6290                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6291                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6292 
6293   static const MCPhysReg VR[] = {// Vector registers.
6294                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6295                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6296                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6297 
6298   if (ArgFlags.isByVal()) {
6299     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6300       report_fatal_error("Pass-by-value arguments with alignment greater than "
6301                          "register width are not supported.");
6302 
6303     const unsigned ByValSize = ArgFlags.getByValSize();
6304 
6305     // An empty aggregate parameter takes up no storage and no registers,
6306     // but needs a MemLoc for a stack slot for the formal arguments side.
6307     if (ByValSize == 0) {
6308       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6309                                        State.getNextStackOffset(), RegVT,
6310                                        LocInfo));
6311       return false;
6312     }
6313 
6314     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6315     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6316     for (const unsigned E = Offset + StackSize; Offset < E;
6317          Offset += PtrAlign.value()) {
6318       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6319         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6320       else {
6321         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6322                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6323                                          LocInfo));
6324         break;
6325       }
6326     }
6327     return false;
6328   }
6329 
6330   // Arguments always reserve parameter save area.
6331   switch (ValVT.SimpleTy) {
6332   default:
6333     report_fatal_error("Unhandled value type for argument.");
6334   case MVT::i64:
6335     // i64 arguments should have been split to i32 for PPC32.
6336     assert(IsPPC64 && "PPC32 should have split i64 values.");
6337     LLVM_FALLTHROUGH;
6338   case MVT::i1:
6339   case MVT::i32: {
6340     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6341     // AIX integer arguments are always passed in register width.
6342     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6343       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6344                                   : CCValAssign::LocInfo::ZExt;
6345     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6346       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6347     else
6348       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6349 
6350     return false;
6351   }
6352   case MVT::f32:
6353   case MVT::f64: {
6354     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6355     const unsigned StoreSize = LocVT.getStoreSize();
6356     // Floats are always 4-byte aligned in the PSA on AIX.
6357     // This includes f64 in 64-bit mode for ABI compatibility.
6358     const unsigned Offset =
6359         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6360     unsigned FReg = State.AllocateReg(FPR);
6361     if (FReg)
6362       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6363 
6364     // Reserve and initialize GPRs or initialize the PSA as required.
6365     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6366       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6367         assert(FReg && "An FPR should be available when a GPR is reserved.");
6368         if (State.isVarArg()) {
6369           // Successfully reserved GPRs are only initialized for vararg calls.
6370           // Custom handling is required for:
6371           //   f64 in PPC32 needs to be split into 2 GPRs.
6372           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6373           State.addLoc(
6374               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6375         }
6376       } else {
6377         // If there are insufficient GPRs, the PSA needs to be initialized.
6378         // Initialization occurs even if an FPR was initialized for
6379         // compatibility with the AIX XL compiler. The full memory for the
6380         // argument will be initialized even if a prior word is saved in GPR.
6381         // A custom memLoc is used when the argument also passes in FPR so
6382         // that the callee handling can skip over it easily.
6383         State.addLoc(
6384             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6385                                              LocInfo)
6386                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6387         break;
6388       }
6389     }
6390 
6391     return false;
6392   }
6393   case MVT::v4f32:
6394   case MVT::v4i32:
6395   case MVT::v8i16:
6396   case MVT::v16i8:
6397   case MVT::v2i64:
6398   case MVT::v2f64:
6399   case MVT::v1i128: {
6400     if (State.isVarArg())
6401       report_fatal_error(
6402           "variadic arguments for vector types are unimplemented for AIX");
6403 
6404     if (unsigned VReg = State.AllocateReg(VR))
6405       State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6406     else {
6407       report_fatal_error(
6408           "passing vector parameters to the stack is unimplemented for AIX");
6409     }
6410     return false;
6411   }
6412   }
6413   return true;
6414 }
6415 
6416 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6417                                                     bool IsPPC64) {
6418   assert((IsPPC64 || SVT != MVT::i64) &&
6419          "i64 should have been split for 32-bit codegen.");
6420 
6421   switch (SVT) {
6422   default:
6423     report_fatal_error("Unexpected value type for formal argument");
6424   case MVT::i1:
6425   case MVT::i32:
6426   case MVT::i64:
6427     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6428   case MVT::f32:
6429     return &PPC::F4RCRegClass;
6430   case MVT::f64:
6431     return &PPC::F8RCRegClass;
6432   case MVT::v4f32:
6433   case MVT::v4i32:
6434   case MVT::v8i16:
6435   case MVT::v16i8:
6436   case MVT::v2i64:
6437   case MVT::v2f64:
6438   case MVT::v1i128:
6439     return &PPC::VRRCRegClass;
6440   }
6441 }
6442 
6443 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6444                                         SelectionDAG &DAG, SDValue ArgValue,
6445                                         MVT LocVT, const SDLoc &dl) {
6446   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6447   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6448 
6449   if (Flags.isSExt())
6450     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6451                            DAG.getValueType(ValVT));
6452   else if (Flags.isZExt())
6453     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6454                            DAG.getValueType(ValVT));
6455 
6456   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6457 }
6458 
6459 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6460   const unsigned LASize = FL->getLinkageSize();
6461 
6462   if (PPC::GPRCRegClass.contains(Reg)) {
6463     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6464            "Reg must be a valid argument register!");
6465     return LASize + 4 * (Reg - PPC::R3);
6466   }
6467 
6468   if (PPC::G8RCRegClass.contains(Reg)) {
6469     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6470            "Reg must be a valid argument register!");
6471     return LASize + 8 * (Reg - PPC::X3);
6472   }
6473 
6474   llvm_unreachable("Only general purpose registers expected.");
6475 }
6476 
6477 //   AIX ABI Stack Frame Layout:
6478 //
6479 //   Low Memory +--------------------------------------------+
6480 //   SP   +---> | Back chain                                 | ---+
6481 //        |     +--------------------------------------------+    |
6482 //        |     | Saved Condition Register                   |    |
6483 //        |     +--------------------------------------------+    |
6484 //        |     | Saved Linkage Register                     |    |
6485 //        |     +--------------------------------------------+    | Linkage Area
6486 //        |     | Reserved for compilers                     |    |
6487 //        |     +--------------------------------------------+    |
6488 //        |     | Reserved for binders                       |    |
6489 //        |     +--------------------------------------------+    |
6490 //        |     | Saved TOC pointer                          | ---+
6491 //        |     +--------------------------------------------+
6492 //        |     | Parameter save area                        |
6493 //        |     +--------------------------------------------+
6494 //        |     | Alloca space                               |
6495 //        |     +--------------------------------------------+
6496 //        |     | Local variable space                       |
6497 //        |     +--------------------------------------------+
6498 //        |     | Float/int conversion temporary             |
6499 //        |     +--------------------------------------------+
6500 //        |     | Save area for AltiVec registers            |
6501 //        |     +--------------------------------------------+
6502 //        |     | AltiVec alignment padding                  |
6503 //        |     +--------------------------------------------+
6504 //        |     | Save area for VRSAVE register              |
6505 //        |     +--------------------------------------------+
6506 //        |     | Save area for General Purpose registers    |
6507 //        |     +--------------------------------------------+
6508 //        |     | Save area for Floating Point registers     |
6509 //        |     +--------------------------------------------+
6510 //        +---- | Back chain                                 |
6511 // High Memory  +--------------------------------------------+
6512 //
6513 //  Specifications:
6514 //  AIX 7.2 Assembler Language Reference
6515 //  Subroutine linkage convention
6516 
6517 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6518     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6519     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6520     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6521 
6522   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6523           CallConv == CallingConv::Fast) &&
6524          "Unexpected calling convention!");
6525 
6526   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6527     report_fatal_error("Tail call support is unimplemented on AIX.");
6528 
6529   if (useSoftFloat())
6530     report_fatal_error("Soft float support is unimplemented on AIX.");
6531 
6532   const PPCSubtarget &Subtarget =
6533       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6534 
6535   const bool IsPPC64 = Subtarget.isPPC64();
6536   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6537 
6538   // Assign locations to all of the incoming arguments.
6539   SmallVector<CCValAssign, 16> ArgLocs;
6540   MachineFunction &MF = DAG.getMachineFunction();
6541   MachineFrameInfo &MFI = MF.getFrameInfo();
6542   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6543   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6544 
6545   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6546   // Reserve space for the linkage area on the stack.
6547   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6548   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6549   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6550 
6551   SmallVector<SDValue, 8> MemOps;
6552 
6553   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6554     CCValAssign &VA = ArgLocs[I++];
6555     MVT LocVT = VA.getLocVT();
6556     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6557     if (VA.isMemLoc() && VA.getValVT().isVector())
6558       report_fatal_error(
6559           "passing vector parameters to the stack is unimplemented for AIX");
6560 
6561     // For compatibility with the AIX XL compiler, the float args in the
6562     // parameter save area are initialized even if the argument is available
6563     // in register.  The caller is required to initialize both the register
6564     // and memory, however, the callee can choose to expect it in either.
6565     // The memloc is dismissed here because the argument is retrieved from
6566     // the register.
6567     if (VA.isMemLoc() && VA.needsCustom())
6568       continue;
6569 
6570     if (VA.isRegLoc()) {
6571       if (VA.getValVT().isScalarInteger())
6572         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6573       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector())
6574         FuncInfo->appendParameterType(VA.getValVT().SimpleTy == MVT::f32
6575                                           ? PPCFunctionInfo::ShortFloatPoint
6576                                           : PPCFunctionInfo::LongFloatPoint);
6577     }
6578 
6579     if (Flags.isByVal() && VA.isMemLoc()) {
6580       const unsigned Size =
6581           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
6582                   PtrByteSize);
6583       const int FI = MF.getFrameInfo().CreateFixedObject(
6584           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
6585           /* IsAliased */ true);
6586       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6587       InVals.push_back(FIN);
6588 
6589       continue;
6590     }
6591 
6592     if (Flags.isByVal()) {
6593       assert(VA.isRegLoc() && "MemLocs should already be handled.");
6594 
6595       const MCPhysReg ArgReg = VA.getLocReg();
6596       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
6597 
6598       if (Flags.getNonZeroByValAlign() > PtrByteSize)
6599         report_fatal_error("Over aligned byvals not supported yet.");
6600 
6601       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
6602       const int FI = MF.getFrameInfo().CreateFixedObject(
6603           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
6604           /* IsAliased */ true);
6605       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6606       InVals.push_back(FIN);
6607 
6608       // Add live ins for all the RegLocs for the same ByVal.
6609       const TargetRegisterClass *RegClass =
6610           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6611 
6612       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
6613                                                unsigned Offset) {
6614         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
6615         // Since the callers side has left justified the aggregate in the
6616         // register, we can simply store the entire register into the stack
6617         // slot.
6618         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6619         // The store to the fixedstack object is needed becuase accessing a
6620         // field of the ByVal will use a gep and load. Ideally we will optimize
6621         // to extracting the value from the register directly, and elide the
6622         // stores when the arguments address is not taken, but that will need to
6623         // be future work.
6624         SDValue Store = DAG.getStore(
6625             CopyFrom.getValue(1), dl, CopyFrom,
6626             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
6627             MachinePointerInfo::getFixedStack(MF, FI, Offset));
6628 
6629         MemOps.push_back(Store);
6630       };
6631 
6632       unsigned Offset = 0;
6633       HandleRegLoc(VA.getLocReg(), Offset);
6634       Offset += PtrByteSize;
6635       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
6636            Offset += PtrByteSize) {
6637         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
6638                "RegLocs should be for ByVal argument.");
6639 
6640         const CCValAssign RL = ArgLocs[I++];
6641         HandleRegLoc(RL.getLocReg(), Offset);
6642         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
6643       }
6644 
6645       if (Offset != StackSize) {
6646         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
6647                "Expected MemLoc for remaining bytes.");
6648         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
6649         // Consume the MemLoc.The InVal has already been emitted, so nothing
6650         // more needs to be done.
6651         ++I;
6652       }
6653 
6654       continue;
6655     }
6656 
6657     EVT ValVT = VA.getValVT();
6658     if (VA.isRegLoc() && !VA.needsCustom()) {
6659       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
6660       unsigned VReg =
6661           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6662       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6663       if (ValVT.isScalarInteger() &&
6664           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
6665         ArgValue =
6666             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6667       }
6668       InVals.push_back(ArgValue);
6669       continue;
6670     }
6671     if (VA.isMemLoc()) {
6672       const unsigned LocSize = LocVT.getStoreSize();
6673       const unsigned ValSize = ValVT.getStoreSize();
6674       assert((ValSize <= LocSize) &&
6675              "Object size is larger than size of MemLoc");
6676       int CurArgOffset = VA.getLocMemOffset();
6677       // Objects are right-justified because AIX is big-endian.
6678       if (LocSize > ValSize)
6679         CurArgOffset += LocSize - ValSize;
6680       // Potential tail calls could cause overwriting of argument stack slots.
6681       const bool IsImmutable =
6682           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6683             (CallConv == CallingConv::Fast));
6684       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6685       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6686       SDValue ArgValue =
6687           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6688       InVals.push_back(ArgValue);
6689       continue;
6690     }
6691   }
6692 
6693   // On AIX a minimum of 8 words is saved to the parameter save area.
6694   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6695   // Area that is at least reserved in the caller of this function.
6696   unsigned CallerReservedArea =
6697       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
6698 
6699   // Set the size that is at least reserved in caller of this function. Tail
6700   // call optimized function's reserved stack space needs to be aligned so
6701   // that taking the difference between two stack areas will result in an
6702   // aligned stack.
6703   CallerReservedArea =
6704       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
6705   FuncInfo->setMinReservedArea(CallerReservedArea);
6706 
6707   if (isVarArg) {
6708     FuncInfo->setVarArgsFrameIndex(
6709         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
6710     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
6711 
6712     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6713                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6714 
6715     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6716                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6717     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
6718 
6719     // The fixed integer arguments of a variadic function are stored to the
6720     // VarArgsFrameIndex on the stack so that they may be loaded by
6721     // dereferencing the result of va_next.
6722     for (unsigned GPRIndex =
6723              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
6724          GPRIndex < NumGPArgRegs; ++GPRIndex) {
6725 
6726       const unsigned VReg =
6727           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
6728                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
6729 
6730       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
6731       SDValue Store =
6732           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
6733       MemOps.push_back(Store);
6734       // Increment the address for the next argument to store.
6735       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
6736       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
6737     }
6738   }
6739 
6740   if (!MemOps.empty())
6741     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
6742 
6743   return Chain;
6744 }
6745 
6746 SDValue PPCTargetLowering::LowerCall_AIX(
6747     SDValue Chain, SDValue Callee, CallFlags CFlags,
6748     const SmallVectorImpl<ISD::OutputArg> &Outs,
6749     const SmallVectorImpl<SDValue> &OutVals,
6750     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6751     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6752     const CallBase *CB) const {
6753   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
6754   // AIX ABI stack frame layout.
6755 
6756   assert((CFlags.CallConv == CallingConv::C ||
6757           CFlags.CallConv == CallingConv::Cold ||
6758           CFlags.CallConv == CallingConv::Fast) &&
6759          "Unexpected calling convention!");
6760 
6761   if (CFlags.IsPatchPoint)
6762     report_fatal_error("This call type is unimplemented on AIX.");
6763 
6764   const PPCSubtarget& Subtarget =
6765       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
6766 
6767   MachineFunction &MF = DAG.getMachineFunction();
6768   SmallVector<CCValAssign, 16> ArgLocs;
6769   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
6770                  *DAG.getContext());
6771 
6772   // Reserve space for the linkage save area (LSA) on the stack.
6773   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
6774   //   [SP][CR][LR][2 x reserved][TOC].
6775   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
6776   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6777   const bool IsPPC64 = Subtarget.isPPC64();
6778   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
6779   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6780   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6781   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
6782 
6783   // The prolog code of the callee may store up to 8 GPR argument registers to
6784   // the stack, allowing va_start to index over them in memory if the callee
6785   // is variadic.
6786   // Because we cannot tell if this is needed on the caller side, we have to
6787   // conservatively assume that it is needed.  As such, make sure we have at
6788   // least enough stack space for the caller to store the 8 GPRs.
6789   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
6790   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
6791                                      CCInfo.getNextStackOffset());
6792 
6793   // Adjust the stack pointer for the new arguments...
6794   // These operations are automatically eliminated by the prolog/epilog pass.
6795   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6796   SDValue CallSeqStart = Chain;
6797 
6798   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6799   SmallVector<SDValue, 8> MemOpChains;
6800 
6801   // Set up a copy of the stack pointer for loading and storing any
6802   // arguments that may not fit in the registers available for argument
6803   // passing.
6804   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
6805                                    : DAG.getRegister(PPC::R1, MVT::i32);
6806 
6807   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
6808     const unsigned ValNo = ArgLocs[I].getValNo();
6809     SDValue Arg = OutVals[ValNo];
6810     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
6811 
6812     if (Flags.isByVal()) {
6813       const unsigned ByValSize = Flags.getByValSize();
6814 
6815       // Nothing to do for zero-sized ByVals on the caller side.
6816       if (!ByValSize) {
6817         ++I;
6818         continue;
6819       }
6820 
6821       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
6822         return DAG.getExtLoad(
6823             ISD::ZEXTLOAD, dl, PtrVT, Chain,
6824             (LoadOffset != 0)
6825                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
6826                 : Arg,
6827             MachinePointerInfo(), VT);
6828       };
6829 
6830       unsigned LoadOffset = 0;
6831 
6832       // Initialize registers, which are fully occupied by the by-val argument.
6833       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
6834         SDValue Load = GetLoad(PtrVT, LoadOffset);
6835         MemOpChains.push_back(Load.getValue(1));
6836         LoadOffset += PtrByteSize;
6837         const CCValAssign &ByValVA = ArgLocs[I++];
6838         assert(ByValVA.getValNo() == ValNo &&
6839                "Unexpected location for pass-by-value argument.");
6840         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
6841       }
6842 
6843       if (LoadOffset == ByValSize)
6844         continue;
6845 
6846       // There must be one more loc to handle the remainder.
6847       assert(ArgLocs[I].getValNo() == ValNo &&
6848              "Expected additional location for by-value argument.");
6849 
6850       if (ArgLocs[I].isMemLoc()) {
6851         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
6852         const CCValAssign &ByValVA = ArgLocs[I++];
6853         ISD::ArgFlagsTy MemcpyFlags = Flags;
6854         // Only memcpy the bytes that don't pass in register.
6855         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
6856         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
6857             (LoadOffset != 0)
6858                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
6859                 : Arg,
6860             DAG.getObjectPtrOffset(dl, StackPtr,
6861                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
6862             CallSeqStart, MemcpyFlags, DAG, dl);
6863         continue;
6864       }
6865 
6866       // Initialize the final register residue.
6867       // Any residue that occupies the final by-val arg register must be
6868       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
6869       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
6870       // 2 and 1 byte loads.
6871       const unsigned ResidueBytes = ByValSize % PtrByteSize;
6872       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
6873              "Unexpected register residue for by-value argument.");
6874       SDValue ResidueVal;
6875       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
6876         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
6877         const MVT VT =
6878             N == 1 ? MVT::i8
6879                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
6880         SDValue Load = GetLoad(VT, LoadOffset);
6881         MemOpChains.push_back(Load.getValue(1));
6882         LoadOffset += N;
6883         Bytes += N;
6884 
6885         // By-val arguments are passed left-justfied in register.
6886         // Every load here needs to be shifted, otherwise a full register load
6887         // should have been used.
6888         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
6889                "Unexpected load emitted during handling of pass-by-value "
6890                "argument.");
6891         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
6892         EVT ShiftAmountTy =
6893             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
6894         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
6895         SDValue ShiftedLoad =
6896             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
6897         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
6898                                               ShiftedLoad)
6899                                 : ShiftedLoad;
6900       }
6901 
6902       const CCValAssign &ByValVA = ArgLocs[I++];
6903       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
6904       continue;
6905     }
6906 
6907     CCValAssign &VA = ArgLocs[I++];
6908     const MVT LocVT = VA.getLocVT();
6909     const MVT ValVT = VA.getValVT();
6910 
6911     if (VA.isMemLoc() && VA.getValVT().isVector())
6912       report_fatal_error(
6913           "passing vector parameters to the stack is unimplemented for AIX");
6914 
6915     switch (VA.getLocInfo()) {
6916     default:
6917       report_fatal_error("Unexpected argument extension type.");
6918     case CCValAssign::Full:
6919       break;
6920     case CCValAssign::ZExt:
6921       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6922       break;
6923     case CCValAssign::SExt:
6924       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6925       break;
6926     }
6927 
6928     if (VA.isRegLoc() && !VA.needsCustom()) {
6929       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
6930       continue;
6931     }
6932 
6933     if (VA.isMemLoc()) {
6934       SDValue PtrOff =
6935           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
6936       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6937       MemOpChains.push_back(
6938           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
6939 
6940       continue;
6941     }
6942 
6943     // Custom handling is used for GPR initializations for vararg float
6944     // arguments.
6945     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
6946            ValVT.isFloatingPoint() && LocVT.isInteger() &&
6947            "Unexpected register handling for calling convention.");
6948 
6949     SDValue ArgAsInt =
6950         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
6951 
6952     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
6953       // f32 in 32-bit GPR
6954       // f64 in 64-bit GPR
6955       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
6956     else if (Arg.getValueType().getFixedSizeInBits() <
6957              LocVT.getFixedSizeInBits())
6958       // f32 in 64-bit GPR.
6959       RegsToPass.push_back(std::make_pair(
6960           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
6961     else {
6962       // f64 in two 32-bit GPRs
6963       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
6964       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
6965              "Unexpected custom register for argument!");
6966       CCValAssign &GPR1 = VA;
6967       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
6968                                      DAG.getConstant(32, dl, MVT::i8));
6969       RegsToPass.push_back(std::make_pair(
6970           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
6971 
6972       if (I != E) {
6973         // If only 1 GPR was available, there will only be one custom GPR and
6974         // the argument will also pass in memory.
6975         CCValAssign &PeekArg = ArgLocs[I];
6976         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
6977           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
6978           CCValAssign &GPR2 = ArgLocs[I++];
6979           RegsToPass.push_back(std::make_pair(
6980               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
6981         }
6982       }
6983     }
6984   }
6985 
6986   if (!MemOpChains.empty())
6987     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6988 
6989   // For indirect calls, we need to save the TOC base to the stack for
6990   // restoration after the call.
6991   if (CFlags.IsIndirect) {
6992     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6993     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
6994     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
6995     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
6996     const unsigned TOCSaveOffset =
6997         Subtarget.getFrameLowering()->getTOCSaveOffset();
6998 
6999     setUsesTOCBasePtr(DAG);
7000     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7001     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7002     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7003     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7004     Chain = DAG.getStore(
7005         Val.getValue(1), dl, Val, AddPtr,
7006         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7007   }
7008 
7009   // Build a sequence of copy-to-reg nodes chained together with token chain
7010   // and flag operands which copy the outgoing args into the appropriate regs.
7011   SDValue InFlag;
7012   for (auto Reg : RegsToPass) {
7013     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7014     InFlag = Chain.getValue(1);
7015   }
7016 
7017   const int SPDiff = 0;
7018   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7019                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7020 }
7021 
7022 bool
7023 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7024                                   MachineFunction &MF, bool isVarArg,
7025                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7026                                   LLVMContext &Context) const {
7027   SmallVector<CCValAssign, 16> RVLocs;
7028   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7029   return CCInfo.CheckReturn(
7030       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7031                 ? RetCC_PPC_Cold
7032                 : RetCC_PPC);
7033 }
7034 
7035 SDValue
7036 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7037                                bool isVarArg,
7038                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7039                                const SmallVectorImpl<SDValue> &OutVals,
7040                                const SDLoc &dl, SelectionDAG &DAG) const {
7041   SmallVector<CCValAssign, 16> RVLocs;
7042   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7043                  *DAG.getContext());
7044   CCInfo.AnalyzeReturn(Outs,
7045                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7046                            ? RetCC_PPC_Cold
7047                            : RetCC_PPC);
7048 
7049   SDValue Flag;
7050   SmallVector<SDValue, 4> RetOps(1, Chain);
7051 
7052   // Copy the result values into the output registers.
7053   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7054     CCValAssign &VA = RVLocs[i];
7055     assert(VA.isRegLoc() && "Can only return in registers!");
7056 
7057     SDValue Arg = OutVals[RealResIdx];
7058 
7059     switch (VA.getLocInfo()) {
7060     default: llvm_unreachable("Unknown loc info!");
7061     case CCValAssign::Full: break;
7062     case CCValAssign::AExt:
7063       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7064       break;
7065     case CCValAssign::ZExt:
7066       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7067       break;
7068     case CCValAssign::SExt:
7069       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7070       break;
7071     }
7072     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7073       bool isLittleEndian = Subtarget.isLittleEndian();
7074       // Legalize ret f64 -> ret 2 x i32.
7075       SDValue SVal =
7076           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7077                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7078       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7079       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7080       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7081                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7082       Flag = Chain.getValue(1);
7083       VA = RVLocs[++i]; // skip ahead to next loc
7084       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7085     } else
7086       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7087     Flag = Chain.getValue(1);
7088     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7089   }
7090 
7091   RetOps[0] = Chain;  // Update chain.
7092 
7093   // Add the flag if we have it.
7094   if (Flag.getNode())
7095     RetOps.push_back(Flag);
7096 
7097   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7098 }
7099 
7100 SDValue
7101 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7102                                                 SelectionDAG &DAG) const {
7103   SDLoc dl(Op);
7104 
7105   // Get the correct type for integers.
7106   EVT IntVT = Op.getValueType();
7107 
7108   // Get the inputs.
7109   SDValue Chain = Op.getOperand(0);
7110   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7111   // Build a DYNAREAOFFSET node.
7112   SDValue Ops[2] = {Chain, FPSIdx};
7113   SDVTList VTs = DAG.getVTList(IntVT);
7114   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7115 }
7116 
7117 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7118                                              SelectionDAG &DAG) const {
7119   // When we pop the dynamic allocation we need to restore the SP link.
7120   SDLoc dl(Op);
7121 
7122   // Get the correct type for pointers.
7123   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7124 
7125   // Construct the stack pointer operand.
7126   bool isPPC64 = Subtarget.isPPC64();
7127   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7128   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7129 
7130   // Get the operands for the STACKRESTORE.
7131   SDValue Chain = Op.getOperand(0);
7132   SDValue SaveSP = Op.getOperand(1);
7133 
7134   // Load the old link SP.
7135   SDValue LoadLinkSP =
7136       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7137 
7138   // Restore the stack pointer.
7139   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7140 
7141   // Store the old link SP.
7142   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7143 }
7144 
7145 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7146   MachineFunction &MF = DAG.getMachineFunction();
7147   bool isPPC64 = Subtarget.isPPC64();
7148   EVT PtrVT = getPointerTy(MF.getDataLayout());
7149 
7150   // Get current frame pointer save index.  The users of this index will be
7151   // primarily DYNALLOC instructions.
7152   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7153   int RASI = FI->getReturnAddrSaveIndex();
7154 
7155   // If the frame pointer save index hasn't been defined yet.
7156   if (!RASI) {
7157     // Find out what the fix offset of the frame pointer save area.
7158     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7159     // Allocate the frame index for frame pointer save area.
7160     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7161     // Save the result.
7162     FI->setReturnAddrSaveIndex(RASI);
7163   }
7164   return DAG.getFrameIndex(RASI, PtrVT);
7165 }
7166 
7167 SDValue
7168 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7169   MachineFunction &MF = DAG.getMachineFunction();
7170   bool isPPC64 = Subtarget.isPPC64();
7171   EVT PtrVT = getPointerTy(MF.getDataLayout());
7172 
7173   // Get current frame pointer save index.  The users of this index will be
7174   // primarily DYNALLOC instructions.
7175   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7176   int FPSI = FI->getFramePointerSaveIndex();
7177 
7178   // If the frame pointer save index hasn't been defined yet.
7179   if (!FPSI) {
7180     // Find out what the fix offset of the frame pointer save area.
7181     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7182     // Allocate the frame index for frame pointer save area.
7183     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7184     // Save the result.
7185     FI->setFramePointerSaveIndex(FPSI);
7186   }
7187   return DAG.getFrameIndex(FPSI, PtrVT);
7188 }
7189 
7190 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7191                                                    SelectionDAG &DAG) const {
7192   MachineFunction &MF = DAG.getMachineFunction();
7193   // Get the inputs.
7194   SDValue Chain = Op.getOperand(0);
7195   SDValue Size  = Op.getOperand(1);
7196   SDLoc dl(Op);
7197 
7198   // Get the correct type for pointers.
7199   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7200   // Negate the size.
7201   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7202                                 DAG.getConstant(0, dl, PtrVT), Size);
7203   // Construct a node for the frame pointer save index.
7204   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7205   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7206   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7207   if (hasInlineStackProbe(MF))
7208     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7209   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7210 }
7211 
7212 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7213                                                      SelectionDAG &DAG) const {
7214   MachineFunction &MF = DAG.getMachineFunction();
7215 
7216   bool isPPC64 = Subtarget.isPPC64();
7217   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7218 
7219   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7220   return DAG.getFrameIndex(FI, PtrVT);
7221 }
7222 
7223 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7224                                                SelectionDAG &DAG) const {
7225   SDLoc DL(Op);
7226   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7227                      DAG.getVTList(MVT::i32, MVT::Other),
7228                      Op.getOperand(0), Op.getOperand(1));
7229 }
7230 
7231 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7232                                                 SelectionDAG &DAG) const {
7233   SDLoc DL(Op);
7234   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7235                      Op.getOperand(0), Op.getOperand(1));
7236 }
7237 
7238 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7239   if (Op.getValueType().isVector())
7240     return LowerVectorLoad(Op, DAG);
7241 
7242   assert(Op.getValueType() == MVT::i1 &&
7243          "Custom lowering only for i1 loads");
7244 
7245   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7246 
7247   SDLoc dl(Op);
7248   LoadSDNode *LD = cast<LoadSDNode>(Op);
7249 
7250   SDValue Chain = LD->getChain();
7251   SDValue BasePtr = LD->getBasePtr();
7252   MachineMemOperand *MMO = LD->getMemOperand();
7253 
7254   SDValue NewLD =
7255       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7256                      BasePtr, MVT::i8, MMO);
7257   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7258 
7259   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7260   return DAG.getMergeValues(Ops, dl);
7261 }
7262 
7263 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7264   if (Op.getOperand(1).getValueType().isVector())
7265     return LowerVectorStore(Op, DAG);
7266 
7267   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7268          "Custom lowering only for i1 stores");
7269 
7270   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7271 
7272   SDLoc dl(Op);
7273   StoreSDNode *ST = cast<StoreSDNode>(Op);
7274 
7275   SDValue Chain = ST->getChain();
7276   SDValue BasePtr = ST->getBasePtr();
7277   SDValue Value = ST->getValue();
7278   MachineMemOperand *MMO = ST->getMemOperand();
7279 
7280   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7281                       Value);
7282   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7283 }
7284 
7285 // FIXME: Remove this once the ANDI glue bug is fixed:
7286 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7287   assert(Op.getValueType() == MVT::i1 &&
7288          "Custom lowering only for i1 results");
7289 
7290   SDLoc DL(Op);
7291   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7292 }
7293 
7294 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7295                                                SelectionDAG &DAG) const {
7296 
7297   // Implements a vector truncate that fits in a vector register as a shuffle.
7298   // We want to legalize vector truncates down to where the source fits in
7299   // a vector register (and target is therefore smaller than vector register
7300   // size).  At that point legalization will try to custom lower the sub-legal
7301   // result and get here - where we can contain the truncate as a single target
7302   // operation.
7303 
7304   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7305   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7306   //
7307   // We will implement it for big-endian ordering as this (where x denotes
7308   // undefined):
7309   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7310   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7311   //
7312   // The same operation in little-endian ordering will be:
7313   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7314   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7315 
7316   EVT TrgVT = Op.getValueType();
7317   assert(TrgVT.isVector() && "Vector type expected.");
7318   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7319   EVT EltVT = TrgVT.getVectorElementType();
7320   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7321       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7322       !isPowerOf2_32(EltVT.getSizeInBits()))
7323     return SDValue();
7324 
7325   SDValue N1 = Op.getOperand(0);
7326   EVT SrcVT = N1.getValueType();
7327   unsigned SrcSize = SrcVT.getSizeInBits();
7328   if (SrcSize > 256 ||
7329       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7330       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7331     return SDValue();
7332   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7333     return SDValue();
7334 
7335   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7336   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7337 
7338   SDLoc DL(Op);
7339   SDValue Op1, Op2;
7340   if (SrcSize == 256) {
7341     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7342     EVT SplitVT =
7343         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7344     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7345     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7346                       DAG.getConstant(0, DL, VecIdxTy));
7347     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7348                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7349   }
7350   else {
7351     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7352     Op2 = DAG.getUNDEF(WideVT);
7353   }
7354 
7355   // First list the elements we want to keep.
7356   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7357   SmallVector<int, 16> ShuffV;
7358   if (Subtarget.isLittleEndian())
7359     for (unsigned i = 0; i < TrgNumElts; ++i)
7360       ShuffV.push_back(i * SizeMult);
7361   else
7362     for (unsigned i = 1; i <= TrgNumElts; ++i)
7363       ShuffV.push_back(i * SizeMult - 1);
7364 
7365   // Populate the remaining elements with undefs.
7366   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7367     // ShuffV.push_back(i + WideNumElts);
7368     ShuffV.push_back(WideNumElts + 1);
7369 
7370   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7371   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7372   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7373 }
7374 
7375 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7376 /// possible.
7377 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7378   // Not FP, or using SPE? Not a fsel.
7379   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7380       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7381     return Op;
7382 
7383   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7384 
7385   EVT ResVT = Op.getValueType();
7386   EVT CmpVT = Op.getOperand(0).getValueType();
7387   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7388   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7389   SDLoc dl(Op);
7390   SDNodeFlags Flags = Op.getNode()->getFlags();
7391 
7392   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7393   // presence of infinities.
7394   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7395     switch (CC) {
7396     default:
7397       break;
7398     case ISD::SETOGT:
7399     case ISD::SETGT:
7400       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7401     case ISD::SETOLT:
7402     case ISD::SETLT:
7403       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7404     }
7405   }
7406 
7407   // We might be able to do better than this under some circumstances, but in
7408   // general, fsel-based lowering of select is a finite-math-only optimization.
7409   // For more information, see section F.3 of the 2.06 ISA specification.
7410   // With ISA 3.0
7411   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7412       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7413     return Op;
7414 
7415   // If the RHS of the comparison is a 0.0, we don't need to do the
7416   // subtraction at all.
7417   SDValue Sel1;
7418   if (isFloatingPointZero(RHS))
7419     switch (CC) {
7420     default: break;       // SETUO etc aren't handled by fsel.
7421     case ISD::SETNE:
7422       std::swap(TV, FV);
7423       LLVM_FALLTHROUGH;
7424     case ISD::SETEQ:
7425       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7426         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7427       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7428       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7429         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7430       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7431                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7432     case ISD::SETULT:
7433     case ISD::SETLT:
7434       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7435       LLVM_FALLTHROUGH;
7436     case ISD::SETOGE:
7437     case ISD::SETGE:
7438       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7439         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7440       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7441     case ISD::SETUGT:
7442     case ISD::SETGT:
7443       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7444       LLVM_FALLTHROUGH;
7445     case ISD::SETOLE:
7446     case ISD::SETLE:
7447       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7448         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7449       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7450                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7451     }
7452 
7453   SDValue Cmp;
7454   switch (CC) {
7455   default: break;       // SETUO etc aren't handled by fsel.
7456   case ISD::SETNE:
7457     std::swap(TV, FV);
7458     LLVM_FALLTHROUGH;
7459   case ISD::SETEQ:
7460     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7461     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7462       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7463     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7464     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7465       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7466     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7467                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7468   case ISD::SETULT:
7469   case ISD::SETLT:
7470     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7471     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7472       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7473     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7474   case ISD::SETOGE:
7475   case ISD::SETGE:
7476     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7477     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7478       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7479     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7480   case ISD::SETUGT:
7481   case ISD::SETGT:
7482     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7483     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7484       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7485     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7486   case ISD::SETOLE:
7487   case ISD::SETLE:
7488     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7489     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7490       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7491     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7492   }
7493   return Op;
7494 }
7495 
7496 static unsigned getPPCStrictOpcode(unsigned Opc) {
7497   switch (Opc) {
7498   default:
7499     llvm_unreachable("No strict version of this opcode!");
7500   case PPCISD::FCTIDZ:
7501     return PPCISD::STRICT_FCTIDZ;
7502   case PPCISD::FCTIWZ:
7503     return PPCISD::STRICT_FCTIWZ;
7504   case PPCISD::FCTIDUZ:
7505     return PPCISD::STRICT_FCTIDUZ;
7506   case PPCISD::FCTIWUZ:
7507     return PPCISD::STRICT_FCTIWUZ;
7508   case PPCISD::FCFID:
7509     return PPCISD::STRICT_FCFID;
7510   case PPCISD::FCFIDU:
7511     return PPCISD::STRICT_FCFIDU;
7512   case PPCISD::FCFIDS:
7513     return PPCISD::STRICT_FCFIDS;
7514   case PPCISD::FCFIDUS:
7515     return PPCISD::STRICT_FCFIDUS;
7516   }
7517 }
7518 
7519 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7520                               const PPCSubtarget &Subtarget) {
7521   SDLoc dl(Op);
7522   bool IsStrict = Op->isStrictFPOpcode();
7523   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7524                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7525 
7526   // TODO: Any other flags to propagate?
7527   SDNodeFlags Flags;
7528   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7529 
7530   // For strict nodes, source is the second operand.
7531   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7532   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
7533   assert(Src.getValueType().isFloatingPoint());
7534   if (Src.getValueType() == MVT::f32) {
7535     if (IsStrict) {
7536       Src =
7537           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
7538                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
7539       Chain = Src.getValue(1);
7540     } else
7541       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7542   }
7543   SDValue Conv;
7544   unsigned Opc = ISD::DELETED_NODE;
7545   switch (Op.getSimpleValueType().SimpleTy) {
7546   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7547   case MVT::i32:
7548     Opc = IsSigned ? PPCISD::FCTIWZ
7549                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
7550     break;
7551   case MVT::i64:
7552     assert((IsSigned || Subtarget.hasFPCVT()) &&
7553            "i64 FP_TO_UINT is supported only with FPCVT");
7554     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
7555   }
7556   if (IsStrict) {
7557     Opc = getPPCStrictOpcode(Opc);
7558     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
7559                        {Chain, Src}, Flags);
7560   } else {
7561     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
7562   }
7563   return Conv;
7564 }
7565 
7566 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7567                                                SelectionDAG &DAG,
7568                                                const SDLoc &dl) const {
7569   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
7570   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7571                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7572   bool IsStrict = Op->isStrictFPOpcode();
7573 
7574   // Convert the FP value to an int value through memory.
7575   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7576                   (IsSigned || Subtarget.hasFPCVT());
7577   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7578   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7579   MachinePointerInfo MPI =
7580       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7581 
7582   // Emit a store to the stack slot.
7583   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
7584   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
7585   if (i32Stack) {
7586     MachineFunction &MF = DAG.getMachineFunction();
7587     Alignment = Align(4);
7588     MachineMemOperand *MMO =
7589         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
7590     SDValue Ops[] = { Chain, Tmp, FIPtr };
7591     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7592               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7593   } else
7594     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
7595 
7596   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7597   // add in a bias on big endian.
7598   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7599     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7600                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7601     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7602   }
7603 
7604   RLI.Chain = Chain;
7605   RLI.Ptr = FIPtr;
7606   RLI.MPI = MPI;
7607   RLI.Alignment = Alignment;
7608 }
7609 
7610 /// Custom lowers floating point to integer conversions to use
7611 /// the direct move instructions available in ISA 2.07 to avoid the
7612 /// need for load/store combinations.
7613 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7614                                                     SelectionDAG &DAG,
7615                                                     const SDLoc &dl) const {
7616   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
7617   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
7618   if (Op->isStrictFPOpcode())
7619     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
7620   else
7621     return Mov;
7622 }
7623 
7624 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7625                                           const SDLoc &dl) const {
7626   bool IsStrict = Op->isStrictFPOpcode();
7627   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7628                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7629   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7630   EVT SrcVT = Src.getValueType();
7631   EVT DstVT = Op.getValueType();
7632 
7633   // FP to INT conversions are legal for f128.
7634   if (SrcVT == MVT::f128)
7635     return Subtarget.hasP9Vector() ? Op : SDValue();
7636 
7637   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7638   // PPC (the libcall is not available).
7639   if (SrcVT == MVT::ppcf128) {
7640     if (DstVT == MVT::i32) {
7641       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
7642       // set other fast-math flags to FP operations in both strict and
7643       // non-strict cases. (FP_TO_SINT, FSUB)
7644       SDNodeFlags Flags;
7645       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7646 
7647       if (IsSigned) {
7648         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
7649                                  DAG.getIntPtrConstant(0, dl));
7650         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
7651                                  DAG.getIntPtrConstant(1, dl));
7652 
7653         // Add the two halves of the long double in round-to-zero mode, and use
7654         // a smaller FP_TO_SINT.
7655         if (IsStrict) {
7656           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
7657                                     DAG.getVTList(MVT::f64, MVT::Other),
7658                                     {Op.getOperand(0), Lo, Hi}, Flags);
7659           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
7660                              DAG.getVTList(MVT::i32, MVT::Other),
7661                              {Res.getValue(1), Res}, Flags);
7662         } else {
7663           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7664           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7665         }
7666       } else {
7667         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7668         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7669         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7670         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
7671         if (IsStrict) {
7672           // Sel = Src < 0x80000000
7673           // FltOfs = select Sel, 0.0, 0x80000000
7674           // IntOfs = select Sel, 0, 0x80000000
7675           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7676           SDValue Chain = Op.getOperand(0);
7677           EVT SetCCVT =
7678               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7679           EVT DstSetCCVT =
7680               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7681           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7682                                      Chain, true);
7683           Chain = Sel.getValue(1);
7684 
7685           SDValue FltOfs = DAG.getSelect(
7686               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7687           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7688 
7689           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
7690                                     DAG.getVTList(SrcVT, MVT::Other),
7691                                     {Chain, Src, FltOfs}, Flags);
7692           Chain = Val.getValue(1);
7693           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
7694                                      DAG.getVTList(DstVT, MVT::Other),
7695                                      {Chain, Val}, Flags);
7696           Chain = SInt.getValue(1);
7697           SDValue IntOfs = DAG.getSelect(
7698               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
7699           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7700           return DAG.getMergeValues({Result, Chain}, dl);
7701         } else {
7702           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7703           // FIXME: generated code sucks.
7704           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
7705           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7706           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
7707           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
7708           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
7709         }
7710       }
7711     }
7712 
7713     return SDValue();
7714   }
7715 
7716   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7717     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7718 
7719   ReuseLoadInfo RLI;
7720   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7721 
7722   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7723                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7724 }
7725 
7726 // We're trying to insert a regular store, S, and then a load, L. If the
7727 // incoming value, O, is a load, we might just be able to have our load use the
7728 // address used by O. However, we don't know if anything else will store to
7729 // that address before we can load from it. To prevent this situation, we need
7730 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7731 // the same chain operand as O, we create a token factor from the chain results
7732 // of O and L, and we replace all uses of O's chain result with that token
7733 // factor (see spliceIntoChain below for this last part).
7734 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7735                                             ReuseLoadInfo &RLI,
7736                                             SelectionDAG &DAG,
7737                                             ISD::LoadExtType ET) const {
7738   // Conservatively skip reusing for constrained FP nodes.
7739   if (Op->isStrictFPOpcode())
7740     return false;
7741 
7742   SDLoc dl(Op);
7743   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
7744                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
7745   if (ET == ISD::NON_EXTLOAD &&
7746       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
7747       isOperationLegalOrCustom(Op.getOpcode(),
7748                                Op.getOperand(0).getValueType())) {
7749 
7750     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7751     return true;
7752   }
7753 
7754   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7755   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7756       LD->isNonTemporal())
7757     return false;
7758   if (LD->getMemoryVT() != MemVT)
7759     return false;
7760 
7761   // If the result of the load is an illegal type, then we can't build a
7762   // valid chain for reuse since the legalised loads and token factor node that
7763   // ties the legalised loads together uses a different output chain then the
7764   // illegal load.
7765   if (!isTypeLegal(LD->getValueType(0)))
7766     return false;
7767 
7768   RLI.Ptr = LD->getBasePtr();
7769   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7770     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7771            "Non-pre-inc AM on PPC?");
7772     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7773                           LD->getOffset());
7774   }
7775 
7776   RLI.Chain = LD->getChain();
7777   RLI.MPI = LD->getPointerInfo();
7778   RLI.IsDereferenceable = LD->isDereferenceable();
7779   RLI.IsInvariant = LD->isInvariant();
7780   RLI.Alignment = LD->getAlign();
7781   RLI.AAInfo = LD->getAAInfo();
7782   RLI.Ranges = LD->getRanges();
7783 
7784   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7785   return true;
7786 }
7787 
7788 // Given the head of the old chain, ResChain, insert a token factor containing
7789 // it and NewResChain, and make users of ResChain now be users of that token
7790 // factor.
7791 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7792 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7793                                         SDValue NewResChain,
7794                                         SelectionDAG &DAG) const {
7795   if (!ResChain)
7796     return;
7797 
7798   SDLoc dl(NewResChain);
7799 
7800   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7801                            NewResChain, DAG.getUNDEF(MVT::Other));
7802   assert(TF.getNode() != NewResChain.getNode() &&
7803          "A new TF really is required here");
7804 
7805   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7806   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7807 }
7808 
7809 /// Analyze profitability of direct move
7810 /// prefer float load to int load plus direct move
7811 /// when there is no integer use of int load
7812 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7813   SDNode *Origin = Op.getOperand(0).getNode();
7814   if (Origin->getOpcode() != ISD::LOAD)
7815     return true;
7816 
7817   // If there is no LXSIBZX/LXSIHZX, like Power8,
7818   // prefer direct move if the memory size is 1 or 2 bytes.
7819   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7820   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7821     return true;
7822 
7823   for (SDNode::use_iterator UI = Origin->use_begin(),
7824                             UE = Origin->use_end();
7825        UI != UE; ++UI) {
7826 
7827     // Only look at the users of the loaded value.
7828     if (UI.getUse().get().getResNo() != 0)
7829       continue;
7830 
7831     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7832         UI->getOpcode() != ISD::UINT_TO_FP &&
7833         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
7834         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
7835       return true;
7836   }
7837 
7838   return false;
7839 }
7840 
7841 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
7842                               const PPCSubtarget &Subtarget,
7843                               SDValue Chain = SDValue()) {
7844   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
7845                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
7846   SDLoc dl(Op);
7847 
7848   // TODO: Any other flags to propagate?
7849   SDNodeFlags Flags;
7850   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7851 
7852   // If we have FCFIDS, then use it when converting to single-precision.
7853   // Otherwise, convert to double-precision and then round.
7854   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
7855   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
7856                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
7857   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
7858   if (Op->isStrictFPOpcode()) {
7859     if (!Chain)
7860       Chain = Op.getOperand(0);
7861     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
7862                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
7863   } else
7864     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
7865 }
7866 
7867 /// Custom lowers integer to floating point conversions to use
7868 /// the direct move instructions available in ISA 2.07 to avoid the
7869 /// need for load/store combinations.
7870 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7871                                                     SelectionDAG &DAG,
7872                                                     const SDLoc &dl) const {
7873   assert((Op.getValueType() == MVT::f32 ||
7874           Op.getValueType() == MVT::f64) &&
7875          "Invalid floating point type as target of conversion");
7876   assert(Subtarget.hasFPCVT() &&
7877          "Int to FP conversions with direct moves require FPCVT");
7878   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7879   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7880   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
7881                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
7882   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
7883   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
7884   return convertIntToFP(Op, Mov, DAG, Subtarget);
7885 }
7886 
7887 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7888 
7889   EVT VecVT = Vec.getValueType();
7890   assert(VecVT.isVector() && "Expected a vector type.");
7891   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7892 
7893   EVT EltVT = VecVT.getVectorElementType();
7894   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7895   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7896 
7897   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7898   SmallVector<SDValue, 16> Ops(NumConcat);
7899   Ops[0] = Vec;
7900   SDValue UndefVec = DAG.getUNDEF(VecVT);
7901   for (unsigned i = 1; i < NumConcat; ++i)
7902     Ops[i] = UndefVec;
7903 
7904   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7905 }
7906 
7907 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7908                                                 const SDLoc &dl) const {
7909   bool IsStrict = Op->isStrictFPOpcode();
7910   unsigned Opc = Op.getOpcode();
7911   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7912   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
7913           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
7914          "Unexpected conversion type");
7915   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7916          "Supports conversions to v2f64/v4f32 only.");
7917 
7918   // TODO: Any other flags to propagate?
7919   SDNodeFlags Flags;
7920   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7921 
7922   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
7923   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7924 
7925   SDValue Wide = widenVec(DAG, Src, dl);
7926   EVT WideVT = Wide.getValueType();
7927   unsigned WideNumElts = WideVT.getVectorNumElements();
7928   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7929 
7930   SmallVector<int, 16> ShuffV;
7931   for (unsigned i = 0; i < WideNumElts; ++i)
7932     ShuffV.push_back(i + WideNumElts);
7933 
7934   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7935   int SaveElts = FourEltRes ? 4 : 2;
7936   if (Subtarget.isLittleEndian())
7937     for (int i = 0; i < SaveElts; i++)
7938       ShuffV[i * Stride] = i;
7939   else
7940     for (int i = 1; i <= SaveElts; i++)
7941       ShuffV[i * Stride - 1] = i - 1;
7942 
7943   SDValue ShuffleSrc2 =
7944       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7945   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7946 
7947   SDValue Extend;
7948   if (SignedConv) {
7949     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7950     EVT ExtVT = Src.getValueType();
7951     if (Subtarget.hasP9Altivec())
7952       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
7953                                IntermediateVT.getVectorNumElements());
7954 
7955     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7956                          DAG.getValueType(ExtVT));
7957   } else
7958     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
7959 
7960   if (IsStrict)
7961     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
7962                        {Op.getOperand(0), Extend}, Flags);
7963 
7964   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7965 }
7966 
7967 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7968                                           SelectionDAG &DAG) const {
7969   SDLoc dl(Op);
7970   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
7971                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
7972   bool IsStrict = Op->isStrictFPOpcode();
7973   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7974   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7975 
7976   // TODO: Any other flags to propagate?
7977   SDNodeFlags Flags;
7978   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
7979 
7980   EVT InVT = Src.getValueType();
7981   EVT OutVT = Op.getValueType();
7982   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7983       isOperationCustom(Op.getOpcode(), InVT))
7984     return LowerINT_TO_FPVector(Op, DAG, dl);
7985 
7986   // Conversions to f128 are legal.
7987   if (Op.getValueType() == MVT::f128)
7988     return Subtarget.hasP9Vector() ? Op : SDValue();
7989 
7990   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7991   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7992     return SDValue();
7993 
7994   if (Src.getValueType() == MVT::i1) {
7995     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
7996                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
7997                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
7998     if (IsStrict)
7999       return DAG.getMergeValues({Sel, Chain}, dl);
8000     else
8001       return Sel;
8002   }
8003 
8004   // If we have direct moves, we can do all the conversion, skip the store/load
8005   // however, without FPCVT we can't do most conversions.
8006   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8007       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8008     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8009 
8010   assert((IsSigned || Subtarget.hasFPCVT()) &&
8011          "UINT_TO_FP is supported only with FPCVT");
8012 
8013   if (Src.getValueType() == MVT::i64) {
8014     SDValue SINT = Src;
8015     // When converting to single-precision, we actually need to convert
8016     // to double-precision first and then round to single-precision.
8017     // To avoid double-rounding effects during that operation, we have
8018     // to prepare the input operand.  Bits that might be truncated when
8019     // converting to double-precision are replaced by a bit that won't
8020     // be lost at this stage, but is below the single-precision rounding
8021     // position.
8022     //
8023     // However, if -enable-unsafe-fp-math is in effect, accept double
8024     // rounding to avoid the extra overhead.
8025     if (Op.getValueType() == MVT::f32 &&
8026         !Subtarget.hasFPCVT() &&
8027         !DAG.getTarget().Options.UnsafeFPMath) {
8028 
8029       // Twiddle input to make sure the low 11 bits are zero.  (If this
8030       // is the case, we are guaranteed the value will fit into the 53 bit
8031       // mantissa of an IEEE double-precision value without rounding.)
8032       // If any of those low 11 bits were not zero originally, make sure
8033       // bit 12 (value 2048) is set instead, so that the final rounding
8034       // to single-precision gets the correct result.
8035       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8036                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8037       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8038                           Round, DAG.getConstant(2047, dl, MVT::i64));
8039       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8040       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8041                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8042 
8043       // However, we cannot use that value unconditionally: if the magnitude
8044       // of the input value is small, the bit-twiddling we did above might
8045       // end up visibly changing the output.  Fortunately, in that case, we
8046       // don't need to twiddle bits since the original input will convert
8047       // exactly to double-precision floating-point already.  Therefore,
8048       // construct a conditional to use the original value if the top 11
8049       // bits are all sign-bit copies, and use the rounded value computed
8050       // above otherwise.
8051       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8052                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8053       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8054                          Cond, DAG.getConstant(1, dl, MVT::i64));
8055       Cond = DAG.getSetCC(
8056           dl,
8057           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8058           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8059 
8060       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8061     }
8062 
8063     ReuseLoadInfo RLI;
8064     SDValue Bits;
8065 
8066     MachineFunction &MF = DAG.getMachineFunction();
8067     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8068       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8069                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8070       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8071     } else if (Subtarget.hasLFIWAX() &&
8072                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8073       MachineMemOperand *MMO =
8074         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8075                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8076       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8077       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8078                                      DAG.getVTList(MVT::f64, MVT::Other),
8079                                      Ops, MVT::i32, MMO);
8080       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8081     } else if (Subtarget.hasFPCVT() &&
8082                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8083       MachineMemOperand *MMO =
8084         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8085                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8086       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8087       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8088                                      DAG.getVTList(MVT::f64, MVT::Other),
8089                                      Ops, MVT::i32, MMO);
8090       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8091     } else if (((Subtarget.hasLFIWAX() &&
8092                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8093                 (Subtarget.hasFPCVT() &&
8094                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8095                SINT.getOperand(0).getValueType() == MVT::i32) {
8096       MachineFrameInfo &MFI = MF.getFrameInfo();
8097       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8098 
8099       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8100       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8101 
8102       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8103                                    MachinePointerInfo::getFixedStack(
8104                                        DAG.getMachineFunction(), FrameIdx));
8105       Chain = Store;
8106 
8107       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8108              "Expected an i32 store");
8109 
8110       RLI.Ptr = FIdx;
8111       RLI.Chain = Chain;
8112       RLI.MPI =
8113           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8114       RLI.Alignment = Align(4);
8115 
8116       MachineMemOperand *MMO =
8117         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8118                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8119       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8120       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8121                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8122                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8123                                      Ops, MVT::i32, MMO);
8124       Chain = Bits.getValue(1);
8125     } else
8126       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8127 
8128     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8129     if (IsStrict)
8130       Chain = FP.getValue(1);
8131 
8132     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8133       if (IsStrict)
8134         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8135                          DAG.getVTList(MVT::f32, MVT::Other),
8136                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8137       else
8138         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8139                          DAG.getIntPtrConstant(0, dl));
8140     }
8141     return FP;
8142   }
8143 
8144   assert(Src.getValueType() == MVT::i32 &&
8145          "Unhandled INT_TO_FP type in custom expander!");
8146   // Since we only generate this in 64-bit mode, we can take advantage of
8147   // 64-bit registers.  In particular, sign extend the input value into the
8148   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8149   // then lfd it and fcfid it.
8150   MachineFunction &MF = DAG.getMachineFunction();
8151   MachineFrameInfo &MFI = MF.getFrameInfo();
8152   EVT PtrVT = getPointerTy(MF.getDataLayout());
8153 
8154   SDValue Ld;
8155   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8156     ReuseLoadInfo RLI;
8157     bool ReusingLoad;
8158     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8159       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8160       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8161 
8162       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8163                                    MachinePointerInfo::getFixedStack(
8164                                        DAG.getMachineFunction(), FrameIdx));
8165       Chain = Store;
8166 
8167       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8168              "Expected an i32 store");
8169 
8170       RLI.Ptr = FIdx;
8171       RLI.Chain = Chain;
8172       RLI.MPI =
8173           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8174       RLI.Alignment = Align(4);
8175     }
8176 
8177     MachineMemOperand *MMO =
8178       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8179                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8180     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8181     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8182                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8183                                  MVT::i32, MMO);
8184     Chain = Ld.getValue(1);
8185     if (ReusingLoad)
8186       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8187   } else {
8188     assert(Subtarget.isPPC64() &&
8189            "i32->FP without LFIWAX supported only on PPC64");
8190 
8191     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8192     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8193 
8194     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8195 
8196     // STD the extended value into the stack slot.
8197     SDValue Store = DAG.getStore(
8198         Chain, dl, Ext64, FIdx,
8199         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8200     Chain = Store;
8201 
8202     // Load the value as a double.
8203     Ld = DAG.getLoad(
8204         MVT::f64, dl, Chain, FIdx,
8205         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8206     Chain = Ld.getValue(1);
8207   }
8208 
8209   // FCFID it and return it.
8210   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8211   if (IsStrict)
8212     Chain = FP.getValue(1);
8213   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8214     if (IsStrict)
8215       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8216                        DAG.getVTList(MVT::f32, MVT::Other),
8217                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8218     else
8219       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8220                        DAG.getIntPtrConstant(0, dl));
8221   }
8222   return FP;
8223 }
8224 
8225 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8226                                             SelectionDAG &DAG) const {
8227   SDLoc dl(Op);
8228   /*
8229    The rounding mode is in bits 30:31 of FPSR, and has the following
8230    settings:
8231      00 Round to nearest
8232      01 Round to 0
8233      10 Round to +inf
8234      11 Round to -inf
8235 
8236   FLT_ROUNDS, on the other hand, expects the following:
8237     -1 Undefined
8238      0 Round to 0
8239      1 Round to nearest
8240      2 Round to +inf
8241      3 Round to -inf
8242 
8243   To perform the conversion, we do:
8244     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8245   */
8246 
8247   MachineFunction &MF = DAG.getMachineFunction();
8248   EVT VT = Op.getValueType();
8249   EVT PtrVT = getPointerTy(MF.getDataLayout());
8250 
8251   // Save FP Control Word to register
8252   SDValue Chain = Op.getOperand(0);
8253   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8254   Chain = MFFS.getValue(1);
8255 
8256   SDValue CWD;
8257   if (isTypeLegal(MVT::i64)) {
8258     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8259                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8260   } else {
8261     // Save FP register to stack slot
8262     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8263     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8264     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8265 
8266     // Load FP Control Word from low 32 bits of stack slot.
8267     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8268            "Stack slot adjustment is valid only on big endian subtargets!");
8269     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8270     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8271     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8272     Chain = CWD.getValue(1);
8273   }
8274 
8275   // Transform as necessary
8276   SDValue CWD1 =
8277     DAG.getNode(ISD::AND, dl, MVT::i32,
8278                 CWD, DAG.getConstant(3, dl, MVT::i32));
8279   SDValue CWD2 =
8280     DAG.getNode(ISD::SRL, dl, MVT::i32,
8281                 DAG.getNode(ISD::AND, dl, MVT::i32,
8282                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8283                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8284                             DAG.getConstant(3, dl, MVT::i32)),
8285                 DAG.getConstant(1, dl, MVT::i32));
8286 
8287   SDValue RetVal =
8288     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8289 
8290   RetVal =
8291       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8292                   dl, VT, RetVal);
8293 
8294   return DAG.getMergeValues({RetVal, Chain}, dl);
8295 }
8296 
8297 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8298   EVT VT = Op.getValueType();
8299   unsigned BitWidth = VT.getSizeInBits();
8300   SDLoc dl(Op);
8301   assert(Op.getNumOperands() == 3 &&
8302          VT == Op.getOperand(1).getValueType() &&
8303          "Unexpected SHL!");
8304 
8305   // Expand into a bunch of logical ops.  Note that these ops
8306   // depend on the PPC behavior for oversized shift amounts.
8307   SDValue Lo = Op.getOperand(0);
8308   SDValue Hi = Op.getOperand(1);
8309   SDValue Amt = Op.getOperand(2);
8310   EVT AmtVT = Amt.getValueType();
8311 
8312   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8313                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8314   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8315   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8316   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8317   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8318                              DAG.getConstant(-BitWidth, dl, AmtVT));
8319   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8320   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8321   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8322   SDValue OutOps[] = { OutLo, OutHi };
8323   return DAG.getMergeValues(OutOps, dl);
8324 }
8325 
8326 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8327   EVT VT = Op.getValueType();
8328   SDLoc dl(Op);
8329   unsigned BitWidth = VT.getSizeInBits();
8330   assert(Op.getNumOperands() == 3 &&
8331          VT == Op.getOperand(1).getValueType() &&
8332          "Unexpected SRL!");
8333 
8334   // Expand into a bunch of logical ops.  Note that these ops
8335   // depend on the PPC behavior for oversized shift amounts.
8336   SDValue Lo = Op.getOperand(0);
8337   SDValue Hi = Op.getOperand(1);
8338   SDValue Amt = Op.getOperand(2);
8339   EVT AmtVT = Amt.getValueType();
8340 
8341   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8342                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8343   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8344   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8345   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8346   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8347                              DAG.getConstant(-BitWidth, dl, AmtVT));
8348   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8349   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8350   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8351   SDValue OutOps[] = { OutLo, OutHi };
8352   return DAG.getMergeValues(OutOps, dl);
8353 }
8354 
8355 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8356   SDLoc dl(Op);
8357   EVT VT = Op.getValueType();
8358   unsigned BitWidth = VT.getSizeInBits();
8359   assert(Op.getNumOperands() == 3 &&
8360          VT == Op.getOperand(1).getValueType() &&
8361          "Unexpected SRA!");
8362 
8363   // Expand into a bunch of logical ops, followed by a select_cc.
8364   SDValue Lo = Op.getOperand(0);
8365   SDValue Hi = Op.getOperand(1);
8366   SDValue Amt = Op.getOperand(2);
8367   EVT AmtVT = Amt.getValueType();
8368 
8369   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8370                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8371   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8372   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8373   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8374   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8375                              DAG.getConstant(-BitWidth, dl, AmtVT));
8376   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8377   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8378   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8379                                   Tmp4, Tmp6, ISD::SETLE);
8380   SDValue OutOps[] = { OutLo, OutHi };
8381   return DAG.getMergeValues(OutOps, dl);
8382 }
8383 
8384 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8385                                             SelectionDAG &DAG) const {
8386   SDLoc dl(Op);
8387   EVT VT = Op.getValueType();
8388   unsigned BitWidth = VT.getSizeInBits();
8389 
8390   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8391   SDValue X = Op.getOperand(0);
8392   SDValue Y = Op.getOperand(1);
8393   SDValue Z = Op.getOperand(2);
8394   EVT AmtVT = Z.getValueType();
8395 
8396   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8397   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8398   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8399   // on PowerPC shift by BW being well defined.
8400   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8401                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8402   SDValue SubZ =
8403       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8404   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8405   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8406   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8407 }
8408 
8409 //===----------------------------------------------------------------------===//
8410 // Vector related lowering.
8411 //
8412 
8413 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8414 /// element size of SplatSize. Cast the result to VT.
8415 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8416                                       SelectionDAG &DAG, const SDLoc &dl) {
8417   static const MVT VTys[] = { // canonical VT to use for each size.
8418     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8419   };
8420 
8421   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8422 
8423   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8424   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8425     SplatSize = 1;
8426     Val = 0xFF;
8427   }
8428 
8429   EVT CanonicalVT = VTys[SplatSize-1];
8430 
8431   // Build a canonical splat for this value.
8432   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8433 }
8434 
8435 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8436 /// specified intrinsic ID.
8437 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8438                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8439   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8440   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8441                      DAG.getConstant(IID, dl, MVT::i32), Op);
8442 }
8443 
8444 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8445 /// specified intrinsic ID.
8446 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8447                                 SelectionDAG &DAG, const SDLoc &dl,
8448                                 EVT DestVT = MVT::Other) {
8449   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8450   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8451                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8452 }
8453 
8454 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8455 /// specified intrinsic ID.
8456 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8457                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8458                                 EVT DestVT = MVT::Other) {
8459   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8460   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8461                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8462 }
8463 
8464 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8465 /// amount.  The result has the specified value type.
8466 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8467                            SelectionDAG &DAG, const SDLoc &dl) {
8468   // Force LHS/RHS to be the right type.
8469   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8470   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8471 
8472   int Ops[16];
8473   for (unsigned i = 0; i != 16; ++i)
8474     Ops[i] = i + Amt;
8475   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8476   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8477 }
8478 
8479 /// Do we have an efficient pattern in a .td file for this node?
8480 ///
8481 /// \param V - pointer to the BuildVectorSDNode being matched
8482 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8483 ///
8484 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8485 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8486 /// the opposite is true (expansion is beneficial) are:
8487 /// - The node builds a vector out of integers that are not 32 or 64-bits
8488 /// - The node builds a vector out of constants
8489 /// - The node is a "load-and-splat"
8490 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8491 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8492                                             bool HasDirectMove,
8493                                             bool HasP8Vector) {
8494   EVT VecVT = V->getValueType(0);
8495   bool RightType = VecVT == MVT::v2f64 ||
8496     (HasP8Vector && VecVT == MVT::v4f32) ||
8497     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8498   if (!RightType)
8499     return false;
8500 
8501   bool IsSplat = true;
8502   bool IsLoad = false;
8503   SDValue Op0 = V->getOperand(0);
8504 
8505   // This function is called in a block that confirms the node is not a constant
8506   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8507   // different constants.
8508   if (V->isConstant())
8509     return false;
8510   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8511     if (V->getOperand(i).isUndef())
8512       return false;
8513     // We want to expand nodes that represent load-and-splat even if the
8514     // loaded value is a floating point truncation or conversion to int.
8515     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8516         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8517          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8518         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8519          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8520         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8521          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8522       IsLoad = true;
8523     // If the operands are different or the input is not a load and has more
8524     // uses than just this BV node, then it isn't a splat.
8525     if (V->getOperand(i) != Op0 ||
8526         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8527       IsSplat = false;
8528   }
8529   return !(IsSplat && IsLoad);
8530 }
8531 
8532 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8533 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8534 
8535   SDLoc dl(Op);
8536   SDValue Op0 = Op->getOperand(0);
8537 
8538   if ((Op.getValueType() != MVT::f128) ||
8539       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8540       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8541       (Op0.getOperand(1).getValueType() != MVT::i64))
8542     return SDValue();
8543 
8544   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8545                      Op0.getOperand(1));
8546 }
8547 
8548 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8549   const SDValue *InputLoad = &Op;
8550   if (InputLoad->getOpcode() == ISD::BITCAST)
8551     InputLoad = &InputLoad->getOperand(0);
8552   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8553       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8554     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8555     InputLoad = &InputLoad->getOperand(0);
8556   }
8557   if (InputLoad->getOpcode() != ISD::LOAD)
8558     return nullptr;
8559   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8560   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8561 }
8562 
8563 // Convert the argument APFloat to a single precision APFloat if there is no
8564 // loss in information during the conversion to single precision APFloat and the
8565 // resulting number is not a denormal number. Return true if successful.
8566 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
8567   APFloat APFloatToConvert = ArgAPFloat;
8568   bool LosesInfo = true;
8569   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8570                            &LosesInfo);
8571   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
8572   if (Success)
8573     ArgAPFloat = APFloatToConvert;
8574   return Success;
8575 }
8576 
8577 // Bitcast the argument APInt to a double and convert it to a single precision
8578 // APFloat, bitcast the APFloat to an APInt and assign it to the original
8579 // argument if there is no loss in information during the conversion from
8580 // double to single precision APFloat and the resulting number is not a denormal
8581 // number. Return true if successful.
8582 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
8583   double DpValue = ArgAPInt.bitsToDouble();
8584   APFloat APFloatDp(DpValue);
8585   bool Success = convertToNonDenormSingle(APFloatDp);
8586   if (Success)
8587     ArgAPInt = APFloatDp.bitcastToAPInt();
8588   return Success;
8589 }
8590 
8591 // If this is a case we can't handle, return null and let the default
8592 // expansion code take care of it.  If we CAN select this case, and if it
8593 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8594 // this case more efficiently than a constant pool load, lower it to the
8595 // sequence of ops that should be used.
8596 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8597                                              SelectionDAG &DAG) const {
8598   SDLoc dl(Op);
8599   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8600   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8601 
8602   // Check if this is a splat of a constant value.
8603   APInt APSplatBits, APSplatUndef;
8604   unsigned SplatBitSize;
8605   bool HasAnyUndefs;
8606   bool BVNIsConstantSplat =
8607       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8608                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
8609 
8610   // If it is a splat of a double, check if we can shrink it to a 32 bit
8611   // non-denormal float which when converted back to double gives us the same
8612   // double. This is to exploit the XXSPLTIDP instruction.
8613   // If we lose precision, we use XXSPLTI32DX.
8614   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
8615       Subtarget.hasPrefixInstrs()) {
8616     // Check the type first to short-circuit so we don't modify APSplatBits if
8617     // this block isn't executed.
8618     if ((Op->getValueType(0) == MVT::v2f64) &&
8619         convertToNonDenormSingle(APSplatBits)) {
8620       SDValue SplatNode = DAG.getNode(
8621           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
8622           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
8623       return DAG.getBitcast(Op.getValueType(), SplatNode);
8624     } else {
8625       // We may lose precision, so we have to use XXSPLTI32DX.
8626 
8627       uint32_t Hi =
8628           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
8629       uint32_t Lo =
8630           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
8631       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
8632 
8633       if (!Hi || !Lo)
8634         // If either load is 0, then we should generate XXLXOR to set to 0.
8635         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
8636 
8637       if (Hi)
8638         SplatNode = DAG.getNode(
8639             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
8640             DAG.getTargetConstant(0, dl, MVT::i32),
8641             DAG.getTargetConstant(Hi, dl, MVT::i32));
8642 
8643       if (Lo)
8644         SplatNode =
8645             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
8646                         DAG.getTargetConstant(1, dl, MVT::i32),
8647                         DAG.getTargetConstant(Lo, dl, MVT::i32));
8648 
8649       return DAG.getBitcast(Op.getValueType(), SplatNode);
8650     }
8651   }
8652 
8653   if (!BVNIsConstantSplat || SplatBitSize > 32) {
8654 
8655     bool IsPermutedLoad = false;
8656     const SDValue *InputLoad =
8657         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
8658     // Handle load-and-splat patterns as we have instructions that will do this
8659     // in one go.
8660     if (InputLoad && DAG.isSplatValue(Op, true)) {
8661       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8662 
8663       // We have handling for 4 and 8 byte elements.
8664       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8665 
8666       // Checking for a single use of this load, we have to check for vector
8667       // width (128 bits) / ElementSize uses (since each operand of the
8668       // BUILD_VECTOR is a separate use of the value.
8669       unsigned NumUsesOfInputLD = 128 / ElementSize;
8670       for (SDValue BVInOp : Op->ops())
8671         if (BVInOp.isUndef())
8672           NumUsesOfInputLD--;
8673       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
8674       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
8675           ((Subtarget.hasVSX() && ElementSize == 64) ||
8676            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8677         SDValue Ops[] = {
8678           LD->getChain(),    // Chain
8679           LD->getBasePtr(),  // Ptr
8680           DAG.getValueType(Op.getValueType()) // VT
8681         };
8682         SDValue LdSplt = DAG.getMemIntrinsicNode(
8683             PPCISD::LD_SPLAT, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8684             Ops, LD->getMemoryVT(), LD->getMemOperand());
8685         // Replace all uses of the output chain of the original load with the
8686         // output chain of the new load.
8687         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
8688                                       LdSplt.getValue(1));
8689         return LdSplt;
8690       }
8691     }
8692 
8693     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
8694     // 32-bits can be lowered to VSX instructions under certain conditions.
8695     // Without VSX, there is no pattern more efficient than expanding the node.
8696     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
8697         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8698                                         Subtarget.hasP8Vector()))
8699       return Op;
8700     return SDValue();
8701   }
8702 
8703   uint64_t SplatBits = APSplatBits.getZExtValue();
8704   uint64_t SplatUndef = APSplatUndef.getZExtValue();
8705   unsigned SplatSize = SplatBitSize / 8;
8706 
8707   // First, handle single instruction cases.
8708 
8709   // All zeros?
8710   if (SplatBits == 0) {
8711     // Canonicalize all zero vectors to be v4i32.
8712     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8713       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8714       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8715     }
8716     return Op;
8717   }
8718 
8719   // We have XXSPLTIW for constant splats four bytes wide.
8720   // Given vector length is a multiple of 4, 2-byte splats can be replaced
8721   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
8722   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
8723   // turned into a 4-byte splat of 0xABABABAB.
8724   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
8725     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
8726                                   Op.getValueType(), DAG, dl);
8727 
8728   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
8729     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8730                                   dl);
8731 
8732   // We have XXSPLTIB for constant splats one byte wide.
8733   if (Subtarget.hasP9Vector() && SplatSize == 1)
8734     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8735                                   dl);
8736 
8737   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8738   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8739                     (32-SplatBitSize));
8740   if (SextVal >= -16 && SextVal <= 15)
8741     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
8742                                   dl);
8743 
8744   // Two instruction sequences.
8745 
8746   // If this value is in the range [-32,30] and is even, use:
8747   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8748   // If this value is in the range [17,31] and is odd, use:
8749   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8750   // If this value is in the range [-31,-17] and is odd, use:
8751   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8752   // Note the last two are three-instruction sequences.
8753   if (SextVal >= -32 && SextVal <= 31) {
8754     // To avoid having these optimizations undone by constant folding,
8755     // we convert to a pseudo that will be expanded later into one of
8756     // the above forms.
8757     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8758     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8759               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8760     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8761     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8762     if (VT == Op.getValueType())
8763       return RetVal;
8764     else
8765       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8766   }
8767 
8768   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8769   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8770   // for fneg/fabs.
8771   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8772     // Make -1 and vspltisw -1:
8773     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
8774 
8775     // Make the VSLW intrinsic, computing 0x8000_0000.
8776     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8777                                    OnesV, DAG, dl);
8778 
8779     // xor by OnesV to invert it.
8780     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8781     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8782   }
8783 
8784   // Check to see if this is a wide variety of vsplti*, binop self cases.
8785   static const signed char SplatCsts[] = {
8786     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8787     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8788   };
8789 
8790   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8791     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8792     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8793     int i = SplatCsts[idx];
8794 
8795     // Figure out what shift amount will be used by altivec if shifted by i in
8796     // this splat size.
8797     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8798 
8799     // vsplti + shl self.
8800     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8801       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
8802       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8803         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8804         Intrinsic::ppc_altivec_vslw
8805       };
8806       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8807       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8808     }
8809 
8810     // vsplti + srl self.
8811     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8812       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
8813       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8814         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8815         Intrinsic::ppc_altivec_vsrw
8816       };
8817       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8818       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8819     }
8820 
8821     // vsplti + rol self.
8822     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8823                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8824       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
8825       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8826         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8827         Intrinsic::ppc_altivec_vrlw
8828       };
8829       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8830       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8831     }
8832 
8833     // t = vsplti c, result = vsldoi t, t, 1
8834     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8835       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
8836       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8837       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8838     }
8839     // t = vsplti c, result = vsldoi t, t, 2
8840     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8841       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
8842       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8843       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8844     }
8845     // t = vsplti c, result = vsldoi t, t, 3
8846     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8847       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
8848       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8849       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8850     }
8851   }
8852 
8853   return SDValue();
8854 }
8855 
8856 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8857 /// the specified operations to build the shuffle.
8858 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8859                                       SDValue RHS, SelectionDAG &DAG,
8860                                       const SDLoc &dl) {
8861   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8862   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8863   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8864 
8865   enum {
8866     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8867     OP_VMRGHW,
8868     OP_VMRGLW,
8869     OP_VSPLTISW0,
8870     OP_VSPLTISW1,
8871     OP_VSPLTISW2,
8872     OP_VSPLTISW3,
8873     OP_VSLDOI4,
8874     OP_VSLDOI8,
8875     OP_VSLDOI12
8876   };
8877 
8878   if (OpNum == OP_COPY) {
8879     if (LHSID == (1*9+2)*9+3) return LHS;
8880     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8881     return RHS;
8882   }
8883 
8884   SDValue OpLHS, OpRHS;
8885   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8886   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8887 
8888   int ShufIdxs[16];
8889   switch (OpNum) {
8890   default: llvm_unreachable("Unknown i32 permute!");
8891   case OP_VMRGHW:
8892     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8893     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8894     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8895     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8896     break;
8897   case OP_VMRGLW:
8898     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8899     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8900     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8901     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8902     break;
8903   case OP_VSPLTISW0:
8904     for (unsigned i = 0; i != 16; ++i)
8905       ShufIdxs[i] = (i&3)+0;
8906     break;
8907   case OP_VSPLTISW1:
8908     for (unsigned i = 0; i != 16; ++i)
8909       ShufIdxs[i] = (i&3)+4;
8910     break;
8911   case OP_VSPLTISW2:
8912     for (unsigned i = 0; i != 16; ++i)
8913       ShufIdxs[i] = (i&3)+8;
8914     break;
8915   case OP_VSPLTISW3:
8916     for (unsigned i = 0; i != 16; ++i)
8917       ShufIdxs[i] = (i&3)+12;
8918     break;
8919   case OP_VSLDOI4:
8920     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8921   case OP_VSLDOI8:
8922     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8923   case OP_VSLDOI12:
8924     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8925   }
8926   EVT VT = OpLHS.getValueType();
8927   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8928   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8929   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8930   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8931 }
8932 
8933 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8934 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8935 /// SDValue.
8936 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8937                                            SelectionDAG &DAG) const {
8938   const unsigned BytesInVector = 16;
8939   bool IsLE = Subtarget.isLittleEndian();
8940   SDLoc dl(N);
8941   SDValue V1 = N->getOperand(0);
8942   SDValue V2 = N->getOperand(1);
8943   unsigned ShiftElts = 0, InsertAtByte = 0;
8944   bool Swap = false;
8945 
8946   // Shifts required to get the byte we want at element 7.
8947   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8948                                    0, 15, 14, 13, 12, 11, 10, 9};
8949   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8950                                 1, 2,  3,  4,  5,  6,  7,  8};
8951 
8952   ArrayRef<int> Mask = N->getMask();
8953   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8954 
8955   // For each mask element, find out if we're just inserting something
8956   // from V2 into V1 or vice versa.
8957   // Possible permutations inserting an element from V2 into V1:
8958   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8959   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8960   //   ...
8961   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8962   // Inserting from V1 into V2 will be similar, except mask range will be
8963   // [16,31].
8964 
8965   bool FoundCandidate = false;
8966   // If both vector operands for the shuffle are the same vector, the mask
8967   // will contain only elements from the first one and the second one will be
8968   // undef.
8969   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8970   // Go through the mask of half-words to find an element that's being moved
8971   // from one vector to the other.
8972   for (unsigned i = 0; i < BytesInVector; ++i) {
8973     unsigned CurrentElement = Mask[i];
8974     // If 2nd operand is undefined, we should only look for element 7 in the
8975     // Mask.
8976     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8977       continue;
8978 
8979     bool OtherElementsInOrder = true;
8980     // Examine the other elements in the Mask to see if they're in original
8981     // order.
8982     for (unsigned j = 0; j < BytesInVector; ++j) {
8983       if (j == i)
8984         continue;
8985       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8986       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8987       // in which we always assume we're always picking from the 1st operand.
8988       int MaskOffset =
8989           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8990       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8991         OtherElementsInOrder = false;
8992         break;
8993       }
8994     }
8995     // If other elements are in original order, we record the number of shifts
8996     // we need to get the element we want into element 7. Also record which byte
8997     // in the vector we should insert into.
8998     if (OtherElementsInOrder) {
8999       // If 2nd operand is undefined, we assume no shifts and no swapping.
9000       if (V2.isUndef()) {
9001         ShiftElts = 0;
9002         Swap = false;
9003       } else {
9004         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9005         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9006                          : BigEndianShifts[CurrentElement & 0xF];
9007         Swap = CurrentElement < BytesInVector;
9008       }
9009       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9010       FoundCandidate = true;
9011       break;
9012     }
9013   }
9014 
9015   if (!FoundCandidate)
9016     return SDValue();
9017 
9018   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9019   // optionally with VECSHL if shift is required.
9020   if (Swap)
9021     std::swap(V1, V2);
9022   if (V2.isUndef())
9023     V2 = V1;
9024   if (ShiftElts) {
9025     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9026                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9027     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9028                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9029   }
9030   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9031                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9032 }
9033 
9034 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9035 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9036 /// SDValue.
9037 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9038                                            SelectionDAG &DAG) const {
9039   const unsigned NumHalfWords = 8;
9040   const unsigned BytesInVector = NumHalfWords * 2;
9041   // Check that the shuffle is on half-words.
9042   if (!isNByteElemShuffleMask(N, 2, 1))
9043     return SDValue();
9044 
9045   bool IsLE = Subtarget.isLittleEndian();
9046   SDLoc dl(N);
9047   SDValue V1 = N->getOperand(0);
9048   SDValue V2 = N->getOperand(1);
9049   unsigned ShiftElts = 0, InsertAtByte = 0;
9050   bool Swap = false;
9051 
9052   // Shifts required to get the half-word we want at element 3.
9053   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9054   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9055 
9056   uint32_t Mask = 0;
9057   uint32_t OriginalOrderLow = 0x1234567;
9058   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9059   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9060   // 32-bit space, only need 4-bit nibbles per element.
9061   for (unsigned i = 0; i < NumHalfWords; ++i) {
9062     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9063     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9064   }
9065 
9066   // For each mask element, find out if we're just inserting something
9067   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9068   // from V2 into V1:
9069   //   X, 1, 2, 3, 4, 5, 6, 7
9070   //   0, X, 2, 3, 4, 5, 6, 7
9071   //   0, 1, X, 3, 4, 5, 6, 7
9072   //   0, 1, 2, X, 4, 5, 6, 7
9073   //   0, 1, 2, 3, X, 5, 6, 7
9074   //   0, 1, 2, 3, 4, X, 6, 7
9075   //   0, 1, 2, 3, 4, 5, X, 7
9076   //   0, 1, 2, 3, 4, 5, 6, X
9077   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9078 
9079   bool FoundCandidate = false;
9080   // Go through the mask of half-words to find an element that's being moved
9081   // from one vector to the other.
9082   for (unsigned i = 0; i < NumHalfWords; ++i) {
9083     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9084     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9085     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9086     uint32_t TargetOrder = 0x0;
9087 
9088     // If both vector operands for the shuffle are the same vector, the mask
9089     // will contain only elements from the first one and the second one will be
9090     // undef.
9091     if (V2.isUndef()) {
9092       ShiftElts = 0;
9093       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9094       TargetOrder = OriginalOrderLow;
9095       Swap = false;
9096       // Skip if not the correct element or mask of other elements don't equal
9097       // to our expected order.
9098       if (MaskOneElt == VINSERTHSrcElem &&
9099           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9100         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9101         FoundCandidate = true;
9102         break;
9103       }
9104     } else { // If both operands are defined.
9105       // Target order is [8,15] if the current mask is between [0,7].
9106       TargetOrder =
9107           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9108       // Skip if mask of other elements don't equal our expected order.
9109       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9110         // We only need the last 3 bits for the number of shifts.
9111         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9112                          : BigEndianShifts[MaskOneElt & 0x7];
9113         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9114         Swap = MaskOneElt < NumHalfWords;
9115         FoundCandidate = true;
9116         break;
9117       }
9118     }
9119   }
9120 
9121   if (!FoundCandidate)
9122     return SDValue();
9123 
9124   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9125   // optionally with VECSHL if shift is required.
9126   if (Swap)
9127     std::swap(V1, V2);
9128   if (V2.isUndef())
9129     V2 = V1;
9130   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9131   if (ShiftElts) {
9132     // Double ShiftElts because we're left shifting on v16i8 type.
9133     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9134                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9135     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9136     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9137                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9138     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9139   }
9140   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9141   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9142                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9143   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9144 }
9145 
9146 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9147 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9148 /// return the default SDValue.
9149 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9150                                               SelectionDAG &DAG) const {
9151   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9152   // to v16i8. Peek through the bitcasts to get the actual operands.
9153   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9154   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9155 
9156   auto ShuffleMask = SVN->getMask();
9157   SDValue VecShuffle(SVN, 0);
9158   SDLoc DL(SVN);
9159 
9160   // Check that we have a four byte shuffle.
9161   if (!isNByteElemShuffleMask(SVN, 4, 1))
9162     return SDValue();
9163 
9164   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9165   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9166     std::swap(LHS, RHS);
9167     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9168     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9169   }
9170 
9171   // Ensure that the RHS is a vector of constants.
9172   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9173   if (!BVN)
9174     return SDValue();
9175 
9176   // Check if RHS is a splat of 4-bytes (or smaller).
9177   APInt APSplatValue, APSplatUndef;
9178   unsigned SplatBitSize;
9179   bool HasAnyUndefs;
9180   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9181                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9182       SplatBitSize > 32)
9183     return SDValue();
9184 
9185   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9186   // The instruction splats a constant C into two words of the source vector
9187   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9188   // Thus we check that the shuffle mask is the equivalent  of
9189   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9190   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9191   // within each word are consecutive, so we only need to check the first byte.
9192   SDValue Index;
9193   bool IsLE = Subtarget.isLittleEndian();
9194   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9195       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9196        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9197     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9198   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9199            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9200             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9201     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9202   else
9203     return SDValue();
9204 
9205   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9206   // for XXSPLTI32DX.
9207   unsigned SplatVal = APSplatValue.getZExtValue();
9208   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9209     SplatVal |= (SplatVal << SplatBitSize);
9210 
9211   SDValue SplatNode = DAG.getNode(
9212       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9213       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9214   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9215 }
9216 
9217 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9218 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9219 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9220 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9221 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9222   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9223   assert(Op.getValueType() == MVT::v1i128 &&
9224          "Only set v1i128 as custom, other type shouldn't reach here!");
9225   SDLoc dl(Op);
9226   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9227   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9228   unsigned SHLAmt = N1.getConstantOperandVal(0);
9229   if (SHLAmt % 8 == 0) {
9230     SmallVector<int, 16> Mask(16, 0);
9231     std::iota(Mask.begin(), Mask.end(), 0);
9232     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9233     if (SDValue Shuffle =
9234             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9235                                  DAG.getUNDEF(MVT::v16i8), Mask))
9236       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9237   }
9238   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9239   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9240                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9241   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9242                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9243   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9244   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9245 }
9246 
9247 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9248 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9249 /// return the code it can be lowered into.  Worst case, it can always be
9250 /// lowered into a vperm.
9251 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9252                                                SelectionDAG &DAG) const {
9253   SDLoc dl(Op);
9254   SDValue V1 = Op.getOperand(0);
9255   SDValue V2 = Op.getOperand(1);
9256   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9257 
9258   // Any nodes that were combined in the target-independent combiner prior
9259   // to vector legalization will not be sent to the target combine. Try to
9260   // combine it here.
9261   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9262     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9263       return NewShuffle;
9264     Op = NewShuffle;
9265     SVOp = cast<ShuffleVectorSDNode>(Op);
9266     V1 = Op.getOperand(0);
9267     V2 = Op.getOperand(1);
9268   }
9269   EVT VT = Op.getValueType();
9270   bool isLittleEndian = Subtarget.isLittleEndian();
9271 
9272   unsigned ShiftElts, InsertAtByte;
9273   bool Swap = false;
9274 
9275   // If this is a load-and-splat, we can do that with a single instruction
9276   // in some cases. However if the load has multiple uses, we don't want to
9277   // combine it because that will just produce multiple loads.
9278   bool IsPermutedLoad = false;
9279   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9280   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9281       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9282       InputLoad->hasOneUse()) {
9283     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9284     int SplatIdx =
9285       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9286 
9287     // The splat index for permuted loads will be in the left half of the vector
9288     // which is strictly wider than the loaded value by 8 bytes. So we need to
9289     // adjust the splat index to point to the correct address in memory.
9290     if (IsPermutedLoad) {
9291       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9292       SplatIdx += IsFourByte ? 2 : 1;
9293       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9294              "Splat of a value outside of the loaded memory");
9295     }
9296 
9297     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9298     // For 4-byte load-and-splat, we need Power9.
9299     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9300       uint64_t Offset = 0;
9301       if (IsFourByte)
9302         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9303       else
9304         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9305 
9306       SDValue BasePtr = LD->getBasePtr();
9307       if (Offset != 0)
9308         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9309                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9310       SDValue Ops[] = {
9311         LD->getChain(),    // Chain
9312         BasePtr,           // BasePtr
9313         DAG.getValueType(Op.getValueType()) // VT
9314       };
9315       SDVTList VTL =
9316         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9317       SDValue LdSplt =
9318         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9319                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9320       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9321       if (LdSplt.getValueType() != SVOp->getValueType(0))
9322         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9323       return LdSplt;
9324     }
9325   }
9326   if (Subtarget.hasP9Vector() &&
9327       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9328                            isLittleEndian)) {
9329     if (Swap)
9330       std::swap(V1, V2);
9331     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9332     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9333     if (ShiftElts) {
9334       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9335                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9336       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9337                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9338       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9339     }
9340     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9341                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9342     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9343   }
9344 
9345   if (Subtarget.hasPrefixInstrs()) {
9346     SDValue SplatInsertNode;
9347     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9348       return SplatInsertNode;
9349   }
9350 
9351   if (Subtarget.hasP9Altivec()) {
9352     SDValue NewISDNode;
9353     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9354       return NewISDNode;
9355 
9356     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9357       return NewISDNode;
9358   }
9359 
9360   if (Subtarget.hasVSX() &&
9361       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9362     if (Swap)
9363       std::swap(V1, V2);
9364     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9365     SDValue Conv2 =
9366         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9367 
9368     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9369                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9370     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9371   }
9372 
9373   if (Subtarget.hasVSX() &&
9374     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9375     if (Swap)
9376       std::swap(V1, V2);
9377     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9378     SDValue Conv2 =
9379         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9380 
9381     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9382                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9383     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9384   }
9385 
9386   if (Subtarget.hasP9Vector()) {
9387      if (PPC::isXXBRHShuffleMask(SVOp)) {
9388       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9389       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9390       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9391     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9392       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9393       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9394       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9395     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9396       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9397       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9398       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9399     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9400       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9401       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9402       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9403     }
9404   }
9405 
9406   if (Subtarget.hasVSX()) {
9407     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9408       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9409 
9410       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9411       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9412                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9413       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9414     }
9415 
9416     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9417     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9418       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9419       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9420       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9421     }
9422   }
9423 
9424   // Cases that are handled by instructions that take permute immediates
9425   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9426   // selected by the instruction selector.
9427   if (V2.isUndef()) {
9428     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9429         PPC::isSplatShuffleMask(SVOp, 2) ||
9430         PPC::isSplatShuffleMask(SVOp, 4) ||
9431         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9432         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9433         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9434         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9435         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9436         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9437         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9438         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9439         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9440         (Subtarget.hasP8Altivec() && (
9441          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9442          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9443          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9444       return Op;
9445     }
9446   }
9447 
9448   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9449   // and produce a fixed permutation.  If any of these match, do not lower to
9450   // VPERM.
9451   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9452   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9453       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9454       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9455       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9456       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9457       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9458       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9459       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9460       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9461       (Subtarget.hasP8Altivec() && (
9462        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9463        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9464        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9465     return Op;
9466 
9467   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9468   // perfect shuffle table to emit an optimal matching sequence.
9469   ArrayRef<int> PermMask = SVOp->getMask();
9470 
9471   unsigned PFIndexes[4];
9472   bool isFourElementShuffle = true;
9473   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9474     unsigned EltNo = 8;   // Start out undef.
9475     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9476       if (PermMask[i*4+j] < 0)
9477         continue;   // Undef, ignore it.
9478 
9479       unsigned ByteSource = PermMask[i*4+j];
9480       if ((ByteSource & 3) != j) {
9481         isFourElementShuffle = false;
9482         break;
9483       }
9484 
9485       if (EltNo == 8) {
9486         EltNo = ByteSource/4;
9487       } else if (EltNo != ByteSource/4) {
9488         isFourElementShuffle = false;
9489         break;
9490       }
9491     }
9492     PFIndexes[i] = EltNo;
9493   }
9494 
9495   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9496   // perfect shuffle vector to determine if it is cost effective to do this as
9497   // discrete instructions, or whether we should use a vperm.
9498   // For now, we skip this for little endian until such time as we have a
9499   // little-endian perfect shuffle table.
9500   if (isFourElementShuffle && !isLittleEndian) {
9501     // Compute the index in the perfect shuffle table.
9502     unsigned PFTableIndex =
9503       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9504 
9505     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9506     unsigned Cost  = (PFEntry >> 30);
9507 
9508     // Determining when to avoid vperm is tricky.  Many things affect the cost
9509     // of vperm, particularly how many times the perm mask needs to be computed.
9510     // For example, if the perm mask can be hoisted out of a loop or is already
9511     // used (perhaps because there are multiple permutes with the same shuffle
9512     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9513     // the loop requires an extra register.
9514     //
9515     // As a compromise, we only emit discrete instructions if the shuffle can be
9516     // generated in 3 or fewer operations.  When we have loop information
9517     // available, if this block is within a loop, we should avoid using vperm
9518     // for 3-operation perms and use a constant pool load instead.
9519     if (Cost < 3)
9520       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9521   }
9522 
9523   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9524   // vector that will get spilled to the constant pool.
9525   if (V2.isUndef()) V2 = V1;
9526 
9527   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9528   // that it is in input element units, not in bytes.  Convert now.
9529 
9530   // For little endian, the order of the input vectors is reversed, and
9531   // the permutation mask is complemented with respect to 31.  This is
9532   // necessary to produce proper semantics with the big-endian-biased vperm
9533   // instruction.
9534   EVT EltVT = V1.getValueType().getVectorElementType();
9535   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9536 
9537   SmallVector<SDValue, 16> ResultMask;
9538   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9539     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9540 
9541     for (unsigned j = 0; j != BytesPerElement; ++j)
9542       if (isLittleEndian)
9543         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9544                                              dl, MVT::i32));
9545       else
9546         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9547                                              MVT::i32));
9548   }
9549 
9550   ShufflesHandledWithVPERM++;
9551   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9552   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9553   LLVM_DEBUG(SVOp->dump());
9554   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9555   LLVM_DEBUG(VPermMask.dump());
9556 
9557   if (isLittleEndian)
9558     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9559                        V2, V1, VPermMask);
9560   else
9561     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9562                        V1, V2, VPermMask);
9563 }
9564 
9565 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9566 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9567 /// information about the intrinsic.
9568 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9569                                  bool &isDot, const PPCSubtarget &Subtarget) {
9570   unsigned IntrinsicID =
9571       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9572   CompareOpc = -1;
9573   isDot = false;
9574   switch (IntrinsicID) {
9575   default:
9576     return false;
9577   // Comparison predicates.
9578   case Intrinsic::ppc_altivec_vcmpbfp_p:
9579     CompareOpc = 966;
9580     isDot = true;
9581     break;
9582   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9583     CompareOpc = 198;
9584     isDot = true;
9585     break;
9586   case Intrinsic::ppc_altivec_vcmpequb_p:
9587     CompareOpc = 6;
9588     isDot = true;
9589     break;
9590   case Intrinsic::ppc_altivec_vcmpequh_p:
9591     CompareOpc = 70;
9592     isDot = true;
9593     break;
9594   case Intrinsic::ppc_altivec_vcmpequw_p:
9595     CompareOpc = 134;
9596     isDot = true;
9597     break;
9598   case Intrinsic::ppc_altivec_vcmpequd_p:
9599     if (Subtarget.hasP8Altivec()) {
9600       CompareOpc = 199;
9601       isDot = true;
9602     } else
9603       return false;
9604     break;
9605   case Intrinsic::ppc_altivec_vcmpneb_p:
9606   case Intrinsic::ppc_altivec_vcmpneh_p:
9607   case Intrinsic::ppc_altivec_vcmpnew_p:
9608   case Intrinsic::ppc_altivec_vcmpnezb_p:
9609   case Intrinsic::ppc_altivec_vcmpnezh_p:
9610   case Intrinsic::ppc_altivec_vcmpnezw_p:
9611     if (Subtarget.hasP9Altivec()) {
9612       switch (IntrinsicID) {
9613       default:
9614         llvm_unreachable("Unknown comparison intrinsic.");
9615       case Intrinsic::ppc_altivec_vcmpneb_p:
9616         CompareOpc = 7;
9617         break;
9618       case Intrinsic::ppc_altivec_vcmpneh_p:
9619         CompareOpc = 71;
9620         break;
9621       case Intrinsic::ppc_altivec_vcmpnew_p:
9622         CompareOpc = 135;
9623         break;
9624       case Intrinsic::ppc_altivec_vcmpnezb_p:
9625         CompareOpc = 263;
9626         break;
9627       case Intrinsic::ppc_altivec_vcmpnezh_p:
9628         CompareOpc = 327;
9629         break;
9630       case Intrinsic::ppc_altivec_vcmpnezw_p:
9631         CompareOpc = 391;
9632         break;
9633       }
9634       isDot = true;
9635     } else
9636       return false;
9637     break;
9638   case Intrinsic::ppc_altivec_vcmpgefp_p:
9639     CompareOpc = 454;
9640     isDot = true;
9641     break;
9642   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9643     CompareOpc = 710;
9644     isDot = true;
9645     break;
9646   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9647     CompareOpc = 774;
9648     isDot = true;
9649     break;
9650   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9651     CompareOpc = 838;
9652     isDot = true;
9653     break;
9654   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9655     CompareOpc = 902;
9656     isDot = true;
9657     break;
9658   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9659     if (Subtarget.hasP8Altivec()) {
9660       CompareOpc = 967;
9661       isDot = true;
9662     } else
9663       return false;
9664     break;
9665   case Intrinsic::ppc_altivec_vcmpgtub_p:
9666     CompareOpc = 518;
9667     isDot = true;
9668     break;
9669   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9670     CompareOpc = 582;
9671     isDot = true;
9672     break;
9673   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9674     CompareOpc = 646;
9675     isDot = true;
9676     break;
9677   case Intrinsic::ppc_altivec_vcmpgtud_p:
9678     if (Subtarget.hasP8Altivec()) {
9679       CompareOpc = 711;
9680       isDot = true;
9681     } else
9682       return false;
9683     break;
9684 
9685   case Intrinsic::ppc_altivec_vcmpequq:
9686   case Intrinsic::ppc_altivec_vcmpgtsq:
9687   case Intrinsic::ppc_altivec_vcmpgtuq:
9688     if (!Subtarget.isISA3_1())
9689       return false;
9690     switch (IntrinsicID) {
9691     default:
9692       llvm_unreachable("Unknown comparison intrinsic.");
9693     case Intrinsic::ppc_altivec_vcmpequq:
9694       CompareOpc = 455;
9695       break;
9696     case Intrinsic::ppc_altivec_vcmpgtsq:
9697       CompareOpc = 903;
9698       break;
9699     case Intrinsic::ppc_altivec_vcmpgtuq:
9700       CompareOpc = 647;
9701       break;
9702     }
9703     break;
9704 
9705   // VSX predicate comparisons use the same infrastructure
9706   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9707   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9708   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9709   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9710   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9711   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9712     if (Subtarget.hasVSX()) {
9713       switch (IntrinsicID) {
9714       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9715         CompareOpc = 99;
9716         break;
9717       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9718         CompareOpc = 115;
9719         break;
9720       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9721         CompareOpc = 107;
9722         break;
9723       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9724         CompareOpc = 67;
9725         break;
9726       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9727         CompareOpc = 83;
9728         break;
9729       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9730         CompareOpc = 75;
9731         break;
9732       }
9733       isDot = true;
9734     } else
9735       return false;
9736     break;
9737 
9738   // Normal Comparisons.
9739   case Intrinsic::ppc_altivec_vcmpbfp:
9740     CompareOpc = 966;
9741     break;
9742   case Intrinsic::ppc_altivec_vcmpeqfp:
9743     CompareOpc = 198;
9744     break;
9745   case Intrinsic::ppc_altivec_vcmpequb:
9746     CompareOpc = 6;
9747     break;
9748   case Intrinsic::ppc_altivec_vcmpequh:
9749     CompareOpc = 70;
9750     break;
9751   case Intrinsic::ppc_altivec_vcmpequw:
9752     CompareOpc = 134;
9753     break;
9754   case Intrinsic::ppc_altivec_vcmpequd:
9755     if (Subtarget.hasP8Altivec())
9756       CompareOpc = 199;
9757     else
9758       return false;
9759     break;
9760   case Intrinsic::ppc_altivec_vcmpneb:
9761   case Intrinsic::ppc_altivec_vcmpneh:
9762   case Intrinsic::ppc_altivec_vcmpnew:
9763   case Intrinsic::ppc_altivec_vcmpnezb:
9764   case Intrinsic::ppc_altivec_vcmpnezh:
9765   case Intrinsic::ppc_altivec_vcmpnezw:
9766     if (Subtarget.hasP9Altivec())
9767       switch (IntrinsicID) {
9768       default:
9769         llvm_unreachable("Unknown comparison intrinsic.");
9770       case Intrinsic::ppc_altivec_vcmpneb:
9771         CompareOpc = 7;
9772         break;
9773       case Intrinsic::ppc_altivec_vcmpneh:
9774         CompareOpc = 71;
9775         break;
9776       case Intrinsic::ppc_altivec_vcmpnew:
9777         CompareOpc = 135;
9778         break;
9779       case Intrinsic::ppc_altivec_vcmpnezb:
9780         CompareOpc = 263;
9781         break;
9782       case Intrinsic::ppc_altivec_vcmpnezh:
9783         CompareOpc = 327;
9784         break;
9785       case Intrinsic::ppc_altivec_vcmpnezw:
9786         CompareOpc = 391;
9787         break;
9788       }
9789     else
9790       return false;
9791     break;
9792   case Intrinsic::ppc_altivec_vcmpgefp:
9793     CompareOpc = 454;
9794     break;
9795   case Intrinsic::ppc_altivec_vcmpgtfp:
9796     CompareOpc = 710;
9797     break;
9798   case Intrinsic::ppc_altivec_vcmpgtsb:
9799     CompareOpc = 774;
9800     break;
9801   case Intrinsic::ppc_altivec_vcmpgtsh:
9802     CompareOpc = 838;
9803     break;
9804   case Intrinsic::ppc_altivec_vcmpgtsw:
9805     CompareOpc = 902;
9806     break;
9807   case Intrinsic::ppc_altivec_vcmpgtsd:
9808     if (Subtarget.hasP8Altivec())
9809       CompareOpc = 967;
9810     else
9811       return false;
9812     break;
9813   case Intrinsic::ppc_altivec_vcmpgtub:
9814     CompareOpc = 518;
9815     break;
9816   case Intrinsic::ppc_altivec_vcmpgtuh:
9817     CompareOpc = 582;
9818     break;
9819   case Intrinsic::ppc_altivec_vcmpgtuw:
9820     CompareOpc = 646;
9821     break;
9822   case Intrinsic::ppc_altivec_vcmpgtud:
9823     if (Subtarget.hasP8Altivec())
9824       CompareOpc = 711;
9825     else
9826       return false;
9827     break;
9828   case Intrinsic::ppc_altivec_vcmpequq_p:
9829   case Intrinsic::ppc_altivec_vcmpgtsq_p:
9830   case Intrinsic::ppc_altivec_vcmpgtuq_p:
9831     if (!Subtarget.isISA3_1())
9832       return false;
9833     switch (IntrinsicID) {
9834     default:
9835       llvm_unreachable("Unknown comparison intrinsic.");
9836     case Intrinsic::ppc_altivec_vcmpequq_p:
9837       CompareOpc = 455;
9838       break;
9839     case Intrinsic::ppc_altivec_vcmpgtsq_p:
9840       CompareOpc = 903;
9841       break;
9842     case Intrinsic::ppc_altivec_vcmpgtuq_p:
9843       CompareOpc = 647;
9844       break;
9845     }
9846     isDot = true;
9847     break;
9848   }
9849   return true;
9850 }
9851 
9852 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9853 /// lower, do it, otherwise return null.
9854 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9855                                                    SelectionDAG &DAG) const {
9856   unsigned IntrinsicID =
9857     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9858 
9859   SDLoc dl(Op);
9860 
9861   switch (IntrinsicID) {
9862   case Intrinsic::thread_pointer:
9863     // Reads the thread pointer register, used for __builtin_thread_pointer.
9864     if (Subtarget.isPPC64())
9865       return DAG.getRegister(PPC::X13, MVT::i64);
9866     return DAG.getRegister(PPC::R2, MVT::i32);
9867 
9868   case Intrinsic::ppc_mma_disassemble_acc:
9869   case Intrinsic::ppc_vsx_disassemble_pair: {
9870     int NumVecs = 2;
9871     SDValue WideVec = Op.getOperand(1);
9872     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
9873       NumVecs = 4;
9874       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
9875     }
9876     SmallVector<SDValue, 4> RetOps;
9877     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
9878       SDValue Extract = DAG.getNode(
9879           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
9880           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
9881                                                      : VecNo,
9882                           dl, MVT::i64));
9883       RetOps.push_back(Extract);
9884     }
9885     return DAG.getMergeValues(RetOps, dl);
9886   }
9887   }
9888 
9889   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9890   // opcode number of the comparison.
9891   int CompareOpc;
9892   bool isDot;
9893   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9894     return SDValue();    // Don't custom lower most intrinsics.
9895 
9896   // If this is a non-dot comparison, make the VCMP node and we are done.
9897   if (!isDot) {
9898     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9899                               Op.getOperand(1), Op.getOperand(2),
9900                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9901     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9902   }
9903 
9904   // Create the PPCISD altivec 'dot' comparison node.
9905   SDValue Ops[] = {
9906     Op.getOperand(2),  // LHS
9907     Op.getOperand(3),  // RHS
9908     DAG.getConstant(CompareOpc, dl, MVT::i32)
9909   };
9910   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9911   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
9912 
9913   // Now that we have the comparison, emit a copy from the CR to a GPR.
9914   // This is flagged to the above dot comparison.
9915   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9916                                 DAG.getRegister(PPC::CR6, MVT::i32),
9917                                 CompNode.getValue(1));
9918 
9919   // Unpack the result based on how the target uses it.
9920   unsigned BitNo;   // Bit # of CR6.
9921   bool InvertBit;   // Invert result?
9922   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9923   default:  // Can't happen, don't crash on invalid number though.
9924   case 0:   // Return the value of the EQ bit of CR6.
9925     BitNo = 0; InvertBit = false;
9926     break;
9927   case 1:   // Return the inverted value of the EQ bit of CR6.
9928     BitNo = 0; InvertBit = true;
9929     break;
9930   case 2:   // Return the value of the LT bit of CR6.
9931     BitNo = 2; InvertBit = false;
9932     break;
9933   case 3:   // Return the inverted value of the LT bit of CR6.
9934     BitNo = 2; InvertBit = true;
9935     break;
9936   }
9937 
9938   // Shift the bit into the low position.
9939   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9940                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9941   // Isolate the bit.
9942   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9943                       DAG.getConstant(1, dl, MVT::i32));
9944 
9945   // If we are supposed to, toggle the bit.
9946   if (InvertBit)
9947     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9948                         DAG.getConstant(1, dl, MVT::i32));
9949   return Flags;
9950 }
9951 
9952 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9953                                                SelectionDAG &DAG) const {
9954   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9955   // the beginning of the argument list.
9956   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9957   SDLoc DL(Op);
9958   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9959   case Intrinsic::ppc_cfence: {
9960     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9961     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9962     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9963                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9964                                                   Op.getOperand(ArgStart + 1)),
9965                                       Op.getOperand(0)),
9966                    0);
9967   }
9968   default:
9969     break;
9970   }
9971   return SDValue();
9972 }
9973 
9974 // Lower scalar BSWAP64 to xxbrd.
9975 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9976   SDLoc dl(Op);
9977   // MTVSRDD
9978   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9979                    Op.getOperand(0));
9980   // XXBRD
9981   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
9982   // MFVSRD
9983   int VectorIndex = 0;
9984   if (Subtarget.isLittleEndian())
9985     VectorIndex = 1;
9986   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9987                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9988   return Op;
9989 }
9990 
9991 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9992 // compared to a value that is atomically loaded (atomic loads zero-extend).
9993 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9994                                                 SelectionDAG &DAG) const {
9995   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9996          "Expecting an atomic compare-and-swap here.");
9997   SDLoc dl(Op);
9998   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9999   EVT MemVT = AtomicNode->getMemoryVT();
10000   if (MemVT.getSizeInBits() >= 32)
10001     return Op;
10002 
10003   SDValue CmpOp = Op.getOperand(2);
10004   // If this is already correctly zero-extended, leave it alone.
10005   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10006   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10007     return Op;
10008 
10009   // Clear the high bits of the compare operand.
10010   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10011   SDValue NewCmpOp =
10012     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10013                 DAG.getConstant(MaskVal, dl, MVT::i32));
10014 
10015   // Replace the existing compare operand with the properly zero-extended one.
10016   SmallVector<SDValue, 4> Ops;
10017   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10018     Ops.push_back(AtomicNode->getOperand(i));
10019   Ops[2] = NewCmpOp;
10020   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10021   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10022   auto NodeTy =
10023     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10024   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10025 }
10026 
10027 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10028                                                  SelectionDAG &DAG) const {
10029   SDLoc dl(Op);
10030   // Create a stack slot that is 16-byte aligned.
10031   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10032   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10033   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10034   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10035 
10036   // Store the input value into Value#0 of the stack slot.
10037   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10038                                MachinePointerInfo());
10039   // Load it out.
10040   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10041 }
10042 
10043 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10044                                                   SelectionDAG &DAG) const {
10045   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10046          "Should only be called for ISD::INSERT_VECTOR_ELT");
10047 
10048   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10049 
10050   EVT VT = Op.getValueType();
10051   SDLoc dl(Op);
10052   SDValue V1 = Op.getOperand(0);
10053   SDValue V2 = Op.getOperand(1);
10054   SDValue V3 = Op.getOperand(2);
10055 
10056   if (Subtarget.isISA3_1()) {
10057     // On P10, we have legal lowering for constant and variable indices for
10058     // integer vectors.
10059     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10060         VT == MVT::v2i64)
10061       return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10062     // For f32 and f64 vectors, we have legal lowering for variable indices.
10063     // For f32 we also have legal lowering when the element is loaded from
10064     // memory.
10065     if (VT == MVT::v4f32 || VT == MVT::v2f64) {
10066       if (!C || (VT == MVT::v4f32 && dyn_cast<LoadSDNode>(V2)))
10067         return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, V2, V3);
10068       return SDValue();
10069     }
10070   }
10071 
10072   // Before P10, we have legal lowering for constant indices but not for
10073   // variable ones.
10074   if (!C)
10075     return SDValue();
10076 
10077   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10078   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10079     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10080     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10081     unsigned InsertAtElement = C->getZExtValue();
10082     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10083     if (Subtarget.isLittleEndian()) {
10084       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10085     }
10086     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10087                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10088   }
10089   return Op;
10090 }
10091 
10092 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10093                                            SelectionDAG &DAG) const {
10094   SDLoc dl(Op);
10095   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10096   SDValue LoadChain = LN->getChain();
10097   SDValue BasePtr = LN->getBasePtr();
10098   EVT VT = Op.getValueType();
10099 
10100   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10101     return Op;
10102 
10103   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10104   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10105   // 2 or 4 vsx registers.
10106   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10107          "Type unsupported without MMA");
10108   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10109          "Type unsupported without paired vector support");
10110   Align Alignment = LN->getAlign();
10111   SmallVector<SDValue, 4> Loads;
10112   SmallVector<SDValue, 4> LoadChains;
10113   unsigned NumVecs = VT.getSizeInBits() / 128;
10114   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10115     SDValue Load =
10116         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10117                     LN->getPointerInfo().getWithOffset(Idx * 16),
10118                     commonAlignment(Alignment, Idx * 16),
10119                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10120     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10121                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10122     Loads.push_back(Load);
10123     LoadChains.push_back(Load.getValue(1));
10124   }
10125   if (Subtarget.isLittleEndian()) {
10126     std::reverse(Loads.begin(), Loads.end());
10127     std::reverse(LoadChains.begin(), LoadChains.end());
10128   }
10129   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10130   SDValue Value =
10131       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10132                   dl, VT, Loads);
10133   SDValue RetOps[] = {Value, TF};
10134   return DAG.getMergeValues(RetOps, dl);
10135 }
10136 
10137 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10138                                             SelectionDAG &DAG) const {
10139   SDLoc dl(Op);
10140   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10141   SDValue StoreChain = SN->getChain();
10142   SDValue BasePtr = SN->getBasePtr();
10143   SDValue Value = SN->getValue();
10144   EVT StoreVT = Value.getValueType();
10145 
10146   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10147     return Op;
10148 
10149   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10150   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10151   // underlying registers individually.
10152   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10153          "Type unsupported without MMA");
10154   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10155          "Type unsupported without paired vector support");
10156   Align Alignment = SN->getAlign();
10157   SmallVector<SDValue, 4> Stores;
10158   unsigned NumVecs = 2;
10159   if (StoreVT == MVT::v512i1) {
10160     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10161     NumVecs = 4;
10162   }
10163   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10164     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10165     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10166                               DAG.getConstant(VecNum, dl, MVT::i64));
10167     SDValue Store =
10168         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10169                      SN->getPointerInfo().getWithOffset(Idx * 16),
10170                      commonAlignment(Alignment, Idx * 16),
10171                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10172     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10173                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10174     Stores.push_back(Store);
10175   }
10176   SDValue TF = DAG.getTokenFactor(dl, Stores);
10177   return TF;
10178 }
10179 
10180 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10181   SDLoc dl(Op);
10182   if (Op.getValueType() == MVT::v4i32) {
10183     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10184 
10185     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10186     // +16 as shift amt.
10187     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10188     SDValue RHSSwap =   // = vrlw RHS, 16
10189       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10190 
10191     // Shrinkify inputs to v8i16.
10192     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10193     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10194     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10195 
10196     // Low parts multiplied together, generating 32-bit results (we ignore the
10197     // top parts).
10198     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10199                                         LHS, RHS, DAG, dl, MVT::v4i32);
10200 
10201     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10202                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10203     // Shift the high parts up 16 bits.
10204     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10205                               Neg16, DAG, dl);
10206     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10207   } else if (Op.getValueType() == MVT::v16i8) {
10208     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10209     bool isLittleEndian = Subtarget.isLittleEndian();
10210 
10211     // Multiply the even 8-bit parts, producing 16-bit sums.
10212     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10213                                            LHS, RHS, DAG, dl, MVT::v8i16);
10214     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10215 
10216     // Multiply the odd 8-bit parts, producing 16-bit sums.
10217     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10218                                           LHS, RHS, DAG, dl, MVT::v8i16);
10219     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10220 
10221     // Merge the results together.  Because vmuleub and vmuloub are
10222     // instructions with a big-endian bias, we must reverse the
10223     // element numbering and reverse the meaning of "odd" and "even"
10224     // when generating little endian code.
10225     int Ops[16];
10226     for (unsigned i = 0; i != 8; ++i) {
10227       if (isLittleEndian) {
10228         Ops[i*2  ] = 2*i;
10229         Ops[i*2+1] = 2*i+16;
10230       } else {
10231         Ops[i*2  ] = 2*i+1;
10232         Ops[i*2+1] = 2*i+1+16;
10233       }
10234     }
10235     if (isLittleEndian)
10236       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10237     else
10238       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10239   } else {
10240     llvm_unreachable("Unknown mul to lower!");
10241   }
10242 }
10243 
10244 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10245   bool IsStrict = Op->isStrictFPOpcode();
10246   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
10247       !Subtarget.hasP9Vector())
10248     return SDValue();
10249 
10250   return Op;
10251 }
10252 
10253 // Custom lowering for fpext vf32 to v2f64
10254 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10255 
10256   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10257          "Should only be called for ISD::FP_EXTEND");
10258 
10259   // FIXME: handle extends from half precision float vectors on P9.
10260   // We only want to custom lower an extend from v2f32 to v2f64.
10261   if (Op.getValueType() != MVT::v2f64 ||
10262       Op.getOperand(0).getValueType() != MVT::v2f32)
10263     return SDValue();
10264 
10265   SDLoc dl(Op);
10266   SDValue Op0 = Op.getOperand(0);
10267 
10268   switch (Op0.getOpcode()) {
10269   default:
10270     return SDValue();
10271   case ISD::EXTRACT_SUBVECTOR: {
10272     assert(Op0.getNumOperands() == 2 &&
10273            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10274            "Node should have 2 operands with second one being a constant!");
10275 
10276     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10277       return SDValue();
10278 
10279     // Custom lower is only done for high or low doubleword.
10280     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10281     if (Idx % 2 != 0)
10282       return SDValue();
10283 
10284     // Since input is v4f32, at this point Idx is either 0 or 2.
10285     // Shift to get the doubleword position we want.
10286     int DWord = Idx >> 1;
10287 
10288     // High and low word positions are different on little endian.
10289     if (Subtarget.isLittleEndian())
10290       DWord ^= 0x1;
10291 
10292     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10293                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10294   }
10295   case ISD::FADD:
10296   case ISD::FMUL:
10297   case ISD::FSUB: {
10298     SDValue NewLoad[2];
10299     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10300       // Ensure both input are loads.
10301       SDValue LdOp = Op0.getOperand(i);
10302       if (LdOp.getOpcode() != ISD::LOAD)
10303         return SDValue();
10304       // Generate new load node.
10305       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10306       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10307       NewLoad[i] = DAG.getMemIntrinsicNode(
10308           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10309           LD->getMemoryVT(), LD->getMemOperand());
10310     }
10311     SDValue NewOp =
10312         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10313                     NewLoad[1], Op0.getNode()->getFlags());
10314     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10315                        DAG.getConstant(0, dl, MVT::i32));
10316   }
10317   case ISD::LOAD: {
10318     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10319     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10320     SDValue NewLd = DAG.getMemIntrinsicNode(
10321         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10322         LD->getMemoryVT(), LD->getMemOperand());
10323     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10324                        DAG.getConstant(0, dl, MVT::i32));
10325   }
10326   }
10327   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10328 }
10329 
10330 /// LowerOperation - Provide custom lowering hooks for some operations.
10331 ///
10332 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10333   switch (Op.getOpcode()) {
10334   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10335   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10336   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10337   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10338   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10339   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10340   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10341   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10342   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10343 
10344   // Variable argument lowering.
10345   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10346   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10347   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10348 
10349   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10350   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10351   case ISD::GET_DYNAMIC_AREA_OFFSET:
10352     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10353 
10354   // Exception handling lowering.
10355   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10356   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10357   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10358 
10359   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10360   case ISD::STORE:              return LowerSTORE(Op, DAG);
10361   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10362   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10363   case ISD::STRICT_FP_TO_UINT:
10364   case ISD::STRICT_FP_TO_SINT:
10365   case ISD::FP_TO_UINT:
10366   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10367   case ISD::STRICT_UINT_TO_FP:
10368   case ISD::STRICT_SINT_TO_FP:
10369   case ISD::UINT_TO_FP:
10370   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10371   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10372 
10373   // Lower 64-bit shifts.
10374   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10375   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10376   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10377 
10378   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10379   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10380 
10381   // Vector-related lowering.
10382   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10383   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10384   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10385   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10386   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10387   case ISD::MUL:                return LowerMUL(Op, DAG);
10388   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10389   case ISD::STRICT_FP_ROUND:
10390   case ISD::FP_ROUND:
10391     return LowerFP_ROUND(Op, DAG);
10392   case ISD::ROTL:               return LowerROTL(Op, DAG);
10393 
10394   // For counter-based loop handling.
10395   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10396 
10397   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10398 
10399   // Frame & Return address.
10400   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10401   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10402 
10403   case ISD::INTRINSIC_VOID:
10404     return LowerINTRINSIC_VOID(Op, DAG);
10405   case ISD::BSWAP:
10406     return LowerBSWAP(Op, DAG);
10407   case ISD::ATOMIC_CMP_SWAP:
10408     return LowerATOMIC_CMP_SWAP(Op, DAG);
10409   }
10410 }
10411 
10412 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10413                                            SmallVectorImpl<SDValue>&Results,
10414                                            SelectionDAG &DAG) const {
10415   SDLoc dl(N);
10416   switch (N->getOpcode()) {
10417   default:
10418     llvm_unreachable("Do not know how to custom type legalize this operation!");
10419   case ISD::READCYCLECOUNTER: {
10420     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10421     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10422 
10423     Results.push_back(
10424         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10425     Results.push_back(RTB.getValue(2));
10426     break;
10427   }
10428   case ISD::INTRINSIC_W_CHAIN: {
10429     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10430         Intrinsic::loop_decrement)
10431       break;
10432 
10433     assert(N->getValueType(0) == MVT::i1 &&
10434            "Unexpected result type for CTR decrement intrinsic");
10435     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10436                                  N->getValueType(0));
10437     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10438     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10439                                  N->getOperand(1));
10440 
10441     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10442     Results.push_back(NewInt.getValue(1));
10443     break;
10444   }
10445   case ISD::VAARG: {
10446     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10447       return;
10448 
10449     EVT VT = N->getValueType(0);
10450 
10451     if (VT == MVT::i64) {
10452       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10453 
10454       Results.push_back(NewNode);
10455       Results.push_back(NewNode.getValue(1));
10456     }
10457     return;
10458   }
10459   case ISD::STRICT_FP_TO_SINT:
10460   case ISD::STRICT_FP_TO_UINT:
10461   case ISD::FP_TO_SINT:
10462   case ISD::FP_TO_UINT:
10463     // LowerFP_TO_INT() can only handle f32 and f64.
10464     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10465         MVT::ppcf128)
10466       return;
10467     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10468     return;
10469   case ISD::TRUNCATE: {
10470     if (!N->getValueType(0).isVector())
10471       return;
10472     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
10473     if (Lowered)
10474       Results.push_back(Lowered);
10475     return;
10476   }
10477   case ISD::FSHL:
10478   case ISD::FSHR:
10479     // Don't handle funnel shifts here.
10480     return;
10481   case ISD::BITCAST:
10482     // Don't handle bitcast here.
10483     return;
10484   case ISD::FP_EXTEND:
10485     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10486     if (Lowered)
10487       Results.push_back(Lowered);
10488     return;
10489   }
10490 }
10491 
10492 //===----------------------------------------------------------------------===//
10493 //  Other Lowering Code
10494 //===----------------------------------------------------------------------===//
10495 
10496 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10497   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10498   Function *Func = Intrinsic::getDeclaration(M, Id);
10499   return Builder.CreateCall(Func, {});
10500 }
10501 
10502 // The mappings for emitLeading/TrailingFence is taken from
10503 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10504 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10505                                                  Instruction *Inst,
10506                                                  AtomicOrdering Ord) const {
10507   if (Ord == AtomicOrdering::SequentiallyConsistent)
10508     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10509   if (isReleaseOrStronger(Ord))
10510     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10511   return nullptr;
10512 }
10513 
10514 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10515                                                   Instruction *Inst,
10516                                                   AtomicOrdering Ord) const {
10517   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10518     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10519     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10520     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10521     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10522       return Builder.CreateCall(
10523           Intrinsic::getDeclaration(
10524               Builder.GetInsertBlock()->getParent()->getParent(),
10525               Intrinsic::ppc_cfence, {Inst->getType()}),
10526           {Inst});
10527     // FIXME: Can use isync for rmw operation.
10528     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10529   }
10530   return nullptr;
10531 }
10532 
10533 MachineBasicBlock *
10534 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10535                                     unsigned AtomicSize,
10536                                     unsigned BinOpcode,
10537                                     unsigned CmpOpcode,
10538                                     unsigned CmpPred) const {
10539   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10540   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10541 
10542   auto LoadMnemonic = PPC::LDARX;
10543   auto StoreMnemonic = PPC::STDCX;
10544   switch (AtomicSize) {
10545   default:
10546     llvm_unreachable("Unexpected size of atomic entity");
10547   case 1:
10548     LoadMnemonic = PPC::LBARX;
10549     StoreMnemonic = PPC::STBCX;
10550     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10551     break;
10552   case 2:
10553     LoadMnemonic = PPC::LHARX;
10554     StoreMnemonic = PPC::STHCX;
10555     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10556     break;
10557   case 4:
10558     LoadMnemonic = PPC::LWARX;
10559     StoreMnemonic = PPC::STWCX;
10560     break;
10561   case 8:
10562     LoadMnemonic = PPC::LDARX;
10563     StoreMnemonic = PPC::STDCX;
10564     break;
10565   }
10566 
10567   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10568   MachineFunction *F = BB->getParent();
10569   MachineFunction::iterator It = ++BB->getIterator();
10570 
10571   Register dest = MI.getOperand(0).getReg();
10572   Register ptrA = MI.getOperand(1).getReg();
10573   Register ptrB = MI.getOperand(2).getReg();
10574   Register incr = MI.getOperand(3).getReg();
10575   DebugLoc dl = MI.getDebugLoc();
10576 
10577   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10578   MachineBasicBlock *loop2MBB =
10579     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10580   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10581   F->insert(It, loopMBB);
10582   if (CmpOpcode)
10583     F->insert(It, loop2MBB);
10584   F->insert(It, exitMBB);
10585   exitMBB->splice(exitMBB->begin(), BB,
10586                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10587   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10588 
10589   MachineRegisterInfo &RegInfo = F->getRegInfo();
10590   Register TmpReg = (!BinOpcode) ? incr :
10591     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10592                                            : &PPC::GPRCRegClass);
10593 
10594   //  thisMBB:
10595   //   ...
10596   //   fallthrough --> loopMBB
10597   BB->addSuccessor(loopMBB);
10598 
10599   //  loopMBB:
10600   //   l[wd]arx dest, ptr
10601   //   add r0, dest, incr
10602   //   st[wd]cx. r0, ptr
10603   //   bne- loopMBB
10604   //   fallthrough --> exitMBB
10605 
10606   // For max/min...
10607   //  loopMBB:
10608   //   l[wd]arx dest, ptr
10609   //   cmpl?[wd] incr, dest
10610   //   bgt exitMBB
10611   //  loop2MBB:
10612   //   st[wd]cx. dest, ptr
10613   //   bne- loopMBB
10614   //   fallthrough --> exitMBB
10615 
10616   BB = loopMBB;
10617   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10618     .addReg(ptrA).addReg(ptrB);
10619   if (BinOpcode)
10620     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10621   if (CmpOpcode) {
10622     // Signed comparisons of byte or halfword values must be sign-extended.
10623     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10624       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10625       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10626               ExtReg).addReg(dest);
10627       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10628         .addReg(incr).addReg(ExtReg);
10629     } else
10630       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10631         .addReg(incr).addReg(dest);
10632 
10633     BuildMI(BB, dl, TII->get(PPC::BCC))
10634       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10635     BB->addSuccessor(loop2MBB);
10636     BB->addSuccessor(exitMBB);
10637     BB = loop2MBB;
10638   }
10639   BuildMI(BB, dl, TII->get(StoreMnemonic))
10640     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10641   BuildMI(BB, dl, TII->get(PPC::BCC))
10642     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10643   BB->addSuccessor(loopMBB);
10644   BB->addSuccessor(exitMBB);
10645 
10646   //  exitMBB:
10647   //   ...
10648   BB = exitMBB;
10649   return BB;
10650 }
10651 
10652 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
10653   switch(MI.getOpcode()) {
10654   default:
10655     return false;
10656   case PPC::COPY:
10657     return TII->isSignExtended(MI);
10658   case PPC::LHA:
10659   case PPC::LHA8:
10660   case PPC::LHAU:
10661   case PPC::LHAU8:
10662   case PPC::LHAUX:
10663   case PPC::LHAUX8:
10664   case PPC::LHAX:
10665   case PPC::LHAX8:
10666   case PPC::LWA:
10667   case PPC::LWAUX:
10668   case PPC::LWAX:
10669   case PPC::LWAX_32:
10670   case PPC::LWA_32:
10671   case PPC::PLHA:
10672   case PPC::PLHA8:
10673   case PPC::PLHA8pc:
10674   case PPC::PLHApc:
10675   case PPC::PLWA:
10676   case PPC::PLWA8:
10677   case PPC::PLWA8pc:
10678   case PPC::PLWApc:
10679   case PPC::EXTSB:
10680   case PPC::EXTSB8:
10681   case PPC::EXTSB8_32_64:
10682   case PPC::EXTSB8_rec:
10683   case PPC::EXTSB_rec:
10684   case PPC::EXTSH:
10685   case PPC::EXTSH8:
10686   case PPC::EXTSH8_32_64:
10687   case PPC::EXTSH8_rec:
10688   case PPC::EXTSH_rec:
10689   case PPC::EXTSW:
10690   case PPC::EXTSWSLI:
10691   case PPC::EXTSWSLI_32_64:
10692   case PPC::EXTSWSLI_32_64_rec:
10693   case PPC::EXTSWSLI_rec:
10694   case PPC::EXTSW_32:
10695   case PPC::EXTSW_32_64:
10696   case PPC::EXTSW_32_64_rec:
10697   case PPC::EXTSW_rec:
10698   case PPC::SRAW:
10699   case PPC::SRAWI:
10700   case PPC::SRAWI_rec:
10701   case PPC::SRAW_rec:
10702     return true;
10703   }
10704   return false;
10705 }
10706 
10707 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10708     MachineInstr &MI, MachineBasicBlock *BB,
10709     bool is8bit, // operation
10710     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10711   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10712   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10713 
10714   // If this is a signed comparison and the value being compared is not known
10715   // to be sign extended, sign extend it here.
10716   DebugLoc dl = MI.getDebugLoc();
10717   MachineFunction *F = BB->getParent();
10718   MachineRegisterInfo &RegInfo = F->getRegInfo();
10719   Register incr = MI.getOperand(3).getReg();
10720   bool IsSignExtended = Register::isVirtualRegister(incr) &&
10721     isSignExtended(*RegInfo.getVRegDef(incr), TII);
10722 
10723   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
10724     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10725     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
10726         .addReg(MI.getOperand(3).getReg());
10727     MI.getOperand(3).setReg(ValueReg);
10728   }
10729   // If we support part-word atomic mnemonics, just use them
10730   if (Subtarget.hasPartwordAtomics())
10731     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10732                             CmpPred);
10733 
10734   // In 64 bit mode we have to use 64 bits for addresses, even though the
10735   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10736   // registers without caring whether they're 32 or 64, but here we're
10737   // doing actual arithmetic on the addresses.
10738   bool is64bit = Subtarget.isPPC64();
10739   bool isLittleEndian = Subtarget.isLittleEndian();
10740   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10741 
10742   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10743   MachineFunction::iterator It = ++BB->getIterator();
10744 
10745   Register dest = MI.getOperand(0).getReg();
10746   Register ptrA = MI.getOperand(1).getReg();
10747   Register ptrB = MI.getOperand(2).getReg();
10748 
10749   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10750   MachineBasicBlock *loop2MBB =
10751       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10752   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10753   F->insert(It, loopMBB);
10754   if (CmpOpcode)
10755     F->insert(It, loop2MBB);
10756   F->insert(It, exitMBB);
10757   exitMBB->splice(exitMBB->begin(), BB,
10758                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10759   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10760 
10761   const TargetRegisterClass *RC =
10762       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10763   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10764 
10765   Register PtrReg = RegInfo.createVirtualRegister(RC);
10766   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10767   Register ShiftReg =
10768       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10769   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10770   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10771   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10772   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10773   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10774   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10775   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10776   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10777   Register Ptr1Reg;
10778   Register TmpReg =
10779       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10780 
10781   //  thisMBB:
10782   //   ...
10783   //   fallthrough --> loopMBB
10784   BB->addSuccessor(loopMBB);
10785 
10786   // The 4-byte load must be aligned, while a char or short may be
10787   // anywhere in the word.  Hence all this nasty bookkeeping code.
10788   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10789   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10790   //   xori shift, shift1, 24 [16]
10791   //   rlwinm ptr, ptr1, 0, 0, 29
10792   //   slw incr2, incr, shift
10793   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10794   //   slw mask, mask2, shift
10795   //  loopMBB:
10796   //   lwarx tmpDest, ptr
10797   //   add tmp, tmpDest, incr2
10798   //   andc tmp2, tmpDest, mask
10799   //   and tmp3, tmp, mask
10800   //   or tmp4, tmp3, tmp2
10801   //   stwcx. tmp4, ptr
10802   //   bne- loopMBB
10803   //   fallthrough --> exitMBB
10804   //   srw dest, tmpDest, shift
10805   if (ptrA != ZeroReg) {
10806     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10807     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10808         .addReg(ptrA)
10809         .addReg(ptrB);
10810   } else {
10811     Ptr1Reg = ptrB;
10812   }
10813   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10814   // mode.
10815   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10816       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10817       .addImm(3)
10818       .addImm(27)
10819       .addImm(is8bit ? 28 : 27);
10820   if (!isLittleEndian)
10821     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10822         .addReg(Shift1Reg)
10823         .addImm(is8bit ? 24 : 16);
10824   if (is64bit)
10825     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10826         .addReg(Ptr1Reg)
10827         .addImm(0)
10828         .addImm(61);
10829   else
10830     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10831         .addReg(Ptr1Reg)
10832         .addImm(0)
10833         .addImm(0)
10834         .addImm(29);
10835   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10836   if (is8bit)
10837     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10838   else {
10839     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10840     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10841         .addReg(Mask3Reg)
10842         .addImm(65535);
10843   }
10844   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10845       .addReg(Mask2Reg)
10846       .addReg(ShiftReg);
10847 
10848   BB = loopMBB;
10849   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10850       .addReg(ZeroReg)
10851       .addReg(PtrReg);
10852   if (BinOpcode)
10853     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10854         .addReg(Incr2Reg)
10855         .addReg(TmpDestReg);
10856   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10857       .addReg(TmpDestReg)
10858       .addReg(MaskReg);
10859   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10860   if (CmpOpcode) {
10861     // For unsigned comparisons, we can directly compare the shifted values.
10862     // For signed comparisons we shift and sign extend.
10863     Register SReg = RegInfo.createVirtualRegister(GPRC);
10864     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10865         .addReg(TmpDestReg)
10866         .addReg(MaskReg);
10867     unsigned ValueReg = SReg;
10868     unsigned CmpReg = Incr2Reg;
10869     if (CmpOpcode == PPC::CMPW) {
10870       ValueReg = RegInfo.createVirtualRegister(GPRC);
10871       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10872           .addReg(SReg)
10873           .addReg(ShiftReg);
10874       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10875       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10876           .addReg(ValueReg);
10877       ValueReg = ValueSReg;
10878       CmpReg = incr;
10879     }
10880     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10881         .addReg(CmpReg)
10882         .addReg(ValueReg);
10883     BuildMI(BB, dl, TII->get(PPC::BCC))
10884         .addImm(CmpPred)
10885         .addReg(PPC::CR0)
10886         .addMBB(exitMBB);
10887     BB->addSuccessor(loop2MBB);
10888     BB->addSuccessor(exitMBB);
10889     BB = loop2MBB;
10890   }
10891   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10892   BuildMI(BB, dl, TII->get(PPC::STWCX))
10893       .addReg(Tmp4Reg)
10894       .addReg(ZeroReg)
10895       .addReg(PtrReg);
10896   BuildMI(BB, dl, TII->get(PPC::BCC))
10897       .addImm(PPC::PRED_NE)
10898       .addReg(PPC::CR0)
10899       .addMBB(loopMBB);
10900   BB->addSuccessor(loopMBB);
10901   BB->addSuccessor(exitMBB);
10902 
10903   //  exitMBB:
10904   //   ...
10905   BB = exitMBB;
10906   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10907       .addReg(TmpDestReg)
10908       .addReg(ShiftReg);
10909   return BB;
10910 }
10911 
10912 llvm::MachineBasicBlock *
10913 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10914                                     MachineBasicBlock *MBB) const {
10915   DebugLoc DL = MI.getDebugLoc();
10916   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10917   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10918 
10919   MachineFunction *MF = MBB->getParent();
10920   MachineRegisterInfo &MRI = MF->getRegInfo();
10921 
10922   const BasicBlock *BB = MBB->getBasicBlock();
10923   MachineFunction::iterator I = ++MBB->getIterator();
10924 
10925   Register DstReg = MI.getOperand(0).getReg();
10926   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10927   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10928   Register mainDstReg = MRI.createVirtualRegister(RC);
10929   Register restoreDstReg = MRI.createVirtualRegister(RC);
10930 
10931   MVT PVT = getPointerTy(MF->getDataLayout());
10932   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10933          "Invalid Pointer Size!");
10934   // For v = setjmp(buf), we generate
10935   //
10936   // thisMBB:
10937   //  SjLjSetup mainMBB
10938   //  bl mainMBB
10939   //  v_restore = 1
10940   //  b sinkMBB
10941   //
10942   // mainMBB:
10943   //  buf[LabelOffset] = LR
10944   //  v_main = 0
10945   //
10946   // sinkMBB:
10947   //  v = phi(main, restore)
10948   //
10949 
10950   MachineBasicBlock *thisMBB = MBB;
10951   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10952   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10953   MF->insert(I, mainMBB);
10954   MF->insert(I, sinkMBB);
10955 
10956   MachineInstrBuilder MIB;
10957 
10958   // Transfer the remainder of BB and its successor edges to sinkMBB.
10959   sinkMBB->splice(sinkMBB->begin(), MBB,
10960                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10961   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10962 
10963   // Note that the structure of the jmp_buf used here is not compatible
10964   // with that used by libc, and is not designed to be. Specifically, it
10965   // stores only those 'reserved' registers that LLVM does not otherwise
10966   // understand how to spill. Also, by convention, by the time this
10967   // intrinsic is called, Clang has already stored the frame address in the
10968   // first slot of the buffer and stack address in the third. Following the
10969   // X86 target code, we'll store the jump address in the second slot. We also
10970   // need to save the TOC pointer (R2) to handle jumps between shared
10971   // libraries, and that will be stored in the fourth slot. The thread
10972   // identifier (R13) is not affected.
10973 
10974   // thisMBB:
10975   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10976   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10977   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10978 
10979   // Prepare IP either in reg.
10980   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10981   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10982   Register BufReg = MI.getOperand(1).getReg();
10983 
10984   if (Subtarget.is64BitELFABI()) {
10985     setUsesTOCBasePtr(*MBB->getParent());
10986     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10987               .addReg(PPC::X2)
10988               .addImm(TOCOffset)
10989               .addReg(BufReg)
10990               .cloneMemRefs(MI);
10991   }
10992 
10993   // Naked functions never have a base pointer, and so we use r1. For all
10994   // other functions, this decision must be delayed until during PEI.
10995   unsigned BaseReg;
10996   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10997     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10998   else
10999     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11000 
11001   MIB = BuildMI(*thisMBB, MI, DL,
11002                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11003             .addReg(BaseReg)
11004             .addImm(BPOffset)
11005             .addReg(BufReg)
11006             .cloneMemRefs(MI);
11007 
11008   // Setup
11009   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11010   MIB.addRegMask(TRI->getNoPreservedMask());
11011 
11012   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11013 
11014   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11015           .addMBB(mainMBB);
11016   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11017 
11018   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11019   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11020 
11021   // mainMBB:
11022   //  mainDstReg = 0
11023   MIB =
11024       BuildMI(mainMBB, DL,
11025               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11026 
11027   // Store IP
11028   if (Subtarget.isPPC64()) {
11029     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11030             .addReg(LabelReg)
11031             .addImm(LabelOffset)
11032             .addReg(BufReg);
11033   } else {
11034     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11035             .addReg(LabelReg)
11036             .addImm(LabelOffset)
11037             .addReg(BufReg);
11038   }
11039   MIB.cloneMemRefs(MI);
11040 
11041   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11042   mainMBB->addSuccessor(sinkMBB);
11043 
11044   // sinkMBB:
11045   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11046           TII->get(PPC::PHI), DstReg)
11047     .addReg(mainDstReg).addMBB(mainMBB)
11048     .addReg(restoreDstReg).addMBB(thisMBB);
11049 
11050   MI.eraseFromParent();
11051   return sinkMBB;
11052 }
11053 
11054 MachineBasicBlock *
11055 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11056                                      MachineBasicBlock *MBB) const {
11057   DebugLoc DL = MI.getDebugLoc();
11058   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11059 
11060   MachineFunction *MF = MBB->getParent();
11061   MachineRegisterInfo &MRI = MF->getRegInfo();
11062 
11063   MVT PVT = getPointerTy(MF->getDataLayout());
11064   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11065          "Invalid Pointer Size!");
11066 
11067   const TargetRegisterClass *RC =
11068     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11069   Register Tmp = MRI.createVirtualRegister(RC);
11070   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11071   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11072   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11073   unsigned BP =
11074       (PVT == MVT::i64)
11075           ? PPC::X30
11076           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11077                                                               : PPC::R30);
11078 
11079   MachineInstrBuilder MIB;
11080 
11081   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11082   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11083   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11084   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11085 
11086   Register BufReg = MI.getOperand(0).getReg();
11087 
11088   // Reload FP (the jumped-to function may not have had a
11089   // frame pointer, and if so, then its r31 will be restored
11090   // as necessary).
11091   if (PVT == MVT::i64) {
11092     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11093             .addImm(0)
11094             .addReg(BufReg);
11095   } else {
11096     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11097             .addImm(0)
11098             .addReg(BufReg);
11099   }
11100   MIB.cloneMemRefs(MI);
11101 
11102   // Reload IP
11103   if (PVT == MVT::i64) {
11104     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11105             .addImm(LabelOffset)
11106             .addReg(BufReg);
11107   } else {
11108     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11109             .addImm(LabelOffset)
11110             .addReg(BufReg);
11111   }
11112   MIB.cloneMemRefs(MI);
11113 
11114   // Reload SP
11115   if (PVT == MVT::i64) {
11116     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11117             .addImm(SPOffset)
11118             .addReg(BufReg);
11119   } else {
11120     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11121             .addImm(SPOffset)
11122             .addReg(BufReg);
11123   }
11124   MIB.cloneMemRefs(MI);
11125 
11126   // Reload BP
11127   if (PVT == MVT::i64) {
11128     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11129             .addImm(BPOffset)
11130             .addReg(BufReg);
11131   } else {
11132     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11133             .addImm(BPOffset)
11134             .addReg(BufReg);
11135   }
11136   MIB.cloneMemRefs(MI);
11137 
11138   // Reload TOC
11139   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11140     setUsesTOCBasePtr(*MBB->getParent());
11141     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11142               .addImm(TOCOffset)
11143               .addReg(BufReg)
11144               .cloneMemRefs(MI);
11145   }
11146 
11147   // Jump
11148   BuildMI(*MBB, MI, DL,
11149           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11150   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11151 
11152   MI.eraseFromParent();
11153   return MBB;
11154 }
11155 
11156 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11157   // If the function specifically requests inline stack probes, emit them.
11158   if (MF.getFunction().hasFnAttribute("probe-stack"))
11159     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11160            "inline-asm";
11161   return false;
11162 }
11163 
11164 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11165   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11166   unsigned StackAlign = TFI->getStackAlignment();
11167   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11168          "Unexpected stack alignment");
11169   // The default stack probe size is 4096 if the function has no
11170   // stack-probe-size attribute.
11171   unsigned StackProbeSize = 4096;
11172   const Function &Fn = MF.getFunction();
11173   if (Fn.hasFnAttribute("stack-probe-size"))
11174     Fn.getFnAttribute("stack-probe-size")
11175         .getValueAsString()
11176         .getAsInteger(0, StackProbeSize);
11177   // Round down to the stack alignment.
11178   StackProbeSize &= ~(StackAlign - 1);
11179   return StackProbeSize ? StackProbeSize : StackAlign;
11180 }
11181 
11182 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11183 // into three phases. In the first phase, it uses pseudo instruction
11184 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11185 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11186 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11187 // MaxCallFrameSize so that it can calculate correct data area pointer.
11188 MachineBasicBlock *
11189 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11190                                     MachineBasicBlock *MBB) const {
11191   const bool isPPC64 = Subtarget.isPPC64();
11192   MachineFunction *MF = MBB->getParent();
11193   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11194   DebugLoc DL = MI.getDebugLoc();
11195   const unsigned ProbeSize = getStackProbeSize(*MF);
11196   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11197   MachineRegisterInfo &MRI = MF->getRegInfo();
11198   // The CFG of probing stack looks as
11199   //         +-----+
11200   //         | MBB |
11201   //         +--+--+
11202   //            |
11203   //       +----v----+
11204   //  +--->+ TestMBB +---+
11205   //  |    +----+----+   |
11206   //  |         |        |
11207   //  |   +-----v----+   |
11208   //  +---+ BlockMBB |   |
11209   //      +----------+   |
11210   //                     |
11211   //       +---------+   |
11212   //       | TailMBB +<--+
11213   //       +---------+
11214   // In MBB, calculate previous frame pointer and final stack pointer.
11215   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11216   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11217   // TailMBB is spliced via \p MI.
11218   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11219   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11220   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11221 
11222   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11223   MF->insert(MBBIter, TestMBB);
11224   MF->insert(MBBIter, BlockMBB);
11225   MF->insert(MBBIter, TailMBB);
11226 
11227   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11228   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11229 
11230   Register DstReg = MI.getOperand(0).getReg();
11231   Register NegSizeReg = MI.getOperand(1).getReg();
11232   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11233   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11234   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11235   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11236 
11237   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11238   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11239   // NegSize.
11240   unsigned ProbeOpc;
11241   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11242     ProbeOpc =
11243         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11244   else
11245     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11246     // and NegSizeReg will be allocated in the same phyreg to avoid
11247     // redundant copy when NegSizeReg has only one use which is current MI and
11248     // will be replaced by PREPARE_PROBED_ALLOCA then.
11249     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11250                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11251   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11252       .addDef(ActualNegSizeReg)
11253       .addReg(NegSizeReg)
11254       .add(MI.getOperand(2))
11255       .add(MI.getOperand(3));
11256 
11257   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11258   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11259           FinalStackPtr)
11260       .addReg(SPReg)
11261       .addReg(ActualNegSizeReg);
11262 
11263   // Materialize a scratch register for update.
11264   int64_t NegProbeSize = -(int64_t)ProbeSize;
11265   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11266   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11267   if (!isInt<16>(NegProbeSize)) {
11268     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11269     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11270         .addImm(NegProbeSize >> 16);
11271     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11272             ScratchReg)
11273         .addReg(TempReg)
11274         .addImm(NegProbeSize & 0xFFFF);
11275   } else
11276     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11277         .addImm(NegProbeSize);
11278 
11279   {
11280     // Probing leading residual part.
11281     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11282     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11283         .addReg(ActualNegSizeReg)
11284         .addReg(ScratchReg);
11285     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11286     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11287         .addReg(Div)
11288         .addReg(ScratchReg);
11289     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11290     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11291         .addReg(Mul)
11292         .addReg(ActualNegSizeReg);
11293     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11294         .addReg(FramePointer)
11295         .addReg(SPReg)
11296         .addReg(NegMod);
11297   }
11298 
11299   {
11300     // Remaining part should be multiple of ProbeSize.
11301     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11302     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11303         .addReg(SPReg)
11304         .addReg(FinalStackPtr);
11305     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11306         .addImm(PPC::PRED_EQ)
11307         .addReg(CmpResult)
11308         .addMBB(TailMBB);
11309     TestMBB->addSuccessor(BlockMBB);
11310     TestMBB->addSuccessor(TailMBB);
11311   }
11312 
11313   {
11314     // Touch the block.
11315     // |P...|P...|P...
11316     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11317         .addReg(FramePointer)
11318         .addReg(SPReg)
11319         .addReg(ScratchReg);
11320     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11321     BlockMBB->addSuccessor(TestMBB);
11322   }
11323 
11324   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11325   // DYNAREAOFFSET pseudo instruction to get the future result.
11326   Register MaxCallFrameSizeReg =
11327       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11328   BuildMI(TailMBB, DL,
11329           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11330           MaxCallFrameSizeReg)
11331       .add(MI.getOperand(2))
11332       .add(MI.getOperand(3));
11333   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11334       .addReg(SPReg)
11335       .addReg(MaxCallFrameSizeReg);
11336 
11337   // Splice instructions after MI to TailMBB.
11338   TailMBB->splice(TailMBB->end(), MBB,
11339                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11340   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11341   MBB->addSuccessor(TestMBB);
11342 
11343   // Delete the pseudo instruction.
11344   MI.eraseFromParent();
11345 
11346   ++NumDynamicAllocaProbed;
11347   return TailMBB;
11348 }
11349 
11350 MachineBasicBlock *
11351 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11352                                                MachineBasicBlock *BB) const {
11353   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11354       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11355     if (Subtarget.is64BitELFABI() &&
11356         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11357         !Subtarget.isUsingPCRelativeCalls()) {
11358       // Call lowering should have added an r2 operand to indicate a dependence
11359       // on the TOC base pointer value. It can't however, because there is no
11360       // way to mark the dependence as implicit there, and so the stackmap code
11361       // will confuse it with a regular operand. Instead, add the dependence
11362       // here.
11363       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11364     }
11365 
11366     return emitPatchPoint(MI, BB);
11367   }
11368 
11369   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11370       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11371     return emitEHSjLjSetJmp(MI, BB);
11372   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11373              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11374     return emitEHSjLjLongJmp(MI, BB);
11375   }
11376 
11377   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11378 
11379   // To "insert" these instructions we actually have to insert their
11380   // control-flow patterns.
11381   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11382   MachineFunction::iterator It = ++BB->getIterator();
11383 
11384   MachineFunction *F = BB->getParent();
11385 
11386   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11387       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11388       MI.getOpcode() == PPC::SELECT_I8) {
11389     SmallVector<MachineOperand, 2> Cond;
11390     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11391         MI.getOpcode() == PPC::SELECT_CC_I8)
11392       Cond.push_back(MI.getOperand(4));
11393     else
11394       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11395     Cond.push_back(MI.getOperand(1));
11396 
11397     DebugLoc dl = MI.getDebugLoc();
11398     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11399                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11400   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11401              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11402              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11403              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11404              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11405              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11406              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11407              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11408              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11409              MI.getOpcode() == PPC::SELECT_F4 ||
11410              MI.getOpcode() == PPC::SELECT_F8 ||
11411              MI.getOpcode() == PPC::SELECT_F16 ||
11412              MI.getOpcode() == PPC::SELECT_SPE ||
11413              MI.getOpcode() == PPC::SELECT_SPE4 ||
11414              MI.getOpcode() == PPC::SELECT_VRRC ||
11415              MI.getOpcode() == PPC::SELECT_VSFRC ||
11416              MI.getOpcode() == PPC::SELECT_VSSRC ||
11417              MI.getOpcode() == PPC::SELECT_VSRC) {
11418     // The incoming instruction knows the destination vreg to set, the
11419     // condition code register to branch on, the true/false values to
11420     // select between, and a branch opcode to use.
11421 
11422     //  thisMBB:
11423     //  ...
11424     //   TrueVal = ...
11425     //   cmpTY ccX, r1, r2
11426     //   bCC copy1MBB
11427     //   fallthrough --> copy0MBB
11428     MachineBasicBlock *thisMBB = BB;
11429     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11430     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11431     DebugLoc dl = MI.getDebugLoc();
11432     F->insert(It, copy0MBB);
11433     F->insert(It, sinkMBB);
11434 
11435     // Transfer the remainder of BB and its successor edges to sinkMBB.
11436     sinkMBB->splice(sinkMBB->begin(), BB,
11437                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11438     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11439 
11440     // Next, add the true and fallthrough blocks as its successors.
11441     BB->addSuccessor(copy0MBB);
11442     BB->addSuccessor(sinkMBB);
11443 
11444     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11445         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11446         MI.getOpcode() == PPC::SELECT_F16 ||
11447         MI.getOpcode() == PPC::SELECT_SPE4 ||
11448         MI.getOpcode() == PPC::SELECT_SPE ||
11449         MI.getOpcode() == PPC::SELECT_VRRC ||
11450         MI.getOpcode() == PPC::SELECT_VSFRC ||
11451         MI.getOpcode() == PPC::SELECT_VSSRC ||
11452         MI.getOpcode() == PPC::SELECT_VSRC) {
11453       BuildMI(BB, dl, TII->get(PPC::BC))
11454           .addReg(MI.getOperand(1).getReg())
11455           .addMBB(sinkMBB);
11456     } else {
11457       unsigned SelectPred = MI.getOperand(4).getImm();
11458       BuildMI(BB, dl, TII->get(PPC::BCC))
11459           .addImm(SelectPred)
11460           .addReg(MI.getOperand(1).getReg())
11461           .addMBB(sinkMBB);
11462     }
11463 
11464     //  copy0MBB:
11465     //   %FalseValue = ...
11466     //   # fallthrough to sinkMBB
11467     BB = copy0MBB;
11468 
11469     // Update machine-CFG edges
11470     BB->addSuccessor(sinkMBB);
11471 
11472     //  sinkMBB:
11473     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11474     //  ...
11475     BB = sinkMBB;
11476     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11477         .addReg(MI.getOperand(3).getReg())
11478         .addMBB(copy0MBB)
11479         .addReg(MI.getOperand(2).getReg())
11480         .addMBB(thisMBB);
11481   } else if (MI.getOpcode() == PPC::ReadTB) {
11482     // To read the 64-bit time-base register on a 32-bit target, we read the
11483     // two halves. Should the counter have wrapped while it was being read, we
11484     // need to try again.
11485     // ...
11486     // readLoop:
11487     // mfspr Rx,TBU # load from TBU
11488     // mfspr Ry,TB  # load from TB
11489     // mfspr Rz,TBU # load from TBU
11490     // cmpw crX,Rx,Rz # check if 'old'='new'
11491     // bne readLoop   # branch if they're not equal
11492     // ...
11493 
11494     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11495     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11496     DebugLoc dl = MI.getDebugLoc();
11497     F->insert(It, readMBB);
11498     F->insert(It, sinkMBB);
11499 
11500     // Transfer the remainder of BB and its successor edges to sinkMBB.
11501     sinkMBB->splice(sinkMBB->begin(), BB,
11502                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11503     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11504 
11505     BB->addSuccessor(readMBB);
11506     BB = readMBB;
11507 
11508     MachineRegisterInfo &RegInfo = F->getRegInfo();
11509     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11510     Register LoReg = MI.getOperand(0).getReg();
11511     Register HiReg = MI.getOperand(1).getReg();
11512 
11513     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11514     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11515     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11516 
11517     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11518 
11519     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11520         .addReg(HiReg)
11521         .addReg(ReadAgainReg);
11522     BuildMI(BB, dl, TII->get(PPC::BCC))
11523         .addImm(PPC::PRED_NE)
11524         .addReg(CmpReg)
11525         .addMBB(readMBB);
11526 
11527     BB->addSuccessor(readMBB);
11528     BB->addSuccessor(sinkMBB);
11529   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11530     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11531   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11532     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11533   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11534     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11535   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11536     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11537 
11538   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11539     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11540   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11541     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11542   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11543     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11544   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11545     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11546 
11547   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11548     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11549   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11550     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11551   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11552     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11553   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11554     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11555 
11556   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11557     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11558   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11559     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11560   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11561     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11562   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11563     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11564 
11565   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11566     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11567   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11568     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11569   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11570     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11571   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11572     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11573 
11574   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11575     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11576   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11577     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11578   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11579     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11580   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11581     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11582 
11583   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11584     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11585   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11586     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11587   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11588     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11589   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11590     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11591 
11592   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11593     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11594   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11595     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11596   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11597     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11598   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11599     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11600 
11601   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11602     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11603   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11604     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11605   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11606     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11607   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11608     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11609 
11610   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11611     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11612   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11613     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11614   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11615     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11616   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11617     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11618 
11619   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11620     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11621   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11622     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11623   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11624     BB = EmitAtomicBinary(MI, BB, 4, 0);
11625   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11626     BB = EmitAtomicBinary(MI, BB, 8, 0);
11627   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11628            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11629            (Subtarget.hasPartwordAtomics() &&
11630             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11631            (Subtarget.hasPartwordAtomics() &&
11632             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11633     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11634 
11635     auto LoadMnemonic = PPC::LDARX;
11636     auto StoreMnemonic = PPC::STDCX;
11637     switch (MI.getOpcode()) {
11638     default:
11639       llvm_unreachable("Compare and swap of unknown size");
11640     case PPC::ATOMIC_CMP_SWAP_I8:
11641       LoadMnemonic = PPC::LBARX;
11642       StoreMnemonic = PPC::STBCX;
11643       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11644       break;
11645     case PPC::ATOMIC_CMP_SWAP_I16:
11646       LoadMnemonic = PPC::LHARX;
11647       StoreMnemonic = PPC::STHCX;
11648       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11649       break;
11650     case PPC::ATOMIC_CMP_SWAP_I32:
11651       LoadMnemonic = PPC::LWARX;
11652       StoreMnemonic = PPC::STWCX;
11653       break;
11654     case PPC::ATOMIC_CMP_SWAP_I64:
11655       LoadMnemonic = PPC::LDARX;
11656       StoreMnemonic = PPC::STDCX;
11657       break;
11658     }
11659     Register dest = MI.getOperand(0).getReg();
11660     Register ptrA = MI.getOperand(1).getReg();
11661     Register ptrB = MI.getOperand(2).getReg();
11662     Register oldval = MI.getOperand(3).getReg();
11663     Register newval = MI.getOperand(4).getReg();
11664     DebugLoc dl = MI.getDebugLoc();
11665 
11666     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11667     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11668     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11669     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11670     F->insert(It, loop1MBB);
11671     F->insert(It, loop2MBB);
11672     F->insert(It, midMBB);
11673     F->insert(It, exitMBB);
11674     exitMBB->splice(exitMBB->begin(), BB,
11675                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11676     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11677 
11678     //  thisMBB:
11679     //   ...
11680     //   fallthrough --> loopMBB
11681     BB->addSuccessor(loop1MBB);
11682 
11683     // loop1MBB:
11684     //   l[bhwd]arx dest, ptr
11685     //   cmp[wd] dest, oldval
11686     //   bne- midMBB
11687     // loop2MBB:
11688     //   st[bhwd]cx. newval, ptr
11689     //   bne- loopMBB
11690     //   b exitBB
11691     // midMBB:
11692     //   st[bhwd]cx. dest, ptr
11693     // exitBB:
11694     BB = loop1MBB;
11695     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11696     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11697         .addReg(oldval)
11698         .addReg(dest);
11699     BuildMI(BB, dl, TII->get(PPC::BCC))
11700         .addImm(PPC::PRED_NE)
11701         .addReg(PPC::CR0)
11702         .addMBB(midMBB);
11703     BB->addSuccessor(loop2MBB);
11704     BB->addSuccessor(midMBB);
11705 
11706     BB = loop2MBB;
11707     BuildMI(BB, dl, TII->get(StoreMnemonic))
11708         .addReg(newval)
11709         .addReg(ptrA)
11710         .addReg(ptrB);
11711     BuildMI(BB, dl, TII->get(PPC::BCC))
11712         .addImm(PPC::PRED_NE)
11713         .addReg(PPC::CR0)
11714         .addMBB(loop1MBB);
11715     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11716     BB->addSuccessor(loop1MBB);
11717     BB->addSuccessor(exitMBB);
11718 
11719     BB = midMBB;
11720     BuildMI(BB, dl, TII->get(StoreMnemonic))
11721         .addReg(dest)
11722         .addReg(ptrA)
11723         .addReg(ptrB);
11724     BB->addSuccessor(exitMBB);
11725 
11726     //  exitMBB:
11727     //   ...
11728     BB = exitMBB;
11729   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11730              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11731     // We must use 64-bit registers for addresses when targeting 64-bit,
11732     // since we're actually doing arithmetic on them.  Other registers
11733     // can be 32-bit.
11734     bool is64bit = Subtarget.isPPC64();
11735     bool isLittleEndian = Subtarget.isLittleEndian();
11736     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11737 
11738     Register dest = MI.getOperand(0).getReg();
11739     Register ptrA = MI.getOperand(1).getReg();
11740     Register ptrB = MI.getOperand(2).getReg();
11741     Register oldval = MI.getOperand(3).getReg();
11742     Register newval = MI.getOperand(4).getReg();
11743     DebugLoc dl = MI.getDebugLoc();
11744 
11745     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11746     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11747     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11748     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11749     F->insert(It, loop1MBB);
11750     F->insert(It, loop2MBB);
11751     F->insert(It, midMBB);
11752     F->insert(It, exitMBB);
11753     exitMBB->splice(exitMBB->begin(), BB,
11754                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11755     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11756 
11757     MachineRegisterInfo &RegInfo = F->getRegInfo();
11758     const TargetRegisterClass *RC =
11759         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11760     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11761 
11762     Register PtrReg = RegInfo.createVirtualRegister(RC);
11763     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11764     Register ShiftReg =
11765         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11766     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11767     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11768     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11769     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11770     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11771     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11772     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11773     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11774     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11775     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11776     Register Ptr1Reg;
11777     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11778     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11779     //  thisMBB:
11780     //   ...
11781     //   fallthrough --> loopMBB
11782     BB->addSuccessor(loop1MBB);
11783 
11784     // The 4-byte load must be aligned, while a char or short may be
11785     // anywhere in the word.  Hence all this nasty bookkeeping code.
11786     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11787     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11788     //   xori shift, shift1, 24 [16]
11789     //   rlwinm ptr, ptr1, 0, 0, 29
11790     //   slw newval2, newval, shift
11791     //   slw oldval2, oldval,shift
11792     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11793     //   slw mask, mask2, shift
11794     //   and newval3, newval2, mask
11795     //   and oldval3, oldval2, mask
11796     // loop1MBB:
11797     //   lwarx tmpDest, ptr
11798     //   and tmp, tmpDest, mask
11799     //   cmpw tmp, oldval3
11800     //   bne- midMBB
11801     // loop2MBB:
11802     //   andc tmp2, tmpDest, mask
11803     //   or tmp4, tmp2, newval3
11804     //   stwcx. tmp4, ptr
11805     //   bne- loop1MBB
11806     //   b exitBB
11807     // midMBB:
11808     //   stwcx. tmpDest, ptr
11809     // exitBB:
11810     //   srw dest, tmpDest, shift
11811     if (ptrA != ZeroReg) {
11812       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11813       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11814           .addReg(ptrA)
11815           .addReg(ptrB);
11816     } else {
11817       Ptr1Reg = ptrB;
11818     }
11819 
11820     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11821     // mode.
11822     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11823         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11824         .addImm(3)
11825         .addImm(27)
11826         .addImm(is8bit ? 28 : 27);
11827     if (!isLittleEndian)
11828       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11829           .addReg(Shift1Reg)
11830           .addImm(is8bit ? 24 : 16);
11831     if (is64bit)
11832       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11833           .addReg(Ptr1Reg)
11834           .addImm(0)
11835           .addImm(61);
11836     else
11837       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11838           .addReg(Ptr1Reg)
11839           .addImm(0)
11840           .addImm(0)
11841           .addImm(29);
11842     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11843         .addReg(newval)
11844         .addReg(ShiftReg);
11845     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11846         .addReg(oldval)
11847         .addReg(ShiftReg);
11848     if (is8bit)
11849       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11850     else {
11851       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11852       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11853           .addReg(Mask3Reg)
11854           .addImm(65535);
11855     }
11856     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11857         .addReg(Mask2Reg)
11858         .addReg(ShiftReg);
11859     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11860         .addReg(NewVal2Reg)
11861         .addReg(MaskReg);
11862     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11863         .addReg(OldVal2Reg)
11864         .addReg(MaskReg);
11865 
11866     BB = loop1MBB;
11867     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11868         .addReg(ZeroReg)
11869         .addReg(PtrReg);
11870     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11871         .addReg(TmpDestReg)
11872         .addReg(MaskReg);
11873     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11874         .addReg(TmpReg)
11875         .addReg(OldVal3Reg);
11876     BuildMI(BB, dl, TII->get(PPC::BCC))
11877         .addImm(PPC::PRED_NE)
11878         .addReg(PPC::CR0)
11879         .addMBB(midMBB);
11880     BB->addSuccessor(loop2MBB);
11881     BB->addSuccessor(midMBB);
11882 
11883     BB = loop2MBB;
11884     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11885         .addReg(TmpDestReg)
11886         .addReg(MaskReg);
11887     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11888         .addReg(Tmp2Reg)
11889         .addReg(NewVal3Reg);
11890     BuildMI(BB, dl, TII->get(PPC::STWCX))
11891         .addReg(Tmp4Reg)
11892         .addReg(ZeroReg)
11893         .addReg(PtrReg);
11894     BuildMI(BB, dl, TII->get(PPC::BCC))
11895         .addImm(PPC::PRED_NE)
11896         .addReg(PPC::CR0)
11897         .addMBB(loop1MBB);
11898     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11899     BB->addSuccessor(loop1MBB);
11900     BB->addSuccessor(exitMBB);
11901 
11902     BB = midMBB;
11903     BuildMI(BB, dl, TII->get(PPC::STWCX))
11904         .addReg(TmpDestReg)
11905         .addReg(ZeroReg)
11906         .addReg(PtrReg);
11907     BB->addSuccessor(exitMBB);
11908 
11909     //  exitMBB:
11910     //   ...
11911     BB = exitMBB;
11912     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11913         .addReg(TmpReg)
11914         .addReg(ShiftReg);
11915   } else if (MI.getOpcode() == PPC::FADDrtz) {
11916     // This pseudo performs an FADD with rounding mode temporarily forced
11917     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11918     // is not modeled at the SelectionDAG level.
11919     Register Dest = MI.getOperand(0).getReg();
11920     Register Src1 = MI.getOperand(1).getReg();
11921     Register Src2 = MI.getOperand(2).getReg();
11922     DebugLoc dl = MI.getDebugLoc();
11923 
11924     MachineRegisterInfo &RegInfo = F->getRegInfo();
11925     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11926 
11927     // Save FPSCR value.
11928     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11929 
11930     // Set rounding mode to round-to-zero.
11931     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
11932         .addImm(31)
11933         .addReg(PPC::RM, RegState::ImplicitDefine);
11934 
11935     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
11936         .addImm(30)
11937         .addReg(PPC::RM, RegState::ImplicitDefine);
11938 
11939     // Perform addition.
11940     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
11941                    .addReg(Src1)
11942                    .addReg(Src2);
11943     if (MI.getFlag(MachineInstr::NoFPExcept))
11944       MIB.setMIFlag(MachineInstr::NoFPExcept);
11945 
11946     // Restore FPSCR value.
11947     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11948   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11949              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11950              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11951              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11952     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11953                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11954                           ? PPC::ANDI8_rec
11955                           : PPC::ANDI_rec;
11956     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11957                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11958 
11959     MachineRegisterInfo &RegInfo = F->getRegInfo();
11960     Register Dest = RegInfo.createVirtualRegister(
11961         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11962 
11963     DebugLoc Dl = MI.getDebugLoc();
11964     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11965         .addReg(MI.getOperand(1).getReg())
11966         .addImm(1);
11967     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11968             MI.getOperand(0).getReg())
11969         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11970   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11971     DebugLoc Dl = MI.getDebugLoc();
11972     MachineRegisterInfo &RegInfo = F->getRegInfo();
11973     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11974     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11975     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11976             MI.getOperand(0).getReg())
11977         .addReg(CRReg);
11978   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11979     DebugLoc Dl = MI.getDebugLoc();
11980     unsigned Imm = MI.getOperand(1).getImm();
11981     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11982     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11983             MI.getOperand(0).getReg())
11984         .addReg(PPC::CR0EQ);
11985   } else if (MI.getOpcode() == PPC::SETRNDi) {
11986     DebugLoc dl = MI.getDebugLoc();
11987     Register OldFPSCRReg = MI.getOperand(0).getReg();
11988 
11989     // Save FPSCR value.
11990     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11991 
11992     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11993     // the following settings:
11994     //   00 Round to nearest
11995     //   01 Round to 0
11996     //   10 Round to +inf
11997     //   11 Round to -inf
11998 
11999     // When the operand is immediate, using the two least significant bits of
12000     // the immediate to set the bits 62:63 of FPSCR.
12001     unsigned Mode = MI.getOperand(1).getImm();
12002     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12003         .addImm(31)
12004         .addReg(PPC::RM, RegState::ImplicitDefine);
12005 
12006     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12007         .addImm(30)
12008         .addReg(PPC::RM, RegState::ImplicitDefine);
12009   } else if (MI.getOpcode() == PPC::SETRND) {
12010     DebugLoc dl = MI.getDebugLoc();
12011 
12012     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12013     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12014     // If the target doesn't have DirectMove, we should use stack to do the
12015     // conversion, because the target doesn't have the instructions like mtvsrd
12016     // or mfvsrd to do this conversion directly.
12017     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12018       if (Subtarget.hasDirectMove()) {
12019         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12020           .addReg(SrcReg);
12021       } else {
12022         // Use stack to do the register copy.
12023         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12024         MachineRegisterInfo &RegInfo = F->getRegInfo();
12025         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12026         if (RC == &PPC::F8RCRegClass) {
12027           // Copy register from F8RCRegClass to G8RCRegclass.
12028           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12029                  "Unsupported RegClass.");
12030 
12031           StoreOp = PPC::STFD;
12032           LoadOp = PPC::LD;
12033         } else {
12034           // Copy register from G8RCRegClass to F8RCRegclass.
12035           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12036                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12037                  "Unsupported RegClass.");
12038         }
12039 
12040         MachineFrameInfo &MFI = F->getFrameInfo();
12041         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12042 
12043         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12044             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12045             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12046             MFI.getObjectAlign(FrameIdx));
12047 
12048         // Store the SrcReg into the stack.
12049         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12050           .addReg(SrcReg)
12051           .addImm(0)
12052           .addFrameIndex(FrameIdx)
12053           .addMemOperand(MMOStore);
12054 
12055         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12056             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12057             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12058             MFI.getObjectAlign(FrameIdx));
12059 
12060         // Load from the stack where SrcReg is stored, and save to DestReg,
12061         // so we have done the RegClass conversion from RegClass::SrcReg to
12062         // RegClass::DestReg.
12063         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12064           .addImm(0)
12065           .addFrameIndex(FrameIdx)
12066           .addMemOperand(MMOLoad);
12067       }
12068     };
12069 
12070     Register OldFPSCRReg = MI.getOperand(0).getReg();
12071 
12072     // Save FPSCR value.
12073     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12074 
12075     // When the operand is gprc register, use two least significant bits of the
12076     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12077     //
12078     // copy OldFPSCRTmpReg, OldFPSCRReg
12079     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12080     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12081     // copy NewFPSCRReg, NewFPSCRTmpReg
12082     // mtfsf 255, NewFPSCRReg
12083     MachineOperand SrcOp = MI.getOperand(1);
12084     MachineRegisterInfo &RegInfo = F->getRegInfo();
12085     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12086 
12087     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12088 
12089     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12090     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12091 
12092     // The first operand of INSERT_SUBREG should be a register which has
12093     // subregisters, we only care about its RegClass, so we should use an
12094     // IMPLICIT_DEF register.
12095     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12096     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12097       .addReg(ImDefReg)
12098       .add(SrcOp)
12099       .addImm(1);
12100 
12101     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12102     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12103       .addReg(OldFPSCRTmpReg)
12104       .addReg(ExtSrcReg)
12105       .addImm(0)
12106       .addImm(62);
12107 
12108     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12109     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12110 
12111     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12112     // bits of FPSCR.
12113     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12114       .addImm(255)
12115       .addReg(NewFPSCRReg)
12116       .addImm(0)
12117       .addImm(0);
12118   } else if (MI.getOpcode() == PPC::SETFLM) {
12119     DebugLoc Dl = MI.getDebugLoc();
12120 
12121     // Result of setflm is previous FPSCR content, so we need to save it first.
12122     Register OldFPSCRReg = MI.getOperand(0).getReg();
12123     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12124 
12125     // Put bits in 32:63 to FPSCR.
12126     Register NewFPSCRReg = MI.getOperand(1).getReg();
12127     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12128         .addImm(255)
12129         .addReg(NewFPSCRReg)
12130         .addImm(0)
12131         .addImm(0);
12132   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12133              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12134     return emitProbedAlloca(MI, BB);
12135   } else {
12136     llvm_unreachable("Unexpected instr type to insert");
12137   }
12138 
12139   MI.eraseFromParent(); // The pseudo instruction is gone now.
12140   return BB;
12141 }
12142 
12143 //===----------------------------------------------------------------------===//
12144 // Target Optimization Hooks
12145 //===----------------------------------------------------------------------===//
12146 
12147 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12148   // For the estimates, convergence is quadratic, so we essentially double the
12149   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12150   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12151   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12152   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12153   if (VT.getScalarType() == MVT::f64)
12154     RefinementSteps++;
12155   return RefinementSteps;
12156 }
12157 
12158 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12159                                             const DenormalMode &Mode) const {
12160   // We only have VSX Vector Test for software Square Root.
12161   EVT VT = Op.getValueType();
12162   if (!isTypeLegal(MVT::i1) ||
12163       (VT != MVT::f64 &&
12164        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12165     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12166 
12167   SDLoc DL(Op);
12168   // The output register of FTSQRT is CR field.
12169   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
12170   // ftsqrt BF,FRB
12171   // Let e_b be the unbiased exponent of the double-precision
12172   // floating-point operand in register FRB.
12173   // fe_flag is set to 1 if either of the following conditions occurs.
12174   //   - The double-precision floating-point operand in register FRB is a zero,
12175   //     a NaN, or an infinity, or a negative value.
12176   //   - e_b is less than or equal to -970.
12177   // Otherwise fe_flag is set to 0.
12178   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
12179   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
12180   // exponent is less than -970)
12181   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
12182   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
12183                                     FTSQRT, SRIdxVal),
12184                  0);
12185 }
12186 
12187 SDValue
12188 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
12189                                                SelectionDAG &DAG) const {
12190   // We only have VSX Vector Square Root.
12191   EVT VT = Op.getValueType();
12192   if (VT != MVT::f64 &&
12193       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
12194     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
12195 
12196   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
12197 }
12198 
12199 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12200                                            int Enabled, int &RefinementSteps,
12201                                            bool &UseOneConstNR,
12202                                            bool Reciprocal) const {
12203   EVT VT = Operand.getValueType();
12204   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12205       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12206       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12207       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12208     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12209       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12210 
12211     // The Newton-Raphson computation with a single constant does not provide
12212     // enough accuracy on some CPUs.
12213     UseOneConstNR = !Subtarget.needsTwoConstNR();
12214     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12215   }
12216   return SDValue();
12217 }
12218 
12219 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12220                                             int Enabled,
12221                                             int &RefinementSteps) const {
12222   EVT VT = Operand.getValueType();
12223   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12224       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12225       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12226       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12227     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12228       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12229     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12230   }
12231   return SDValue();
12232 }
12233 
12234 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12235   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12236   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12237   // enabled for division), this functionality is redundant with the default
12238   // combiner logic (once the division -> reciprocal/multiply transformation
12239   // has taken place). As a result, this matters more for older cores than for
12240   // newer ones.
12241 
12242   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12243   // reciprocal if there are two or more FDIVs (for embedded cores with only
12244   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12245   switch (Subtarget.getCPUDirective()) {
12246   default:
12247     return 3;
12248   case PPC::DIR_440:
12249   case PPC::DIR_A2:
12250   case PPC::DIR_E500:
12251   case PPC::DIR_E500mc:
12252   case PPC::DIR_E5500:
12253     return 2;
12254   }
12255 }
12256 
12257 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12258 // collapsed, and so we need to look through chains of them.
12259 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12260                                      int64_t& Offset, SelectionDAG &DAG) {
12261   if (DAG.isBaseWithConstantOffset(Loc)) {
12262     Base = Loc.getOperand(0);
12263     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12264 
12265     // The base might itself be a base plus an offset, and if so, accumulate
12266     // that as well.
12267     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12268   }
12269 }
12270 
12271 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12272                             unsigned Bytes, int Dist,
12273                             SelectionDAG &DAG) {
12274   if (VT.getSizeInBits() / 8 != Bytes)
12275     return false;
12276 
12277   SDValue BaseLoc = Base->getBasePtr();
12278   if (Loc.getOpcode() == ISD::FrameIndex) {
12279     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12280       return false;
12281     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12282     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12283     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12284     int FS  = MFI.getObjectSize(FI);
12285     int BFS = MFI.getObjectSize(BFI);
12286     if (FS != BFS || FS != (int)Bytes) return false;
12287     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12288   }
12289 
12290   SDValue Base1 = Loc, Base2 = BaseLoc;
12291   int64_t Offset1 = 0, Offset2 = 0;
12292   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12293   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12294   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12295     return true;
12296 
12297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12298   const GlobalValue *GV1 = nullptr;
12299   const GlobalValue *GV2 = nullptr;
12300   Offset1 = 0;
12301   Offset2 = 0;
12302   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12303   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12304   if (isGA1 && isGA2 && GV1 == GV2)
12305     return Offset1 == (Offset2 + Dist*Bytes);
12306   return false;
12307 }
12308 
12309 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12310 // not enforce equality of the chain operands.
12311 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12312                             unsigned Bytes, int Dist,
12313                             SelectionDAG &DAG) {
12314   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12315     EVT VT = LS->getMemoryVT();
12316     SDValue Loc = LS->getBasePtr();
12317     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12318   }
12319 
12320   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12321     EVT VT;
12322     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12323     default: return false;
12324     case Intrinsic::ppc_altivec_lvx:
12325     case Intrinsic::ppc_altivec_lvxl:
12326     case Intrinsic::ppc_vsx_lxvw4x:
12327     case Intrinsic::ppc_vsx_lxvw4x_be:
12328       VT = MVT::v4i32;
12329       break;
12330     case Intrinsic::ppc_vsx_lxvd2x:
12331     case Intrinsic::ppc_vsx_lxvd2x_be:
12332       VT = MVT::v2f64;
12333       break;
12334     case Intrinsic::ppc_altivec_lvebx:
12335       VT = MVT::i8;
12336       break;
12337     case Intrinsic::ppc_altivec_lvehx:
12338       VT = MVT::i16;
12339       break;
12340     case Intrinsic::ppc_altivec_lvewx:
12341       VT = MVT::i32;
12342       break;
12343     }
12344 
12345     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12346   }
12347 
12348   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12349     EVT VT;
12350     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12351     default: return false;
12352     case Intrinsic::ppc_altivec_stvx:
12353     case Intrinsic::ppc_altivec_stvxl:
12354     case Intrinsic::ppc_vsx_stxvw4x:
12355       VT = MVT::v4i32;
12356       break;
12357     case Intrinsic::ppc_vsx_stxvd2x:
12358       VT = MVT::v2f64;
12359       break;
12360     case Intrinsic::ppc_vsx_stxvw4x_be:
12361       VT = MVT::v4i32;
12362       break;
12363     case Intrinsic::ppc_vsx_stxvd2x_be:
12364       VT = MVT::v2f64;
12365       break;
12366     case Intrinsic::ppc_altivec_stvebx:
12367       VT = MVT::i8;
12368       break;
12369     case Intrinsic::ppc_altivec_stvehx:
12370       VT = MVT::i16;
12371       break;
12372     case Intrinsic::ppc_altivec_stvewx:
12373       VT = MVT::i32;
12374       break;
12375     }
12376 
12377     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12378   }
12379 
12380   return false;
12381 }
12382 
12383 // Return true is there is a nearyby consecutive load to the one provided
12384 // (regardless of alignment). We search up and down the chain, looking though
12385 // token factors and other loads (but nothing else). As a result, a true result
12386 // indicates that it is safe to create a new consecutive load adjacent to the
12387 // load provided.
12388 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12389   SDValue Chain = LD->getChain();
12390   EVT VT = LD->getMemoryVT();
12391 
12392   SmallSet<SDNode *, 16> LoadRoots;
12393   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12394   SmallSet<SDNode *, 16> Visited;
12395 
12396   // First, search up the chain, branching to follow all token-factor operands.
12397   // If we find a consecutive load, then we're done, otherwise, record all
12398   // nodes just above the top-level loads and token factors.
12399   while (!Queue.empty()) {
12400     SDNode *ChainNext = Queue.pop_back_val();
12401     if (!Visited.insert(ChainNext).second)
12402       continue;
12403 
12404     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12405       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12406         return true;
12407 
12408       if (!Visited.count(ChainLD->getChain().getNode()))
12409         Queue.push_back(ChainLD->getChain().getNode());
12410     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12411       for (const SDUse &O : ChainNext->ops())
12412         if (!Visited.count(O.getNode()))
12413           Queue.push_back(O.getNode());
12414     } else
12415       LoadRoots.insert(ChainNext);
12416   }
12417 
12418   // Second, search down the chain, starting from the top-level nodes recorded
12419   // in the first phase. These top-level nodes are the nodes just above all
12420   // loads and token factors. Starting with their uses, recursively look though
12421   // all loads (just the chain uses) and token factors to find a consecutive
12422   // load.
12423   Visited.clear();
12424   Queue.clear();
12425 
12426   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12427        IE = LoadRoots.end(); I != IE; ++I) {
12428     Queue.push_back(*I);
12429 
12430     while (!Queue.empty()) {
12431       SDNode *LoadRoot = Queue.pop_back_val();
12432       if (!Visited.insert(LoadRoot).second)
12433         continue;
12434 
12435       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12436         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12437           return true;
12438 
12439       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12440            UE = LoadRoot->use_end(); UI != UE; ++UI)
12441         if (((isa<MemSDNode>(*UI) &&
12442             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12443             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12444           Queue.push_back(*UI);
12445     }
12446   }
12447 
12448   return false;
12449 }
12450 
12451 /// This function is called when we have proved that a SETCC node can be replaced
12452 /// by subtraction (and other supporting instructions) so that the result of
12453 /// comparison is kept in a GPR instead of CR. This function is purely for
12454 /// codegen purposes and has some flags to guide the codegen process.
12455 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12456                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12457   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12458 
12459   // Zero extend the operands to the largest legal integer. Originally, they
12460   // must be of a strictly smaller size.
12461   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12462                          DAG.getConstant(Size, DL, MVT::i32));
12463   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12464                          DAG.getConstant(Size, DL, MVT::i32));
12465 
12466   // Swap if needed. Depends on the condition code.
12467   if (Swap)
12468     std::swap(Op0, Op1);
12469 
12470   // Subtract extended integers.
12471   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12472 
12473   // Move the sign bit to the least significant position and zero out the rest.
12474   // Now the least significant bit carries the result of original comparison.
12475   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12476                              DAG.getConstant(Size - 1, DL, MVT::i32));
12477   auto Final = Shifted;
12478 
12479   // Complement the result if needed. Based on the condition code.
12480   if (Complement)
12481     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12482                         DAG.getConstant(1, DL, MVT::i64));
12483 
12484   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12485 }
12486 
12487 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12488                                                   DAGCombinerInfo &DCI) const {
12489   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12490 
12491   SelectionDAG &DAG = DCI.DAG;
12492   SDLoc DL(N);
12493 
12494   // Size of integers being compared has a critical role in the following
12495   // analysis, so we prefer to do this when all types are legal.
12496   if (!DCI.isAfterLegalizeDAG())
12497     return SDValue();
12498 
12499   // If all users of SETCC extend its value to a legal integer type
12500   // then we replace SETCC with a subtraction
12501   for (SDNode::use_iterator UI = N->use_begin(),
12502        UE = N->use_end(); UI != UE; ++UI) {
12503     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12504       return SDValue();
12505   }
12506 
12507   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12508   auto OpSize = N->getOperand(0).getValueSizeInBits();
12509 
12510   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12511 
12512   if (OpSize < Size) {
12513     switch (CC) {
12514     default: break;
12515     case ISD::SETULT:
12516       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12517     case ISD::SETULE:
12518       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12519     case ISD::SETUGT:
12520       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12521     case ISD::SETUGE:
12522       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12523     }
12524   }
12525 
12526   return SDValue();
12527 }
12528 
12529 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12530                                                   DAGCombinerInfo &DCI) const {
12531   SelectionDAG &DAG = DCI.DAG;
12532   SDLoc dl(N);
12533 
12534   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12535   // If we're tracking CR bits, we need to be careful that we don't have:
12536   //   trunc(binary-ops(zext(x), zext(y)))
12537   // or
12538   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12539   // such that we're unnecessarily moving things into GPRs when it would be
12540   // better to keep them in CR bits.
12541 
12542   // Note that trunc here can be an actual i1 trunc, or can be the effective
12543   // truncation that comes from a setcc or select_cc.
12544   if (N->getOpcode() == ISD::TRUNCATE &&
12545       N->getValueType(0) != MVT::i1)
12546     return SDValue();
12547 
12548   if (N->getOperand(0).getValueType() != MVT::i32 &&
12549       N->getOperand(0).getValueType() != MVT::i64)
12550     return SDValue();
12551 
12552   if (N->getOpcode() == ISD::SETCC ||
12553       N->getOpcode() == ISD::SELECT_CC) {
12554     // If we're looking at a comparison, then we need to make sure that the
12555     // high bits (all except for the first) don't matter the result.
12556     ISD::CondCode CC =
12557       cast<CondCodeSDNode>(N->getOperand(
12558         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12559     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12560 
12561     if (ISD::isSignedIntSetCC(CC)) {
12562       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12563           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12564         return SDValue();
12565     } else if (ISD::isUnsignedIntSetCC(CC)) {
12566       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12567                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12568           !DAG.MaskedValueIsZero(N->getOperand(1),
12569                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12570         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12571                                              : SDValue());
12572     } else {
12573       // This is neither a signed nor an unsigned comparison, just make sure
12574       // that the high bits are equal.
12575       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12576       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12577 
12578       // We don't really care about what is known about the first bit (if
12579       // anything), so pretend that it is known zero for both to ensure they can
12580       // be compared as constants.
12581       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
12582       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
12583 
12584       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
12585           Op1Known.getConstant() != Op2Known.getConstant())
12586         return SDValue();
12587     }
12588   }
12589 
12590   // We now know that the higher-order bits are irrelevant, we just need to
12591   // make sure that all of the intermediate operations are bit operations, and
12592   // all inputs are extensions.
12593   if (N->getOperand(0).getOpcode() != ISD::AND &&
12594       N->getOperand(0).getOpcode() != ISD::OR  &&
12595       N->getOperand(0).getOpcode() != ISD::XOR &&
12596       N->getOperand(0).getOpcode() != ISD::SELECT &&
12597       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12598       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12599       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12600       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12601       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12602     return SDValue();
12603 
12604   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12605       N->getOperand(1).getOpcode() != ISD::AND &&
12606       N->getOperand(1).getOpcode() != ISD::OR  &&
12607       N->getOperand(1).getOpcode() != ISD::XOR &&
12608       N->getOperand(1).getOpcode() != ISD::SELECT &&
12609       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12610       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12611       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12612       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12613       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12614     return SDValue();
12615 
12616   SmallVector<SDValue, 4> Inputs;
12617   SmallVector<SDValue, 8> BinOps, PromOps;
12618   SmallPtrSet<SDNode *, 16> Visited;
12619 
12620   for (unsigned i = 0; i < 2; ++i) {
12621     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12622           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12623           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12624           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12625         isa<ConstantSDNode>(N->getOperand(i)))
12626       Inputs.push_back(N->getOperand(i));
12627     else
12628       BinOps.push_back(N->getOperand(i));
12629 
12630     if (N->getOpcode() == ISD::TRUNCATE)
12631       break;
12632   }
12633 
12634   // Visit all inputs, collect all binary operations (and, or, xor and
12635   // select) that are all fed by extensions.
12636   while (!BinOps.empty()) {
12637     SDValue BinOp = BinOps.pop_back_val();
12638 
12639     if (!Visited.insert(BinOp.getNode()).second)
12640       continue;
12641 
12642     PromOps.push_back(BinOp);
12643 
12644     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12645       // The condition of the select is not promoted.
12646       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12647         continue;
12648       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12649         continue;
12650 
12651       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12652             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12653             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12654            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12655           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12656         Inputs.push_back(BinOp.getOperand(i));
12657       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12658                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12659                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12660                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12661                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12662                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12663                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12664                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12665                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12666         BinOps.push_back(BinOp.getOperand(i));
12667       } else {
12668         // We have an input that is not an extension or another binary
12669         // operation; we'll abort this transformation.
12670         return SDValue();
12671       }
12672     }
12673   }
12674 
12675   // Make sure that this is a self-contained cluster of operations (which
12676   // is not quite the same thing as saying that everything has only one
12677   // use).
12678   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12679     if (isa<ConstantSDNode>(Inputs[i]))
12680       continue;
12681 
12682     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12683                               UE = Inputs[i].getNode()->use_end();
12684          UI != UE; ++UI) {
12685       SDNode *User = *UI;
12686       if (User != N && !Visited.count(User))
12687         return SDValue();
12688 
12689       // Make sure that we're not going to promote the non-output-value
12690       // operand(s) or SELECT or SELECT_CC.
12691       // FIXME: Although we could sometimes handle this, and it does occur in
12692       // practice that one of the condition inputs to the select is also one of
12693       // the outputs, we currently can't deal with this.
12694       if (User->getOpcode() == ISD::SELECT) {
12695         if (User->getOperand(0) == Inputs[i])
12696           return SDValue();
12697       } else if (User->getOpcode() == ISD::SELECT_CC) {
12698         if (User->getOperand(0) == Inputs[i] ||
12699             User->getOperand(1) == Inputs[i])
12700           return SDValue();
12701       }
12702     }
12703   }
12704 
12705   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12706     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12707                               UE = PromOps[i].getNode()->use_end();
12708          UI != UE; ++UI) {
12709       SDNode *User = *UI;
12710       if (User != N && !Visited.count(User))
12711         return SDValue();
12712 
12713       // Make sure that we're not going to promote the non-output-value
12714       // operand(s) or SELECT or SELECT_CC.
12715       // FIXME: Although we could sometimes handle this, and it does occur in
12716       // practice that one of the condition inputs to the select is also one of
12717       // the outputs, we currently can't deal with this.
12718       if (User->getOpcode() == ISD::SELECT) {
12719         if (User->getOperand(0) == PromOps[i])
12720           return SDValue();
12721       } else if (User->getOpcode() == ISD::SELECT_CC) {
12722         if (User->getOperand(0) == PromOps[i] ||
12723             User->getOperand(1) == PromOps[i])
12724           return SDValue();
12725       }
12726     }
12727   }
12728 
12729   // Replace all inputs with the extension operand.
12730   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12731     // Constants may have users outside the cluster of to-be-promoted nodes,
12732     // and so we need to replace those as we do the promotions.
12733     if (isa<ConstantSDNode>(Inputs[i]))
12734       continue;
12735     else
12736       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12737   }
12738 
12739   std::list<HandleSDNode> PromOpHandles;
12740   for (auto &PromOp : PromOps)
12741     PromOpHandles.emplace_back(PromOp);
12742 
12743   // Replace all operations (these are all the same, but have a different
12744   // (i1) return type). DAG.getNode will validate that the types of
12745   // a binary operator match, so go through the list in reverse so that
12746   // we've likely promoted both operands first. Any intermediate truncations or
12747   // extensions disappear.
12748   while (!PromOpHandles.empty()) {
12749     SDValue PromOp = PromOpHandles.back().getValue();
12750     PromOpHandles.pop_back();
12751 
12752     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12753         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12754         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12755         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12756       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12757           PromOp.getOperand(0).getValueType() != MVT::i1) {
12758         // The operand is not yet ready (see comment below).
12759         PromOpHandles.emplace_front(PromOp);
12760         continue;
12761       }
12762 
12763       SDValue RepValue = PromOp.getOperand(0);
12764       if (isa<ConstantSDNode>(RepValue))
12765         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12766 
12767       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12768       continue;
12769     }
12770 
12771     unsigned C;
12772     switch (PromOp.getOpcode()) {
12773     default:             C = 0; break;
12774     case ISD::SELECT:    C = 1; break;
12775     case ISD::SELECT_CC: C = 2; break;
12776     }
12777 
12778     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12779          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12780         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12781          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12782       // The to-be-promoted operands of this node have not yet been
12783       // promoted (this should be rare because we're going through the
12784       // list backward, but if one of the operands has several users in
12785       // this cluster of to-be-promoted nodes, it is possible).
12786       PromOpHandles.emplace_front(PromOp);
12787       continue;
12788     }
12789 
12790     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12791                                 PromOp.getNode()->op_end());
12792 
12793     // If there are any constant inputs, make sure they're replaced now.
12794     for (unsigned i = 0; i < 2; ++i)
12795       if (isa<ConstantSDNode>(Ops[C+i]))
12796         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12797 
12798     DAG.ReplaceAllUsesOfValueWith(PromOp,
12799       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12800   }
12801 
12802   // Now we're left with the initial truncation itself.
12803   if (N->getOpcode() == ISD::TRUNCATE)
12804     return N->getOperand(0);
12805 
12806   // Otherwise, this is a comparison. The operands to be compared have just
12807   // changed type (to i1), but everything else is the same.
12808   return SDValue(N, 0);
12809 }
12810 
12811 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12812                                                   DAGCombinerInfo &DCI) const {
12813   SelectionDAG &DAG = DCI.DAG;
12814   SDLoc dl(N);
12815 
12816   // If we're tracking CR bits, we need to be careful that we don't have:
12817   //   zext(binary-ops(trunc(x), trunc(y)))
12818   // or
12819   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12820   // such that we're unnecessarily moving things into CR bits that can more
12821   // efficiently stay in GPRs. Note that if we're not certain that the high
12822   // bits are set as required by the final extension, we still may need to do
12823   // some masking to get the proper behavior.
12824 
12825   // This same functionality is important on PPC64 when dealing with
12826   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12827   // the return values of functions. Because it is so similar, it is handled
12828   // here as well.
12829 
12830   if (N->getValueType(0) != MVT::i32 &&
12831       N->getValueType(0) != MVT::i64)
12832     return SDValue();
12833 
12834   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12835         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12836     return SDValue();
12837 
12838   if (N->getOperand(0).getOpcode() != ISD::AND &&
12839       N->getOperand(0).getOpcode() != ISD::OR  &&
12840       N->getOperand(0).getOpcode() != ISD::XOR &&
12841       N->getOperand(0).getOpcode() != ISD::SELECT &&
12842       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12843     return SDValue();
12844 
12845   SmallVector<SDValue, 4> Inputs;
12846   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12847   SmallPtrSet<SDNode *, 16> Visited;
12848 
12849   // Visit all inputs, collect all binary operations (and, or, xor and
12850   // select) that are all fed by truncations.
12851   while (!BinOps.empty()) {
12852     SDValue BinOp = BinOps.pop_back_val();
12853 
12854     if (!Visited.insert(BinOp.getNode()).second)
12855       continue;
12856 
12857     PromOps.push_back(BinOp);
12858 
12859     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12860       // The condition of the select is not promoted.
12861       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12862         continue;
12863       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12864         continue;
12865 
12866       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12867           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12868         Inputs.push_back(BinOp.getOperand(i));
12869       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12870                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12871                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12872                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12873                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12874         BinOps.push_back(BinOp.getOperand(i));
12875       } else {
12876         // We have an input that is not a truncation or another binary
12877         // operation; we'll abort this transformation.
12878         return SDValue();
12879       }
12880     }
12881   }
12882 
12883   // The operands of a select that must be truncated when the select is
12884   // promoted because the operand is actually part of the to-be-promoted set.
12885   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12886 
12887   // Make sure that this is a self-contained cluster of operations (which
12888   // is not quite the same thing as saying that everything has only one
12889   // use).
12890   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12891     if (isa<ConstantSDNode>(Inputs[i]))
12892       continue;
12893 
12894     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12895                               UE = Inputs[i].getNode()->use_end();
12896          UI != UE; ++UI) {
12897       SDNode *User = *UI;
12898       if (User != N && !Visited.count(User))
12899         return SDValue();
12900 
12901       // If we're going to promote the non-output-value operand(s) or SELECT or
12902       // SELECT_CC, record them for truncation.
12903       if (User->getOpcode() == ISD::SELECT) {
12904         if (User->getOperand(0) == Inputs[i])
12905           SelectTruncOp[0].insert(std::make_pair(User,
12906                                     User->getOperand(0).getValueType()));
12907       } else if (User->getOpcode() == ISD::SELECT_CC) {
12908         if (User->getOperand(0) == Inputs[i])
12909           SelectTruncOp[0].insert(std::make_pair(User,
12910                                     User->getOperand(0).getValueType()));
12911         if (User->getOperand(1) == Inputs[i])
12912           SelectTruncOp[1].insert(std::make_pair(User,
12913                                     User->getOperand(1).getValueType()));
12914       }
12915     }
12916   }
12917 
12918   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12919     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12920                               UE = PromOps[i].getNode()->use_end();
12921          UI != UE; ++UI) {
12922       SDNode *User = *UI;
12923       if (User != N && !Visited.count(User))
12924         return SDValue();
12925 
12926       // If we're going to promote the non-output-value operand(s) or SELECT or
12927       // SELECT_CC, record them for truncation.
12928       if (User->getOpcode() == ISD::SELECT) {
12929         if (User->getOperand(0) == PromOps[i])
12930           SelectTruncOp[0].insert(std::make_pair(User,
12931                                     User->getOperand(0).getValueType()));
12932       } else if (User->getOpcode() == ISD::SELECT_CC) {
12933         if (User->getOperand(0) == PromOps[i])
12934           SelectTruncOp[0].insert(std::make_pair(User,
12935                                     User->getOperand(0).getValueType()));
12936         if (User->getOperand(1) == PromOps[i])
12937           SelectTruncOp[1].insert(std::make_pair(User,
12938                                     User->getOperand(1).getValueType()));
12939       }
12940     }
12941   }
12942 
12943   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12944   bool ReallyNeedsExt = false;
12945   if (N->getOpcode() != ISD::ANY_EXTEND) {
12946     // If all of the inputs are not already sign/zero extended, then
12947     // we'll still need to do that at the end.
12948     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12949       if (isa<ConstantSDNode>(Inputs[i]))
12950         continue;
12951 
12952       unsigned OpBits =
12953         Inputs[i].getOperand(0).getValueSizeInBits();
12954       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12955 
12956       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12957            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12958                                   APInt::getHighBitsSet(OpBits,
12959                                                         OpBits-PromBits))) ||
12960           (N->getOpcode() == ISD::SIGN_EXTEND &&
12961            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12962              (OpBits-(PromBits-1)))) {
12963         ReallyNeedsExt = true;
12964         break;
12965       }
12966     }
12967   }
12968 
12969   // Replace all inputs, either with the truncation operand, or a
12970   // truncation or extension to the final output type.
12971   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12972     // Constant inputs need to be replaced with the to-be-promoted nodes that
12973     // use them because they might have users outside of the cluster of
12974     // promoted nodes.
12975     if (isa<ConstantSDNode>(Inputs[i]))
12976       continue;
12977 
12978     SDValue InSrc = Inputs[i].getOperand(0);
12979     if (Inputs[i].getValueType() == N->getValueType(0))
12980       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12981     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12982       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12983         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12984     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12985       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12986         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12987     else
12988       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12989         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12990   }
12991 
12992   std::list<HandleSDNode> PromOpHandles;
12993   for (auto &PromOp : PromOps)
12994     PromOpHandles.emplace_back(PromOp);
12995 
12996   // Replace all operations (these are all the same, but have a different
12997   // (promoted) return type). DAG.getNode will validate that the types of
12998   // a binary operator match, so go through the list in reverse so that
12999   // we've likely promoted both operands first.
13000   while (!PromOpHandles.empty()) {
13001     SDValue PromOp = PromOpHandles.back().getValue();
13002     PromOpHandles.pop_back();
13003 
13004     unsigned C;
13005     switch (PromOp.getOpcode()) {
13006     default:             C = 0; break;
13007     case ISD::SELECT:    C = 1; break;
13008     case ISD::SELECT_CC: C = 2; break;
13009     }
13010 
13011     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13012          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13013         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13014          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13015       // The to-be-promoted operands of this node have not yet been
13016       // promoted (this should be rare because we're going through the
13017       // list backward, but if one of the operands has several users in
13018       // this cluster of to-be-promoted nodes, it is possible).
13019       PromOpHandles.emplace_front(PromOp);
13020       continue;
13021     }
13022 
13023     // For SELECT and SELECT_CC nodes, we do a similar check for any
13024     // to-be-promoted comparison inputs.
13025     if (PromOp.getOpcode() == ISD::SELECT ||
13026         PromOp.getOpcode() == ISD::SELECT_CC) {
13027       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13028            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13029           (SelectTruncOp[1].count(PromOp.getNode()) &&
13030            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13031         PromOpHandles.emplace_front(PromOp);
13032         continue;
13033       }
13034     }
13035 
13036     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13037                                 PromOp.getNode()->op_end());
13038 
13039     // If this node has constant inputs, then they'll need to be promoted here.
13040     for (unsigned i = 0; i < 2; ++i) {
13041       if (!isa<ConstantSDNode>(Ops[C+i]))
13042         continue;
13043       if (Ops[C+i].getValueType() == N->getValueType(0))
13044         continue;
13045 
13046       if (N->getOpcode() == ISD::SIGN_EXTEND)
13047         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13048       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13049         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13050       else
13051         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13052     }
13053 
13054     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13055     // truncate them again to the original value type.
13056     if (PromOp.getOpcode() == ISD::SELECT ||
13057         PromOp.getOpcode() == ISD::SELECT_CC) {
13058       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13059       if (SI0 != SelectTruncOp[0].end())
13060         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13061       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13062       if (SI1 != SelectTruncOp[1].end())
13063         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13064     }
13065 
13066     DAG.ReplaceAllUsesOfValueWith(PromOp,
13067       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13068   }
13069 
13070   // Now we're left with the initial extension itself.
13071   if (!ReallyNeedsExt)
13072     return N->getOperand(0);
13073 
13074   // To zero extend, just mask off everything except for the first bit (in the
13075   // i1 case).
13076   if (N->getOpcode() == ISD::ZERO_EXTEND)
13077     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13078                        DAG.getConstant(APInt::getLowBitsSet(
13079                                          N->getValueSizeInBits(0), PromBits),
13080                                        dl, N->getValueType(0)));
13081 
13082   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13083          "Invalid extension type");
13084   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13085   SDValue ShiftCst =
13086       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13087   return DAG.getNode(
13088       ISD::SRA, dl, N->getValueType(0),
13089       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13090       ShiftCst);
13091 }
13092 
13093 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13094                                         DAGCombinerInfo &DCI) const {
13095   assert(N->getOpcode() == ISD::SETCC &&
13096          "Should be called with a SETCC node");
13097 
13098   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13099   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13100     SDValue LHS = N->getOperand(0);
13101     SDValue RHS = N->getOperand(1);
13102 
13103     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13104     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13105         LHS.hasOneUse())
13106       std::swap(LHS, RHS);
13107 
13108     // x == 0-y --> x+y == 0
13109     // x != 0-y --> x+y != 0
13110     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13111         RHS.hasOneUse()) {
13112       SDLoc DL(N);
13113       SelectionDAG &DAG = DCI.DAG;
13114       EVT VT = N->getValueType(0);
13115       EVT OpVT = LHS.getValueType();
13116       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13117       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13118     }
13119   }
13120 
13121   return DAGCombineTruncBoolExt(N, DCI);
13122 }
13123 
13124 // Is this an extending load from an f32 to an f64?
13125 static bool isFPExtLoad(SDValue Op) {
13126   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13127     return LD->getExtensionType() == ISD::EXTLOAD &&
13128       Op.getValueType() == MVT::f64;
13129   return false;
13130 }
13131 
13132 /// Reduces the number of fp-to-int conversion when building a vector.
13133 ///
13134 /// If this vector is built out of floating to integer conversions,
13135 /// transform it to a vector built out of floating point values followed by a
13136 /// single floating to integer conversion of the vector.
13137 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13138 /// becomes (fptosi (build_vector ($A, $B, ...)))
13139 SDValue PPCTargetLowering::
13140 combineElementTruncationToVectorTruncation(SDNode *N,
13141                                            DAGCombinerInfo &DCI) const {
13142   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13143          "Should be called with a BUILD_VECTOR node");
13144 
13145   SelectionDAG &DAG = DCI.DAG;
13146   SDLoc dl(N);
13147 
13148   SDValue FirstInput = N->getOperand(0);
13149   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13150          "The input operand must be an fp-to-int conversion.");
13151 
13152   // This combine happens after legalization so the fp_to_[su]i nodes are
13153   // already converted to PPCSISD nodes.
13154   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13155   if (FirstConversion == PPCISD::FCTIDZ ||
13156       FirstConversion == PPCISD::FCTIDUZ ||
13157       FirstConversion == PPCISD::FCTIWZ ||
13158       FirstConversion == PPCISD::FCTIWUZ) {
13159     bool IsSplat = true;
13160     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13161       FirstConversion == PPCISD::FCTIWUZ;
13162     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13163     SmallVector<SDValue, 4> Ops;
13164     EVT TargetVT = N->getValueType(0);
13165     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13166       SDValue NextOp = N->getOperand(i);
13167       if (NextOp.getOpcode() != PPCISD::MFVSR)
13168         return SDValue();
13169       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13170       if (NextConversion != FirstConversion)
13171         return SDValue();
13172       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13173       // This is not valid if the input was originally double precision. It is
13174       // also not profitable to do unless this is an extending load in which
13175       // case doing this combine will allow us to combine consecutive loads.
13176       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13177         return SDValue();
13178       if (N->getOperand(i) != FirstInput)
13179         IsSplat = false;
13180     }
13181 
13182     // If this is a splat, we leave it as-is since there will be only a single
13183     // fp-to-int conversion followed by a splat of the integer. This is better
13184     // for 32-bit and smaller ints and neutral for 64-bit ints.
13185     if (IsSplat)
13186       return SDValue();
13187 
13188     // Now that we know we have the right type of node, get its operands
13189     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13190       SDValue In = N->getOperand(i).getOperand(0);
13191       if (Is32Bit) {
13192         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13193         // here, we know that all inputs are extending loads so this is safe).
13194         if (In.isUndef())
13195           Ops.push_back(DAG.getUNDEF(SrcVT));
13196         else {
13197           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13198                                       MVT::f32, In.getOperand(0),
13199                                       DAG.getIntPtrConstant(1, dl));
13200           Ops.push_back(Trunc);
13201         }
13202       } else
13203         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13204     }
13205 
13206     unsigned Opcode;
13207     if (FirstConversion == PPCISD::FCTIDZ ||
13208         FirstConversion == PPCISD::FCTIWZ)
13209       Opcode = ISD::FP_TO_SINT;
13210     else
13211       Opcode = ISD::FP_TO_UINT;
13212 
13213     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13214     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13215     return DAG.getNode(Opcode, dl, TargetVT, BV);
13216   }
13217   return SDValue();
13218 }
13219 
13220 /// Reduce the number of loads when building a vector.
13221 ///
13222 /// Building a vector out of multiple loads can be converted to a load
13223 /// of the vector type if the loads are consecutive. If the loads are
13224 /// consecutive but in descending order, a shuffle is added at the end
13225 /// to reorder the vector.
13226 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13227   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13228          "Should be called with a BUILD_VECTOR node");
13229 
13230   SDLoc dl(N);
13231 
13232   // Return early for non byte-sized type, as they can't be consecutive.
13233   if (!N->getValueType(0).getVectorElementType().isByteSized())
13234     return SDValue();
13235 
13236   bool InputsAreConsecutiveLoads = true;
13237   bool InputsAreReverseConsecutive = true;
13238   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13239   SDValue FirstInput = N->getOperand(0);
13240   bool IsRoundOfExtLoad = false;
13241 
13242   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13243       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13244     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13245     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13246   }
13247   // Not a build vector of (possibly fp_rounded) loads.
13248   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13249       N->getNumOperands() == 1)
13250     return SDValue();
13251 
13252   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13253     // If any inputs are fp_round(extload), they all must be.
13254     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13255       return SDValue();
13256 
13257     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13258       N->getOperand(i);
13259     if (NextInput.getOpcode() != ISD::LOAD)
13260       return SDValue();
13261 
13262     SDValue PreviousInput =
13263       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13264     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13265     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13266 
13267     // If any inputs are fp_round(extload), they all must be.
13268     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13269       return SDValue();
13270 
13271     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13272       InputsAreConsecutiveLoads = false;
13273     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13274       InputsAreReverseConsecutive = false;
13275 
13276     // Exit early if the loads are neither consecutive nor reverse consecutive.
13277     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13278       return SDValue();
13279   }
13280 
13281   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13282          "The loads cannot be both consecutive and reverse consecutive.");
13283 
13284   SDValue FirstLoadOp =
13285     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13286   SDValue LastLoadOp =
13287     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13288                        N->getOperand(N->getNumOperands()-1);
13289 
13290   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13291   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13292   if (InputsAreConsecutiveLoads) {
13293     assert(LD1 && "Input needs to be a LoadSDNode.");
13294     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13295                        LD1->getBasePtr(), LD1->getPointerInfo(),
13296                        LD1->getAlignment());
13297   }
13298   if (InputsAreReverseConsecutive) {
13299     assert(LDL && "Input needs to be a LoadSDNode.");
13300     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13301                                LDL->getBasePtr(), LDL->getPointerInfo(),
13302                                LDL->getAlignment());
13303     SmallVector<int, 16> Ops;
13304     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13305       Ops.push_back(i);
13306 
13307     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13308                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13309   }
13310   return SDValue();
13311 }
13312 
13313 // This function adds the required vector_shuffle needed to get
13314 // the elements of the vector extract in the correct position
13315 // as specified by the CorrectElems encoding.
13316 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13317                                       SDValue Input, uint64_t Elems,
13318                                       uint64_t CorrectElems) {
13319   SDLoc dl(N);
13320 
13321   unsigned NumElems = Input.getValueType().getVectorNumElements();
13322   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13323 
13324   // Knowing the element indices being extracted from the original
13325   // vector and the order in which they're being inserted, just put
13326   // them at element indices required for the instruction.
13327   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13328     if (DAG.getDataLayout().isLittleEndian())
13329       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13330     else
13331       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13332     CorrectElems = CorrectElems >> 8;
13333     Elems = Elems >> 8;
13334   }
13335 
13336   SDValue Shuffle =
13337       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13338                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13339 
13340   EVT VT = N->getValueType(0);
13341   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13342 
13343   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13344                                Input.getValueType().getVectorElementType(),
13345                                VT.getVectorNumElements());
13346   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13347                      DAG.getValueType(ExtVT));
13348 }
13349 
13350 // Look for build vector patterns where input operands come from sign
13351 // extended vector_extract elements of specific indices. If the correct indices
13352 // aren't used, add a vector shuffle to fix up the indices and create
13353 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13354 // during instruction selection.
13355 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13356   // This array encodes the indices that the vector sign extend instructions
13357   // extract from when extending from one type to another for both BE and LE.
13358   // The right nibble of each byte corresponds to the LE incides.
13359   // and the left nibble of each byte corresponds to the BE incides.
13360   // For example: 0x3074B8FC  byte->word
13361   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13362   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13363   // For example: 0x000070F8  byte->double word
13364   // For LE: the allowed indices are: 0x0,0x8
13365   // For BE: the allowed indices are: 0x7,0xF
13366   uint64_t TargetElems[] = {
13367       0x3074B8FC, // b->w
13368       0x000070F8, // b->d
13369       0x10325476, // h->w
13370       0x00003074, // h->d
13371       0x00001032, // w->d
13372   };
13373 
13374   uint64_t Elems = 0;
13375   int Index;
13376   SDValue Input;
13377 
13378   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13379     if (!Op)
13380       return false;
13381     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13382         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13383       return false;
13384 
13385     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13386     // of the right width.
13387     SDValue Extract = Op.getOperand(0);
13388     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13389       Extract = Extract.getOperand(0);
13390     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13391       return false;
13392 
13393     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13394     if (!ExtOp)
13395       return false;
13396 
13397     Index = ExtOp->getZExtValue();
13398     if (Input && Input != Extract.getOperand(0))
13399       return false;
13400 
13401     if (!Input)
13402       Input = Extract.getOperand(0);
13403 
13404     Elems = Elems << 8;
13405     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13406     Elems |= Index;
13407 
13408     return true;
13409   };
13410 
13411   // If the build vector operands aren't sign extended vector extracts,
13412   // of the same input vector, then return.
13413   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13414     if (!isSExtOfVecExtract(N->getOperand(i))) {
13415       return SDValue();
13416     }
13417   }
13418 
13419   // If the vector extract indicies are not correct, add the appropriate
13420   // vector_shuffle.
13421   int TgtElemArrayIdx;
13422   int InputSize = Input.getValueType().getScalarSizeInBits();
13423   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13424   if (InputSize + OutputSize == 40)
13425     TgtElemArrayIdx = 0;
13426   else if (InputSize + OutputSize == 72)
13427     TgtElemArrayIdx = 1;
13428   else if (InputSize + OutputSize == 48)
13429     TgtElemArrayIdx = 2;
13430   else if (InputSize + OutputSize == 80)
13431     TgtElemArrayIdx = 3;
13432   else if (InputSize + OutputSize == 96)
13433     TgtElemArrayIdx = 4;
13434   else
13435     return SDValue();
13436 
13437   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13438   CorrectElems = DAG.getDataLayout().isLittleEndian()
13439                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13440                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13441   if (Elems != CorrectElems) {
13442     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13443   }
13444 
13445   // Regular lowering will catch cases where a shuffle is not needed.
13446   return SDValue();
13447 }
13448 
13449 // Look for the pattern of a load from a narrow width to i128, feeding
13450 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13451 // (LXVRZX). This node represents a zero extending load that will be matched
13452 // to the Load VSX Vector Rightmost instructions.
13453 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13454   SDLoc DL(N);
13455 
13456   // This combine is only eligible for a BUILD_VECTOR of v1i128.
13457   if (N->getValueType(0) != MVT::v1i128)
13458     return SDValue();
13459 
13460   SDValue Operand = N->getOperand(0);
13461   // Proceed with the transformation if the operand to the BUILD_VECTOR
13462   // is a load instruction.
13463   if (Operand.getOpcode() != ISD::LOAD)
13464     return SDValue();
13465 
13466   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
13467   EVT MemoryType = LD->getMemoryVT();
13468 
13469   // This transformation is only valid if the we are loading either a byte,
13470   // halfword, word, or doubleword.
13471   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
13472                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
13473 
13474   // Ensure that the load from the narrow width is being zero extended to i128.
13475   if (!ValidLDType ||
13476       (LD->getExtensionType() != ISD::ZEXTLOAD &&
13477        LD->getExtensionType() != ISD::EXTLOAD))
13478     return SDValue();
13479 
13480   SDValue LoadOps[] = {
13481       LD->getChain(), LD->getBasePtr(),
13482       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
13483 
13484   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
13485                                  DAG.getVTList(MVT::v1i128, MVT::Other),
13486                                  LoadOps, MemoryType, LD->getMemOperand());
13487 }
13488 
13489 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13490                                                  DAGCombinerInfo &DCI) const {
13491   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13492          "Should be called with a BUILD_VECTOR node");
13493 
13494   SelectionDAG &DAG = DCI.DAG;
13495   SDLoc dl(N);
13496 
13497   if (!Subtarget.hasVSX())
13498     return SDValue();
13499 
13500   // The target independent DAG combiner will leave a build_vector of
13501   // float-to-int conversions intact. We can generate MUCH better code for
13502   // a float-to-int conversion of a vector of floats.
13503   SDValue FirstInput = N->getOperand(0);
13504   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13505     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13506     if (Reduced)
13507       return Reduced;
13508   }
13509 
13510   // If we're building a vector out of consecutive loads, just load that
13511   // vector type.
13512   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13513   if (Reduced)
13514     return Reduced;
13515 
13516   // If we're building a vector out of extended elements from another vector
13517   // we have P9 vector integer extend instructions. The code assumes legal
13518   // input types (i.e. it can't handle things like v4i16) so do not run before
13519   // legalization.
13520   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13521     Reduced = combineBVOfVecSExt(N, DAG);
13522     if (Reduced)
13523       return Reduced;
13524   }
13525 
13526   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
13527   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
13528   // is a load from <valid narrow width> to i128.
13529   if (Subtarget.isISA3_1()) {
13530     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
13531     if (BVOfZLoad)
13532       return BVOfZLoad;
13533   }
13534 
13535   if (N->getValueType(0) != MVT::v2f64)
13536     return SDValue();
13537 
13538   // Looking for:
13539   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13540   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13541       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13542     return SDValue();
13543   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13544       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13545     return SDValue();
13546   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13547     return SDValue();
13548 
13549   SDValue Ext1 = FirstInput.getOperand(0);
13550   SDValue Ext2 = N->getOperand(1).getOperand(0);
13551   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13552      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13553     return SDValue();
13554 
13555   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13556   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13557   if (!Ext1Op || !Ext2Op)
13558     return SDValue();
13559   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13560       Ext1.getOperand(0) != Ext2.getOperand(0))
13561     return SDValue();
13562 
13563   int FirstElem = Ext1Op->getZExtValue();
13564   int SecondElem = Ext2Op->getZExtValue();
13565   int SubvecIdx;
13566   if (FirstElem == 0 && SecondElem == 1)
13567     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13568   else if (FirstElem == 2 && SecondElem == 3)
13569     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13570   else
13571     return SDValue();
13572 
13573   SDValue SrcVec = Ext1.getOperand(0);
13574   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13575     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13576   return DAG.getNode(NodeType, dl, MVT::v2f64,
13577                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13578 }
13579 
13580 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13581                                               DAGCombinerInfo &DCI) const {
13582   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13583           N->getOpcode() == ISD::UINT_TO_FP) &&
13584          "Need an int -> FP conversion node here");
13585 
13586   if (useSoftFloat() || !Subtarget.has64BitSupport())
13587     return SDValue();
13588 
13589   SelectionDAG &DAG = DCI.DAG;
13590   SDLoc dl(N);
13591   SDValue Op(N, 0);
13592 
13593   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13594   // from the hardware.
13595   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13596     return SDValue();
13597   if (!Op.getOperand(0).getValueType().isSimple())
13598     return SDValue();
13599   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13600       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13601     return SDValue();
13602 
13603   SDValue FirstOperand(Op.getOperand(0));
13604   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13605     (FirstOperand.getValueType() == MVT::i8 ||
13606      FirstOperand.getValueType() == MVT::i16);
13607   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13608     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13609     bool DstDouble = Op.getValueType() == MVT::f64;
13610     unsigned ConvOp = Signed ?
13611       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13612       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13613     SDValue WidthConst =
13614       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13615                             dl, false);
13616     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13617     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13618     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13619                                          DAG.getVTList(MVT::f64, MVT::Other),
13620                                          Ops, MVT::i8, LDN->getMemOperand());
13621 
13622     // For signed conversion, we need to sign-extend the value in the VSR
13623     if (Signed) {
13624       SDValue ExtOps[] = { Ld, WidthConst };
13625       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13626       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13627     } else
13628       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13629   }
13630 
13631 
13632   // For i32 intermediate values, unfortunately, the conversion functions
13633   // leave the upper 32 bits of the value are undefined. Within the set of
13634   // scalar instructions, we have no method for zero- or sign-extending the
13635   // value. Thus, we cannot handle i32 intermediate values here.
13636   if (Op.getOperand(0).getValueType() == MVT::i32)
13637     return SDValue();
13638 
13639   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13640          "UINT_TO_FP is supported only with FPCVT");
13641 
13642   // If we have FCFIDS, then use it when converting to single-precision.
13643   // Otherwise, convert to double-precision and then round.
13644   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13645                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13646                                                             : PPCISD::FCFIDS)
13647                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13648                                                             : PPCISD::FCFID);
13649   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13650                   ? MVT::f32
13651                   : MVT::f64;
13652 
13653   // If we're converting from a float, to an int, and back to a float again,
13654   // then we don't need the store/load pair at all.
13655   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13656        Subtarget.hasFPCVT()) ||
13657       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13658     SDValue Src = Op.getOperand(0).getOperand(0);
13659     if (Src.getValueType() == MVT::f32) {
13660       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13661       DCI.AddToWorklist(Src.getNode());
13662     } else if (Src.getValueType() != MVT::f64) {
13663       // Make sure that we don't pick up a ppc_fp128 source value.
13664       return SDValue();
13665     }
13666 
13667     unsigned FCTOp =
13668       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13669                                                         PPCISD::FCTIDUZ;
13670 
13671     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13672     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13673 
13674     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13675       FP = DAG.getNode(ISD::FP_ROUND, dl,
13676                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13677       DCI.AddToWorklist(FP.getNode());
13678     }
13679 
13680     return FP;
13681   }
13682 
13683   return SDValue();
13684 }
13685 
13686 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13687 // builtins) into loads with swaps.
13688 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13689                                               DAGCombinerInfo &DCI) const {
13690   SelectionDAG &DAG = DCI.DAG;
13691   SDLoc dl(N);
13692   SDValue Chain;
13693   SDValue Base;
13694   MachineMemOperand *MMO;
13695 
13696   switch (N->getOpcode()) {
13697   default:
13698     llvm_unreachable("Unexpected opcode for little endian VSX load");
13699   case ISD::LOAD: {
13700     LoadSDNode *LD = cast<LoadSDNode>(N);
13701     Chain = LD->getChain();
13702     Base = LD->getBasePtr();
13703     MMO = LD->getMemOperand();
13704     // If the MMO suggests this isn't a load of a full vector, leave
13705     // things alone.  For a built-in, we have to make the change for
13706     // correctness, so if there is a size problem that will be a bug.
13707     if (MMO->getSize() < 16)
13708       return SDValue();
13709     break;
13710   }
13711   case ISD::INTRINSIC_W_CHAIN: {
13712     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13713     Chain = Intrin->getChain();
13714     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13715     // us what we want. Get operand 2 instead.
13716     Base = Intrin->getOperand(2);
13717     MMO = Intrin->getMemOperand();
13718     break;
13719   }
13720   }
13721 
13722   MVT VecTy = N->getValueType(0).getSimpleVT();
13723 
13724   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13725   // aligned and the type is a vector with elements up to 4 bytes
13726   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13727       VecTy.getScalarSizeInBits() <= 32) {
13728     return SDValue();
13729   }
13730 
13731   SDValue LoadOps[] = { Chain, Base };
13732   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13733                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13734                                          LoadOps, MVT::v2f64, MMO);
13735 
13736   DCI.AddToWorklist(Load.getNode());
13737   Chain = Load.getValue(1);
13738   SDValue Swap = DAG.getNode(
13739       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13740   DCI.AddToWorklist(Swap.getNode());
13741 
13742   // Add a bitcast if the resulting load type doesn't match v2f64.
13743   if (VecTy != MVT::v2f64) {
13744     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13745     DCI.AddToWorklist(N.getNode());
13746     // Package {bitcast value, swap's chain} to match Load's shape.
13747     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13748                        N, Swap.getValue(1));
13749   }
13750 
13751   return Swap;
13752 }
13753 
13754 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13755 // builtins) into stores with swaps.
13756 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13757                                                DAGCombinerInfo &DCI) const {
13758   SelectionDAG &DAG = DCI.DAG;
13759   SDLoc dl(N);
13760   SDValue Chain;
13761   SDValue Base;
13762   unsigned SrcOpnd;
13763   MachineMemOperand *MMO;
13764 
13765   switch (N->getOpcode()) {
13766   default:
13767     llvm_unreachable("Unexpected opcode for little endian VSX store");
13768   case ISD::STORE: {
13769     StoreSDNode *ST = cast<StoreSDNode>(N);
13770     Chain = ST->getChain();
13771     Base = ST->getBasePtr();
13772     MMO = ST->getMemOperand();
13773     SrcOpnd = 1;
13774     // If the MMO suggests this isn't a store of a full vector, leave
13775     // things alone.  For a built-in, we have to make the change for
13776     // correctness, so if there is a size problem that will be a bug.
13777     if (MMO->getSize() < 16)
13778       return SDValue();
13779     break;
13780   }
13781   case ISD::INTRINSIC_VOID: {
13782     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13783     Chain = Intrin->getChain();
13784     // Intrin->getBasePtr() oddly does not get what we want.
13785     Base = Intrin->getOperand(3);
13786     MMO = Intrin->getMemOperand();
13787     SrcOpnd = 2;
13788     break;
13789   }
13790   }
13791 
13792   SDValue Src = N->getOperand(SrcOpnd);
13793   MVT VecTy = Src.getValueType().getSimpleVT();
13794 
13795   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13796   // aligned and the type is a vector with elements up to 4 bytes
13797   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13798       VecTy.getScalarSizeInBits() <= 32) {
13799     return SDValue();
13800   }
13801 
13802   // All stores are done as v2f64 and possible bit cast.
13803   if (VecTy != MVT::v2f64) {
13804     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13805     DCI.AddToWorklist(Src.getNode());
13806   }
13807 
13808   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13809                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13810   DCI.AddToWorklist(Swap.getNode());
13811   Chain = Swap.getValue(1);
13812   SDValue StoreOps[] = { Chain, Swap, Base };
13813   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13814                                           DAG.getVTList(MVT::Other),
13815                                           StoreOps, VecTy, MMO);
13816   DCI.AddToWorklist(Store.getNode());
13817   return Store;
13818 }
13819 
13820 // Handle DAG combine for STORE (FP_TO_INT F).
13821 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13822                                                DAGCombinerInfo &DCI) const {
13823 
13824   SelectionDAG &DAG = DCI.DAG;
13825   SDLoc dl(N);
13826   unsigned Opcode = N->getOperand(1).getOpcode();
13827 
13828   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13829          && "Not a FP_TO_INT Instruction!");
13830 
13831   SDValue Val = N->getOperand(1).getOperand(0);
13832   EVT Op1VT = N->getOperand(1).getValueType();
13833   EVT ResVT = Val.getValueType();
13834 
13835   if (!isTypeLegal(ResVT))
13836     return SDValue();
13837 
13838   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13839   bool ValidTypeForStoreFltAsInt =
13840         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13841          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13842 
13843   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13844       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13845     return SDValue();
13846 
13847   // Extend f32 values to f64
13848   if (ResVT.getScalarSizeInBits() == 32) {
13849     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13850     DCI.AddToWorklist(Val.getNode());
13851   }
13852 
13853   // Set signed or unsigned conversion opcode.
13854   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13855                           PPCISD::FP_TO_SINT_IN_VSR :
13856                           PPCISD::FP_TO_UINT_IN_VSR;
13857 
13858   Val = DAG.getNode(ConvOpcode,
13859                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13860   DCI.AddToWorklist(Val.getNode());
13861 
13862   // Set number of bytes being converted.
13863   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13864   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13865                     DAG.getIntPtrConstant(ByteSize, dl, false),
13866                     DAG.getValueType(Op1VT) };
13867 
13868   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13869           DAG.getVTList(MVT::Other), Ops,
13870           cast<StoreSDNode>(N)->getMemoryVT(),
13871           cast<StoreSDNode>(N)->getMemOperand());
13872 
13873   DCI.AddToWorklist(Val.getNode());
13874   return Val;
13875 }
13876 
13877 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
13878   // Check that the source of the element keeps flipping
13879   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
13880   bool PrevElemFromFirstVec = Mask[0] < NumElts;
13881   for (int i = 1, e = Mask.size(); i < e; i++) {
13882     if (PrevElemFromFirstVec && Mask[i] < NumElts)
13883       return false;
13884     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
13885       return false;
13886     PrevElemFromFirstVec = !PrevElemFromFirstVec;
13887   }
13888   return true;
13889 }
13890 
13891 static bool isSplatBV(SDValue Op) {
13892   if (Op.getOpcode() != ISD::BUILD_VECTOR)
13893     return false;
13894   SDValue FirstOp;
13895 
13896   // Find first non-undef input.
13897   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
13898     FirstOp = Op.getOperand(i);
13899     if (!FirstOp.isUndef())
13900       break;
13901   }
13902 
13903   // All inputs are undef or the same as the first non-undef input.
13904   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
13905     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
13906       return false;
13907   return true;
13908 }
13909 
13910 static SDValue isScalarToVec(SDValue Op) {
13911   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13912     return Op;
13913   if (Op.getOpcode() != ISD::BITCAST)
13914     return SDValue();
13915   Op = Op.getOperand(0);
13916   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13917     return Op;
13918   return SDValue();
13919 }
13920 
13921 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
13922                                             int LHSMaxIdx, int RHSMinIdx,
13923                                             int RHSMaxIdx, int HalfVec) {
13924   for (int i = 0, e = ShuffV.size(); i < e; i++) {
13925     int Idx = ShuffV[i];
13926     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
13927       ShuffV[i] += HalfVec;
13928   }
13929 }
13930 
13931 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
13932 // the original is:
13933 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
13934 // In such a case, just change the shuffle mask to extract the element
13935 // from the permuted index.
13936 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
13937   SDLoc dl(OrigSToV);
13938   EVT VT = OrigSToV.getValueType();
13939   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13940          "Expecting a SCALAR_TO_VECTOR here");
13941   SDValue Input = OrigSToV.getOperand(0);
13942 
13943   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13944     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
13945     SDValue OrigVector = Input.getOperand(0);
13946 
13947     // Can't handle non-const element indices or different vector types
13948     // for the input to the extract and the output of the scalar_to_vector.
13949     if (Idx && VT == OrigVector.getValueType()) {
13950       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
13951       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
13952       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
13953     }
13954   }
13955   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
13956                      OrigSToV.getOperand(0));
13957 }
13958 
13959 // On little endian subtargets, combine shuffles such as:
13960 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
13961 // into:
13962 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
13963 // because the latter can be matched to a single instruction merge.
13964 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
13965 // to put the value into element zero. Adjust the shuffle mask so that the
13966 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
13967 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
13968                                                 SelectionDAG &DAG) const {
13969   SDValue LHS = SVN->getOperand(0);
13970   SDValue RHS = SVN->getOperand(1);
13971   auto Mask = SVN->getMask();
13972   int NumElts = LHS.getValueType().getVectorNumElements();
13973   SDValue Res(SVN, 0);
13974   SDLoc dl(SVN);
13975 
13976   // None of these combines are useful on big endian systems since the ISA
13977   // already has a big endian bias.
13978   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13979     return Res;
13980 
13981   // If this is not a shuffle of a shuffle and the first element comes from
13982   // the second vector, canonicalize to the commuted form. This will make it
13983   // more likely to match one of the single instruction patterns.
13984   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13985       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
13986     std::swap(LHS, RHS);
13987     Res = DAG.getCommutedVectorShuffle(*SVN);
13988     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13989   }
13990 
13991   // Adjust the shuffle mask if either input vector comes from a
13992   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
13993   // form (to prevent the need for a swap).
13994   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
13995   SDValue SToVLHS = isScalarToVec(LHS);
13996   SDValue SToVRHS = isScalarToVec(RHS);
13997   if (SToVLHS || SToVRHS) {
13998     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
13999                             : SToVRHS.getValueType().getVectorNumElements();
14000     int NumEltsOut = ShuffV.size();
14001 
14002     // Initially assume that neither input is permuted. These will be adjusted
14003     // accordingly if either input is.
14004     int LHSMaxIdx = -1;
14005     int RHSMinIdx = -1;
14006     int RHSMaxIdx = -1;
14007     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14008 
14009     // Get the permuted scalar to vector nodes for the source(s) that come from
14010     // ISD::SCALAR_TO_VECTOR.
14011     if (SToVLHS) {
14012       // Set up the values for the shuffle vector fixup.
14013       LHSMaxIdx = NumEltsOut / NumEltsIn;
14014       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14015       if (SToVLHS.getValueType() != LHS.getValueType())
14016         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14017       LHS = SToVLHS;
14018     }
14019     if (SToVRHS) {
14020       RHSMinIdx = NumEltsOut;
14021       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14022       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14023       if (SToVRHS.getValueType() != RHS.getValueType())
14024         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14025       RHS = SToVRHS;
14026     }
14027 
14028     // Fix up the shuffle mask to reflect where the desired element actually is.
14029     // The minimum and maximum indices that correspond to element zero for both
14030     // the LHS and RHS are computed and will control which shuffle mask entries
14031     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14032     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14033     // HalfVec to refer to the corresponding element in the permuted vector.
14034     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14035                                     HalfVec);
14036     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14037 
14038     // We may have simplified away the shuffle. We won't be able to do anything
14039     // further with it here.
14040     if (!isa<ShuffleVectorSDNode>(Res))
14041       return Res;
14042     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14043   }
14044 
14045   // The common case after we commuted the shuffle is that the RHS is a splat
14046   // and we have elements coming in from the splat at indices that are not
14047   // conducive to using a merge.
14048   // Example:
14049   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14050   if (!isSplatBV(RHS))
14051     return Res;
14052 
14053   // We are looking for a mask such that all even elements are from
14054   // one vector and all odd elements from the other.
14055   if (!isAlternatingShuffMask(Mask, NumElts))
14056     return Res;
14057 
14058   // Adjust the mask so we are pulling in the same index from the splat
14059   // as the index from the interesting vector in consecutive elements.
14060   // Example (even elements from first vector):
14061   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14062   if (Mask[0] < NumElts)
14063     for (int i = 1, e = Mask.size(); i < e; i += 2)
14064       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14065   // Example (odd elements from first vector):
14066   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14067   else
14068     for (int i = 0, e = Mask.size(); i < e; i += 2)
14069       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14070 
14071   // If the RHS has undefs, we need to remove them since we may have created
14072   // a shuffle that adds those instead of the splat value.
14073   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14074   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14075 
14076   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14077   return Res;
14078 }
14079 
14080 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14081                                                 LSBaseSDNode *LSBase,
14082                                                 DAGCombinerInfo &DCI) const {
14083   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14084         "Not a reverse memop pattern!");
14085 
14086   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14087     auto Mask = SVN->getMask();
14088     int i = 0;
14089     auto I = Mask.rbegin();
14090     auto E = Mask.rend();
14091 
14092     for (; I != E; ++I) {
14093       if (*I != i)
14094         return false;
14095       i++;
14096     }
14097     return true;
14098   };
14099 
14100   SelectionDAG &DAG = DCI.DAG;
14101   EVT VT = SVN->getValueType(0);
14102 
14103   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14104     return SDValue();
14105 
14106   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14107   // See comment in PPCVSXSwapRemoval.cpp.
14108   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14109   if (!Subtarget.hasP9Vector())
14110     return SDValue();
14111 
14112   if(!IsElementReverse(SVN))
14113     return SDValue();
14114 
14115   if (LSBase->getOpcode() == ISD::LOAD) {
14116     SDLoc dl(SVN);
14117     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14118     return DAG.getMemIntrinsicNode(
14119         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14120         LSBase->getMemoryVT(), LSBase->getMemOperand());
14121   }
14122 
14123   if (LSBase->getOpcode() == ISD::STORE) {
14124     SDLoc dl(LSBase);
14125     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14126                           LSBase->getBasePtr()};
14127     return DAG.getMemIntrinsicNode(
14128         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14129         LSBase->getMemoryVT(), LSBase->getMemOperand());
14130   }
14131 
14132   llvm_unreachable("Expected a load or store node here");
14133 }
14134 
14135 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14136                                              DAGCombinerInfo &DCI) const {
14137   SelectionDAG &DAG = DCI.DAG;
14138   SDLoc dl(N);
14139   switch (N->getOpcode()) {
14140   default: break;
14141   case ISD::ADD:
14142     return combineADD(N, DCI);
14143   case ISD::SHL:
14144     return combineSHL(N, DCI);
14145   case ISD::SRA:
14146     return combineSRA(N, DCI);
14147   case ISD::SRL:
14148     return combineSRL(N, DCI);
14149   case ISD::MUL:
14150     return combineMUL(N, DCI);
14151   case ISD::FMA:
14152   case PPCISD::FNMSUB:
14153     return combineFMALike(N, DCI);
14154   case PPCISD::SHL:
14155     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14156         return N->getOperand(0);
14157     break;
14158   case PPCISD::SRL:
14159     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14160         return N->getOperand(0);
14161     break;
14162   case PPCISD::SRA:
14163     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14164       if (C->isNullValue() ||   //  0 >>s V -> 0.
14165           C->isAllOnesValue())    // -1 >>s V -> -1.
14166         return N->getOperand(0);
14167     }
14168     break;
14169   case ISD::SIGN_EXTEND:
14170   case ISD::ZERO_EXTEND:
14171   case ISD::ANY_EXTEND:
14172     return DAGCombineExtBoolTrunc(N, DCI);
14173   case ISD::TRUNCATE:
14174     return combineTRUNCATE(N, DCI);
14175   case ISD::SETCC:
14176     if (SDValue CSCC = combineSetCC(N, DCI))
14177       return CSCC;
14178     LLVM_FALLTHROUGH;
14179   case ISD::SELECT_CC:
14180     return DAGCombineTruncBoolExt(N, DCI);
14181   case ISD::SINT_TO_FP:
14182   case ISD::UINT_TO_FP:
14183     return combineFPToIntToFP(N, DCI);
14184   case ISD::VECTOR_SHUFFLE:
14185     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14186       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14187       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14188     }
14189     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14190   case ISD::STORE: {
14191 
14192     EVT Op1VT = N->getOperand(1).getValueType();
14193     unsigned Opcode = N->getOperand(1).getOpcode();
14194 
14195     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14196       SDValue Val= combineStoreFPToInt(N, DCI);
14197       if (Val)
14198         return Val;
14199     }
14200 
14201     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14202       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14203       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14204       if (Val)
14205         return Val;
14206     }
14207 
14208     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14209     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14210         N->getOperand(1).getNode()->hasOneUse() &&
14211         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14212          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14213 
14214       // STBRX can only handle simple types and it makes no sense to store less
14215       // two bytes in byte-reversed order.
14216       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14217       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14218         break;
14219 
14220       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14221       // Do an any-extend to 32-bits if this is a half-word input.
14222       if (BSwapOp.getValueType() == MVT::i16)
14223         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14224 
14225       // If the type of BSWAP operand is wider than stored memory width
14226       // it need to be shifted to the right side before STBRX.
14227       if (Op1VT.bitsGT(mVT)) {
14228         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14229         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14230                               DAG.getConstant(Shift, dl, MVT::i32));
14231         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14232         if (Op1VT == MVT::i64)
14233           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14234       }
14235 
14236       SDValue Ops[] = {
14237         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14238       };
14239       return
14240         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14241                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14242                                 cast<StoreSDNode>(N)->getMemOperand());
14243     }
14244 
14245     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14246     // So it can increase the chance of CSE constant construction.
14247     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14248         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14249       // Need to sign-extended to 64-bits to handle negative values.
14250       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14251       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14252                                     MemVT.getSizeInBits());
14253       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14254 
14255       // DAG.getTruncStore() can't be used here because it doesn't accept
14256       // the general (base + offset) addressing mode.
14257       // So we use UpdateNodeOperands and setTruncatingStore instead.
14258       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14259                              N->getOperand(3));
14260       cast<StoreSDNode>(N)->setTruncatingStore(true);
14261       return SDValue(N, 0);
14262     }
14263 
14264     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14265     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14266     if (Op1VT.isSimple()) {
14267       MVT StoreVT = Op1VT.getSimpleVT();
14268       if (Subtarget.needsSwapsForVSXMemOps() &&
14269           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14270            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14271         return expandVSXStoreForLE(N, DCI);
14272     }
14273     break;
14274   }
14275   case ISD::LOAD: {
14276     LoadSDNode *LD = cast<LoadSDNode>(N);
14277     EVT VT = LD->getValueType(0);
14278 
14279     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14280     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14281     if (VT.isSimple()) {
14282       MVT LoadVT = VT.getSimpleVT();
14283       if (Subtarget.needsSwapsForVSXMemOps() &&
14284           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14285            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14286         return expandVSXLoadForLE(N, DCI);
14287     }
14288 
14289     // We sometimes end up with a 64-bit integer load, from which we extract
14290     // two single-precision floating-point numbers. This happens with
14291     // std::complex<float>, and other similar structures, because of the way we
14292     // canonicalize structure copies. However, if we lack direct moves,
14293     // then the final bitcasts from the extracted integer values to the
14294     // floating-point numbers turn into store/load pairs. Even with direct moves,
14295     // just loading the two floating-point numbers is likely better.
14296     auto ReplaceTwoFloatLoad = [&]() {
14297       if (VT != MVT::i64)
14298         return false;
14299 
14300       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14301           LD->isVolatile())
14302         return false;
14303 
14304       //  We're looking for a sequence like this:
14305       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14306       //      t16: i64 = srl t13, Constant:i32<32>
14307       //    t17: i32 = truncate t16
14308       //  t18: f32 = bitcast t17
14309       //    t19: i32 = truncate t13
14310       //  t20: f32 = bitcast t19
14311 
14312       if (!LD->hasNUsesOfValue(2, 0))
14313         return false;
14314 
14315       auto UI = LD->use_begin();
14316       while (UI.getUse().getResNo() != 0) ++UI;
14317       SDNode *Trunc = *UI++;
14318       while (UI.getUse().getResNo() != 0) ++UI;
14319       SDNode *RightShift = *UI;
14320       if (Trunc->getOpcode() != ISD::TRUNCATE)
14321         std::swap(Trunc, RightShift);
14322 
14323       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14324           Trunc->getValueType(0) != MVT::i32 ||
14325           !Trunc->hasOneUse())
14326         return false;
14327       if (RightShift->getOpcode() != ISD::SRL ||
14328           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14329           RightShift->getConstantOperandVal(1) != 32 ||
14330           !RightShift->hasOneUse())
14331         return false;
14332 
14333       SDNode *Trunc2 = *RightShift->use_begin();
14334       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14335           Trunc2->getValueType(0) != MVT::i32 ||
14336           !Trunc2->hasOneUse())
14337         return false;
14338 
14339       SDNode *Bitcast = *Trunc->use_begin();
14340       SDNode *Bitcast2 = *Trunc2->use_begin();
14341 
14342       if (Bitcast->getOpcode() != ISD::BITCAST ||
14343           Bitcast->getValueType(0) != MVT::f32)
14344         return false;
14345       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14346           Bitcast2->getValueType(0) != MVT::f32)
14347         return false;
14348 
14349       if (Subtarget.isLittleEndian())
14350         std::swap(Bitcast, Bitcast2);
14351 
14352       // Bitcast has the second float (in memory-layout order) and Bitcast2
14353       // has the first one.
14354 
14355       SDValue BasePtr = LD->getBasePtr();
14356       if (LD->isIndexed()) {
14357         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14358                "Non-pre-inc AM on PPC?");
14359         BasePtr =
14360           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14361                       LD->getOffset());
14362       }
14363 
14364       auto MMOFlags =
14365           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14366       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14367                                       LD->getPointerInfo(), LD->getAlignment(),
14368                                       MMOFlags, LD->getAAInfo());
14369       SDValue AddPtr =
14370         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14371                     BasePtr, DAG.getIntPtrConstant(4, dl));
14372       SDValue FloatLoad2 = DAG.getLoad(
14373           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14374           LD->getPointerInfo().getWithOffset(4),
14375           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14376 
14377       if (LD->isIndexed()) {
14378         // Note that DAGCombine should re-form any pre-increment load(s) from
14379         // what is produced here if that makes sense.
14380         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14381       }
14382 
14383       DCI.CombineTo(Bitcast2, FloatLoad);
14384       DCI.CombineTo(Bitcast, FloatLoad2);
14385 
14386       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14387                                     SDValue(FloatLoad2.getNode(), 1));
14388       return true;
14389     };
14390 
14391     if (ReplaceTwoFloatLoad())
14392       return SDValue(N, 0);
14393 
14394     EVT MemVT = LD->getMemoryVT();
14395     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14396     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14397     if (LD->isUnindexed() && VT.isVector() &&
14398         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14399           // P8 and later hardware should just use LOAD.
14400           !Subtarget.hasP8Vector() &&
14401           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14402            VT == MVT::v4f32))) &&
14403         LD->getAlign() < ABIAlignment) {
14404       // This is a type-legal unaligned Altivec load.
14405       SDValue Chain = LD->getChain();
14406       SDValue Ptr = LD->getBasePtr();
14407       bool isLittleEndian = Subtarget.isLittleEndian();
14408 
14409       // This implements the loading of unaligned vectors as described in
14410       // the venerable Apple Velocity Engine overview. Specifically:
14411       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14412       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14413       //
14414       // The general idea is to expand a sequence of one or more unaligned
14415       // loads into an alignment-based permutation-control instruction (lvsl
14416       // or lvsr), a series of regular vector loads (which always truncate
14417       // their input address to an aligned address), and a series of
14418       // permutations.  The results of these permutations are the requested
14419       // loaded values.  The trick is that the last "extra" load is not taken
14420       // from the address you might suspect (sizeof(vector) bytes after the
14421       // last requested load), but rather sizeof(vector) - 1 bytes after the
14422       // last requested vector. The point of this is to avoid a page fault if
14423       // the base address happened to be aligned. This works because if the
14424       // base address is aligned, then adding less than a full vector length
14425       // will cause the last vector in the sequence to be (re)loaded.
14426       // Otherwise, the next vector will be fetched as you might suspect was
14427       // necessary.
14428 
14429       // We might be able to reuse the permutation generation from
14430       // a different base address offset from this one by an aligned amount.
14431       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14432       // optimization later.
14433       Intrinsic::ID Intr, IntrLD, IntrPerm;
14434       MVT PermCntlTy, PermTy, LDTy;
14435       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14436                             : Intrinsic::ppc_altivec_lvsl;
14437       IntrLD = Intrinsic::ppc_altivec_lvx;
14438       IntrPerm = Intrinsic::ppc_altivec_vperm;
14439       PermCntlTy = MVT::v16i8;
14440       PermTy = MVT::v4i32;
14441       LDTy = MVT::v4i32;
14442 
14443       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14444 
14445       // Create the new MMO for the new base load. It is like the original MMO,
14446       // but represents an area in memory almost twice the vector size centered
14447       // on the original address. If the address is unaligned, we might start
14448       // reading up to (sizeof(vector)-1) bytes below the address of the
14449       // original unaligned load.
14450       MachineFunction &MF = DAG.getMachineFunction();
14451       MachineMemOperand *BaseMMO =
14452         MF.getMachineMemOperand(LD->getMemOperand(),
14453                                 -(long)MemVT.getStoreSize()+1,
14454                                 2*MemVT.getStoreSize()-1);
14455 
14456       // Create the new base load.
14457       SDValue LDXIntID =
14458           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14459       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14460       SDValue BaseLoad =
14461         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14462                                 DAG.getVTList(PermTy, MVT::Other),
14463                                 BaseLoadOps, LDTy, BaseMMO);
14464 
14465       // Note that the value of IncOffset (which is provided to the next
14466       // load's pointer info offset value, and thus used to calculate the
14467       // alignment), and the value of IncValue (which is actually used to
14468       // increment the pointer value) are different! This is because we
14469       // require the next load to appear to be aligned, even though it
14470       // is actually offset from the base pointer by a lesser amount.
14471       int IncOffset = VT.getSizeInBits() / 8;
14472       int IncValue = IncOffset;
14473 
14474       // Walk (both up and down) the chain looking for another load at the real
14475       // (aligned) offset (the alignment of the other load does not matter in
14476       // this case). If found, then do not use the offset reduction trick, as
14477       // that will prevent the loads from being later combined (as they would
14478       // otherwise be duplicates).
14479       if (!findConsecutiveLoad(LD, DAG))
14480         --IncValue;
14481 
14482       SDValue Increment =
14483           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14484       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14485 
14486       MachineMemOperand *ExtraMMO =
14487         MF.getMachineMemOperand(LD->getMemOperand(),
14488                                 1, 2*MemVT.getStoreSize()-1);
14489       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14490       SDValue ExtraLoad =
14491         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14492                                 DAG.getVTList(PermTy, MVT::Other),
14493                                 ExtraLoadOps, LDTy, ExtraMMO);
14494 
14495       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14496         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14497 
14498       // Because vperm has a big-endian bias, we must reverse the order
14499       // of the input vectors and complement the permute control vector
14500       // when generating little endian code.  We have already handled the
14501       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14502       // and ExtraLoad here.
14503       SDValue Perm;
14504       if (isLittleEndian)
14505         Perm = BuildIntrinsicOp(IntrPerm,
14506                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14507       else
14508         Perm = BuildIntrinsicOp(IntrPerm,
14509                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14510 
14511       if (VT != PermTy)
14512         Perm = Subtarget.hasAltivec()
14513                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14514                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14515                                  DAG.getTargetConstant(1, dl, MVT::i64));
14516                                // second argument is 1 because this rounding
14517                                // is always exact.
14518 
14519       // The output of the permutation is our loaded result, the TokenFactor is
14520       // our new chain.
14521       DCI.CombineTo(N, Perm, TF);
14522       return SDValue(N, 0);
14523     }
14524     }
14525     break;
14526     case ISD::INTRINSIC_WO_CHAIN: {
14527       bool isLittleEndian = Subtarget.isLittleEndian();
14528       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14529       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14530                                            : Intrinsic::ppc_altivec_lvsl);
14531       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14532         SDValue Add = N->getOperand(1);
14533 
14534         int Bits = 4 /* 16 byte alignment */;
14535 
14536         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14537                                   APInt::getAllOnesValue(Bits /* alignment */)
14538                                       .zext(Add.getScalarValueSizeInBits()))) {
14539           SDNode *BasePtr = Add->getOperand(0).getNode();
14540           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14541                                     UE = BasePtr->use_end();
14542                UI != UE; ++UI) {
14543             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14544                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14545                     IID) {
14546               // We've found another LVSL/LVSR, and this address is an aligned
14547               // multiple of that one. The results will be the same, so use the
14548               // one we've just found instead.
14549 
14550               return SDValue(*UI, 0);
14551             }
14552           }
14553         }
14554 
14555         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14556           SDNode *BasePtr = Add->getOperand(0).getNode();
14557           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14558                UE = BasePtr->use_end(); UI != UE; ++UI) {
14559             if (UI->getOpcode() == ISD::ADD &&
14560                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14561                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14562                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14563                 (1ULL << Bits) == 0) {
14564               SDNode *OtherAdd = *UI;
14565               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14566                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14567                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14568                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14569                   return SDValue(*VI, 0);
14570                 }
14571               }
14572             }
14573           }
14574         }
14575       }
14576 
14577       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14578       // Expose the vabsduw/h/b opportunity for down stream
14579       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14580           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14581            IID == Intrinsic::ppc_altivec_vmaxsh ||
14582            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14583         SDValue V1 = N->getOperand(1);
14584         SDValue V2 = N->getOperand(2);
14585         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14586              V1.getSimpleValueType() == MVT::v8i16 ||
14587              V1.getSimpleValueType() == MVT::v16i8) &&
14588             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14589           // (0-a, a)
14590           if (V1.getOpcode() == ISD::SUB &&
14591               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14592               V1.getOperand(1) == V2) {
14593             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14594           }
14595           // (a, 0-a)
14596           if (V2.getOpcode() == ISD::SUB &&
14597               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14598               V2.getOperand(1) == V1) {
14599             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14600           }
14601           // (x-y, y-x)
14602           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14603               V1.getOperand(0) == V2.getOperand(1) &&
14604               V1.getOperand(1) == V2.getOperand(0)) {
14605             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14606           }
14607         }
14608       }
14609     }
14610 
14611     break;
14612   case ISD::INTRINSIC_W_CHAIN:
14613     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14614     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14615     if (Subtarget.needsSwapsForVSXMemOps()) {
14616       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14617       default:
14618         break;
14619       case Intrinsic::ppc_vsx_lxvw4x:
14620       case Intrinsic::ppc_vsx_lxvd2x:
14621         return expandVSXLoadForLE(N, DCI);
14622       }
14623     }
14624     break;
14625   case ISD::INTRINSIC_VOID:
14626     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14627     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14628     if (Subtarget.needsSwapsForVSXMemOps()) {
14629       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14630       default:
14631         break;
14632       case Intrinsic::ppc_vsx_stxvw4x:
14633       case Intrinsic::ppc_vsx_stxvd2x:
14634         return expandVSXStoreForLE(N, DCI);
14635       }
14636     }
14637     break;
14638   case ISD::BSWAP:
14639     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14640     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14641         N->getOperand(0).hasOneUse() &&
14642         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14643          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14644           N->getValueType(0) == MVT::i64))) {
14645       SDValue Load = N->getOperand(0);
14646       LoadSDNode *LD = cast<LoadSDNode>(Load);
14647       // Create the byte-swapping load.
14648       SDValue Ops[] = {
14649         LD->getChain(),    // Chain
14650         LD->getBasePtr(),  // Ptr
14651         DAG.getValueType(N->getValueType(0)) // VT
14652       };
14653       SDValue BSLoad =
14654         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14655                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14656                                               MVT::i64 : MVT::i32, MVT::Other),
14657                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14658 
14659       // If this is an i16 load, insert the truncate.
14660       SDValue ResVal = BSLoad;
14661       if (N->getValueType(0) == MVT::i16)
14662         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14663 
14664       // First, combine the bswap away.  This makes the value produced by the
14665       // load dead.
14666       DCI.CombineTo(N, ResVal);
14667 
14668       // Next, combine the load away, we give it a bogus result value but a real
14669       // chain result.  The result value is dead because the bswap is dead.
14670       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14671 
14672       // Return N so it doesn't get rechecked!
14673       return SDValue(N, 0);
14674     }
14675     break;
14676   case PPCISD::VCMP:
14677     // If a VCMP_rec node already exists with exactly the same operands as this
14678     // node, use its result instead of this node (VCMP_rec computes both a CR6
14679     // and a normal output).
14680     //
14681     if (!N->getOperand(0).hasOneUse() &&
14682         !N->getOperand(1).hasOneUse() &&
14683         !N->getOperand(2).hasOneUse()) {
14684 
14685       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
14686       SDNode *VCMPrecNode = nullptr;
14687 
14688       SDNode *LHSN = N->getOperand(0).getNode();
14689       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14690            UI != E; ++UI)
14691         if (UI->getOpcode() == PPCISD::VCMP_rec &&
14692             UI->getOperand(1) == N->getOperand(1) &&
14693             UI->getOperand(2) == N->getOperand(2) &&
14694             UI->getOperand(0) == N->getOperand(0)) {
14695           VCMPrecNode = *UI;
14696           break;
14697         }
14698 
14699       // If there is no VCMP_rec node, or if the flag value has a single use,
14700       // don't transform this.
14701       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
14702         break;
14703 
14704       // Look at the (necessarily single) use of the flag value.  If it has a
14705       // chain, this transformation is more complex.  Note that multiple things
14706       // could use the value result, which we should ignore.
14707       SDNode *FlagUser = nullptr;
14708       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
14709            FlagUser == nullptr; ++UI) {
14710         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
14711         SDNode *User = *UI;
14712         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14713           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
14714             FlagUser = User;
14715             break;
14716           }
14717         }
14718       }
14719 
14720       // If the user is a MFOCRF instruction, we know this is safe.
14721       // Otherwise we give up for right now.
14722       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14723         return SDValue(VCMPrecNode, 0);
14724     }
14725     break;
14726   case ISD::BRCOND: {
14727     SDValue Cond = N->getOperand(1);
14728     SDValue Target = N->getOperand(2);
14729 
14730     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14731         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14732           Intrinsic::loop_decrement) {
14733 
14734       // We now need to make the intrinsic dead (it cannot be instruction
14735       // selected).
14736       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14737       assert(Cond.getNode()->hasOneUse() &&
14738              "Counter decrement has more than one use");
14739 
14740       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14741                          N->getOperand(0), Target);
14742     }
14743   }
14744   break;
14745   case ISD::BR_CC: {
14746     // If this is a branch on an altivec predicate comparison, lower this so
14747     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14748     // lowering is done pre-legalize, because the legalizer lowers the predicate
14749     // compare down to code that is difficult to reassemble.
14750     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14751     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14752 
14753     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14754     // value. If so, pass-through the AND to get to the intrinsic.
14755     if (LHS.getOpcode() == ISD::AND &&
14756         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14757         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14758           Intrinsic::loop_decrement &&
14759         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14760         !isNullConstant(LHS.getOperand(1)))
14761       LHS = LHS.getOperand(0);
14762 
14763     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14764         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14765           Intrinsic::loop_decrement &&
14766         isa<ConstantSDNode>(RHS)) {
14767       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14768              "Counter decrement comparison is not EQ or NE");
14769 
14770       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14771       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14772                     (CC == ISD::SETNE && !Val);
14773 
14774       // We now need to make the intrinsic dead (it cannot be instruction
14775       // selected).
14776       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14777       assert(LHS.getNode()->hasOneUse() &&
14778              "Counter decrement has more than one use");
14779 
14780       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14781                          N->getOperand(0), N->getOperand(4));
14782     }
14783 
14784     int CompareOpc;
14785     bool isDot;
14786 
14787     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14788         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14789         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14790       assert(isDot && "Can't compare against a vector result!");
14791 
14792       // If this is a comparison against something other than 0/1, then we know
14793       // that the condition is never/always true.
14794       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14795       if (Val != 0 && Val != 1) {
14796         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14797           return N->getOperand(0);
14798         // Always !=, turn it into an unconditional branch.
14799         return DAG.getNode(ISD::BR, dl, MVT::Other,
14800                            N->getOperand(0), N->getOperand(4));
14801       }
14802 
14803       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14804 
14805       // Create the PPCISD altivec 'dot' comparison node.
14806       SDValue Ops[] = {
14807         LHS.getOperand(2),  // LHS of compare
14808         LHS.getOperand(3),  // RHS of compare
14809         DAG.getConstant(CompareOpc, dl, MVT::i32)
14810       };
14811       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14812       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
14813 
14814       // Unpack the result based on how the target uses it.
14815       PPC::Predicate CompOpc;
14816       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14817       default:  // Can't happen, don't crash on invalid number though.
14818       case 0:   // Branch on the value of the EQ bit of CR6.
14819         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14820         break;
14821       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14822         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14823         break;
14824       case 2:   // Branch on the value of the LT bit of CR6.
14825         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14826         break;
14827       case 3:   // Branch on the inverted value of the LT bit of CR6.
14828         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14829         break;
14830       }
14831 
14832       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14833                          DAG.getConstant(CompOpc, dl, MVT::i32),
14834                          DAG.getRegister(PPC::CR6, MVT::i32),
14835                          N->getOperand(4), CompNode.getValue(1));
14836     }
14837     break;
14838   }
14839   case ISD::BUILD_VECTOR:
14840     return DAGCombineBuildVector(N, DCI);
14841   case ISD::ABS:
14842     return combineABS(N, DCI);
14843   case ISD::VSELECT:
14844     return combineVSelect(N, DCI);
14845   }
14846 
14847   return SDValue();
14848 }
14849 
14850 SDValue
14851 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14852                                  SelectionDAG &DAG,
14853                                  SmallVectorImpl<SDNode *> &Created) const {
14854   // fold (sdiv X, pow2)
14855   EVT VT = N->getValueType(0);
14856   if (VT == MVT::i64 && !Subtarget.isPPC64())
14857     return SDValue();
14858   if ((VT != MVT::i32 && VT != MVT::i64) ||
14859       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14860     return SDValue();
14861 
14862   SDLoc DL(N);
14863   SDValue N0 = N->getOperand(0);
14864 
14865   bool IsNegPow2 = (-Divisor).isPowerOf2();
14866   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14867   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14868 
14869   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14870   Created.push_back(Op.getNode());
14871 
14872   if (IsNegPow2) {
14873     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14874     Created.push_back(Op.getNode());
14875   }
14876 
14877   return Op;
14878 }
14879 
14880 //===----------------------------------------------------------------------===//
14881 // Inline Assembly Support
14882 //===----------------------------------------------------------------------===//
14883 
14884 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14885                                                       KnownBits &Known,
14886                                                       const APInt &DemandedElts,
14887                                                       const SelectionDAG &DAG,
14888                                                       unsigned Depth) const {
14889   Known.resetAll();
14890   switch (Op.getOpcode()) {
14891   default: break;
14892   case PPCISD::LBRX: {
14893     // lhbrx is known to have the top bits cleared out.
14894     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14895       Known.Zero = 0xFFFF0000;
14896     break;
14897   }
14898   case ISD::INTRINSIC_WO_CHAIN: {
14899     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14900     default: break;
14901     case Intrinsic::ppc_altivec_vcmpbfp_p:
14902     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14903     case Intrinsic::ppc_altivec_vcmpequb_p:
14904     case Intrinsic::ppc_altivec_vcmpequh_p:
14905     case Intrinsic::ppc_altivec_vcmpequw_p:
14906     case Intrinsic::ppc_altivec_vcmpequd_p:
14907     case Intrinsic::ppc_altivec_vcmpequq_p:
14908     case Intrinsic::ppc_altivec_vcmpgefp_p:
14909     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14910     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14911     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14912     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14913     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14914     case Intrinsic::ppc_altivec_vcmpgtsq_p:
14915     case Intrinsic::ppc_altivec_vcmpgtub_p:
14916     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14917     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14918     case Intrinsic::ppc_altivec_vcmpgtud_p:
14919     case Intrinsic::ppc_altivec_vcmpgtuq_p:
14920       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14921       break;
14922     }
14923   }
14924   }
14925 }
14926 
14927 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14928   switch (Subtarget.getCPUDirective()) {
14929   default: break;
14930   case PPC::DIR_970:
14931   case PPC::DIR_PWR4:
14932   case PPC::DIR_PWR5:
14933   case PPC::DIR_PWR5X:
14934   case PPC::DIR_PWR6:
14935   case PPC::DIR_PWR6X:
14936   case PPC::DIR_PWR7:
14937   case PPC::DIR_PWR8:
14938   case PPC::DIR_PWR9:
14939   case PPC::DIR_PWR10:
14940   case PPC::DIR_PWR_FUTURE: {
14941     if (!ML)
14942       break;
14943 
14944     if (!DisableInnermostLoopAlign32) {
14945       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14946       // so that we can decrease cache misses and branch-prediction misses.
14947       // Actual alignment of the loop will depend on the hotness check and other
14948       // logic in alignBlocks.
14949       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14950         return Align(32);
14951     }
14952 
14953     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14954 
14955     // For small loops (between 5 and 8 instructions), align to a 32-byte
14956     // boundary so that the entire loop fits in one instruction-cache line.
14957     uint64_t LoopSize = 0;
14958     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14959       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14960         LoopSize += TII->getInstSizeInBytes(*J);
14961         if (LoopSize > 32)
14962           break;
14963       }
14964 
14965     if (LoopSize > 16 && LoopSize <= 32)
14966       return Align(32);
14967 
14968     break;
14969   }
14970   }
14971 
14972   return TargetLowering::getPrefLoopAlignment(ML);
14973 }
14974 
14975 /// getConstraintType - Given a constraint, return the type of
14976 /// constraint it is for this target.
14977 PPCTargetLowering::ConstraintType
14978 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14979   if (Constraint.size() == 1) {
14980     switch (Constraint[0]) {
14981     default: break;
14982     case 'b':
14983     case 'r':
14984     case 'f':
14985     case 'd':
14986     case 'v':
14987     case 'y':
14988       return C_RegisterClass;
14989     case 'Z':
14990       // FIXME: While Z does indicate a memory constraint, it specifically
14991       // indicates an r+r address (used in conjunction with the 'y' modifier
14992       // in the replacement string). Currently, we're forcing the base
14993       // register to be r0 in the asm printer (which is interpreted as zero)
14994       // and forming the complete address in the second register. This is
14995       // suboptimal.
14996       return C_Memory;
14997     }
14998   } else if (Constraint == "wc") { // individual CR bits.
14999     return C_RegisterClass;
15000   } else if (Constraint == "wa" || Constraint == "wd" ||
15001              Constraint == "wf" || Constraint == "ws" ||
15002              Constraint == "wi" || Constraint == "ww") {
15003     return C_RegisterClass; // VSX registers.
15004   }
15005   return TargetLowering::getConstraintType(Constraint);
15006 }
15007 
15008 /// Examine constraint type and operand type and determine a weight value.
15009 /// This object must already have been set up with the operand type
15010 /// and the current alternative constraint selected.
15011 TargetLowering::ConstraintWeight
15012 PPCTargetLowering::getSingleConstraintMatchWeight(
15013     AsmOperandInfo &info, const char *constraint) const {
15014   ConstraintWeight weight = CW_Invalid;
15015   Value *CallOperandVal = info.CallOperandVal;
15016     // If we don't have a value, we can't do a match,
15017     // but allow it at the lowest weight.
15018   if (!CallOperandVal)
15019     return CW_Default;
15020   Type *type = CallOperandVal->getType();
15021 
15022   // Look at the constraint type.
15023   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15024     return CW_Register; // an individual CR bit.
15025   else if ((StringRef(constraint) == "wa" ||
15026             StringRef(constraint) == "wd" ||
15027             StringRef(constraint) == "wf") &&
15028            type->isVectorTy())
15029     return CW_Register;
15030   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15031     return CW_Register; // just hold 64-bit integers data.
15032   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15033     return CW_Register;
15034   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15035     return CW_Register;
15036 
15037   switch (*constraint) {
15038   default:
15039     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15040     break;
15041   case 'b':
15042     if (type->isIntegerTy())
15043       weight = CW_Register;
15044     break;
15045   case 'f':
15046     if (type->isFloatTy())
15047       weight = CW_Register;
15048     break;
15049   case 'd':
15050     if (type->isDoubleTy())
15051       weight = CW_Register;
15052     break;
15053   case 'v':
15054     if (type->isVectorTy())
15055       weight = CW_Register;
15056     break;
15057   case 'y':
15058     weight = CW_Register;
15059     break;
15060   case 'Z':
15061     weight = CW_Memory;
15062     break;
15063   }
15064   return weight;
15065 }
15066 
15067 std::pair<unsigned, const TargetRegisterClass *>
15068 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15069                                                 StringRef Constraint,
15070                                                 MVT VT) const {
15071   if (Constraint.size() == 1) {
15072     // GCC RS6000 Constraint Letters
15073     switch (Constraint[0]) {
15074     case 'b':   // R1-R31
15075       if (VT == MVT::i64 && Subtarget.isPPC64())
15076         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15077       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15078     case 'r':   // R0-R31
15079       if (VT == MVT::i64 && Subtarget.isPPC64())
15080         return std::make_pair(0U, &PPC::G8RCRegClass);
15081       return std::make_pair(0U, &PPC::GPRCRegClass);
15082     // 'd' and 'f' constraints are both defined to be "the floating point
15083     // registers", where one is for 32-bit and the other for 64-bit. We don't
15084     // really care overly much here so just give them all the same reg classes.
15085     case 'd':
15086     case 'f':
15087       if (Subtarget.hasSPE()) {
15088         if (VT == MVT::f32 || VT == MVT::i32)
15089           return std::make_pair(0U, &PPC::GPRCRegClass);
15090         if (VT == MVT::f64 || VT == MVT::i64)
15091           return std::make_pair(0U, &PPC::SPERCRegClass);
15092       } else {
15093         if (VT == MVT::f32 || VT == MVT::i32)
15094           return std::make_pair(0U, &PPC::F4RCRegClass);
15095         if (VT == MVT::f64 || VT == MVT::i64)
15096           return std::make_pair(0U, &PPC::F8RCRegClass);
15097       }
15098       break;
15099     case 'v':
15100       if (Subtarget.hasAltivec())
15101         return std::make_pair(0U, &PPC::VRRCRegClass);
15102       break;
15103     case 'y':   // crrc
15104       return std::make_pair(0U, &PPC::CRRCRegClass);
15105     }
15106   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15107     // An individual CR bit.
15108     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15109   } else if ((Constraint == "wa" || Constraint == "wd" ||
15110              Constraint == "wf" || Constraint == "wi") &&
15111              Subtarget.hasVSX()) {
15112     return std::make_pair(0U, &PPC::VSRCRegClass);
15113   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15114     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15115       return std::make_pair(0U, &PPC::VSSRCRegClass);
15116     else
15117       return std::make_pair(0U, &PPC::VSFRCRegClass);
15118   }
15119 
15120   // Handle special cases of physical registers that are not properly handled
15121   // by the base class.
15122   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
15123     // If we name a VSX register, we can't defer to the base class because it
15124     // will not recognize the correct register (their names will be VSL{0-31}
15125     // and V{0-31} so they won't match). So we match them here.
15126     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15127       int VSNum = atoi(Constraint.data() + 3);
15128       assert(VSNum >= 0 && VSNum <= 63 &&
15129              "Attempted to access a vsr out of range");
15130       if (VSNum < 32)
15131         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15132       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15133     }
15134 
15135     // For float registers, we can't defer to the base class as it will match
15136     // the SPILLTOVSRRC class.
15137     if (Constraint.size() > 3 && Constraint[1] == 'f') {
15138       int RegNum = atoi(Constraint.data() + 2);
15139       if (RegNum > 31 || RegNum < 0)
15140         report_fatal_error("Invalid floating point register number");
15141       if (VT == MVT::f32 || VT == MVT::i32)
15142         return Subtarget.hasSPE()
15143                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
15144                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
15145       if (VT == MVT::f64 || VT == MVT::i64)
15146         return Subtarget.hasSPE()
15147                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
15148                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
15149     }
15150   }
15151 
15152   std::pair<unsigned, const TargetRegisterClass *> R =
15153       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15154 
15155   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15156   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15157   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15158   // register.
15159   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15160   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15161   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15162       PPC::GPRCRegClass.contains(R.first))
15163     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15164                             PPC::sub_32, &PPC::G8RCRegClass),
15165                           &PPC::G8RCRegClass);
15166 
15167   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15168   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15169     R.first = PPC::CR0;
15170     R.second = &PPC::CRRCRegClass;
15171   }
15172 
15173   return R;
15174 }
15175 
15176 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15177 /// vector.  If it is invalid, don't add anything to Ops.
15178 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15179                                                      std::string &Constraint,
15180                                                      std::vector<SDValue>&Ops,
15181                                                      SelectionDAG &DAG) const {
15182   SDValue Result;
15183 
15184   // Only support length 1 constraints.
15185   if (Constraint.length() > 1) return;
15186 
15187   char Letter = Constraint[0];
15188   switch (Letter) {
15189   default: break;
15190   case 'I':
15191   case 'J':
15192   case 'K':
15193   case 'L':
15194   case 'M':
15195   case 'N':
15196   case 'O':
15197   case 'P': {
15198     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15199     if (!CST) return; // Must be an immediate to match.
15200     SDLoc dl(Op);
15201     int64_t Value = CST->getSExtValue();
15202     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15203                          // numbers are printed as such.
15204     switch (Letter) {
15205     default: llvm_unreachable("Unknown constraint letter!");
15206     case 'I':  // "I" is a signed 16-bit constant.
15207       if (isInt<16>(Value))
15208         Result = DAG.getTargetConstant(Value, dl, TCVT);
15209       break;
15210     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15211       if (isShiftedUInt<16, 16>(Value))
15212         Result = DAG.getTargetConstant(Value, dl, TCVT);
15213       break;
15214     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15215       if (isShiftedInt<16, 16>(Value))
15216         Result = DAG.getTargetConstant(Value, dl, TCVT);
15217       break;
15218     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15219       if (isUInt<16>(Value))
15220         Result = DAG.getTargetConstant(Value, dl, TCVT);
15221       break;
15222     case 'M':  // "M" is a constant that is greater than 31.
15223       if (Value > 31)
15224         Result = DAG.getTargetConstant(Value, dl, TCVT);
15225       break;
15226     case 'N':  // "N" is a positive constant that is an exact power of two.
15227       if (Value > 0 && isPowerOf2_64(Value))
15228         Result = DAG.getTargetConstant(Value, dl, TCVT);
15229       break;
15230     case 'O':  // "O" is the constant zero.
15231       if (Value == 0)
15232         Result = DAG.getTargetConstant(Value, dl, TCVT);
15233       break;
15234     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15235       if (isInt<16>(-Value))
15236         Result = DAG.getTargetConstant(Value, dl, TCVT);
15237       break;
15238     }
15239     break;
15240   }
15241   }
15242 
15243   if (Result.getNode()) {
15244     Ops.push_back(Result);
15245     return;
15246   }
15247 
15248   // Handle standard constraint letters.
15249   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15250 }
15251 
15252 // isLegalAddressingMode - Return true if the addressing mode represented
15253 // by AM is legal for this target, for a load/store of the specified type.
15254 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15255                                               const AddrMode &AM, Type *Ty,
15256                                               unsigned AS,
15257                                               Instruction *I) const {
15258   // Vector type r+i form is supported since power9 as DQ form. We don't check
15259   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15260   // imm form is preferred and the offset can be adjusted to use imm form later
15261   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15262   // max offset to check legal addressing mode, we should be a little aggressive
15263   // to contain other offsets for that LSRUse.
15264   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15265     return false;
15266 
15267   // PPC allows a sign-extended 16-bit immediate field.
15268   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15269     return false;
15270 
15271   // No global is ever allowed as a base.
15272   if (AM.BaseGV)
15273     return false;
15274 
15275   // PPC only support r+r,
15276   switch (AM.Scale) {
15277   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15278     break;
15279   case 1:
15280     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15281       return false;
15282     // Otherwise we have r+r or r+i.
15283     break;
15284   case 2:
15285     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15286       return false;
15287     // Allow 2*r as r+r.
15288     break;
15289   default:
15290     // No other scales are supported.
15291     return false;
15292   }
15293 
15294   return true;
15295 }
15296 
15297 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15298                                            SelectionDAG &DAG) const {
15299   MachineFunction &MF = DAG.getMachineFunction();
15300   MachineFrameInfo &MFI = MF.getFrameInfo();
15301   MFI.setReturnAddressIsTaken(true);
15302 
15303   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15304     return SDValue();
15305 
15306   SDLoc dl(Op);
15307   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15308 
15309   // Make sure the function does not optimize away the store of the RA to
15310   // the stack.
15311   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15312   FuncInfo->setLRStoreRequired();
15313   bool isPPC64 = Subtarget.isPPC64();
15314   auto PtrVT = getPointerTy(MF.getDataLayout());
15315 
15316   if (Depth > 0) {
15317     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15318     SDValue Offset =
15319         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15320                         isPPC64 ? MVT::i64 : MVT::i32);
15321     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15322                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15323                        MachinePointerInfo());
15324   }
15325 
15326   // Just load the return address off the stack.
15327   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15328   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15329                      MachinePointerInfo());
15330 }
15331 
15332 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15333                                           SelectionDAG &DAG) const {
15334   SDLoc dl(Op);
15335   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15336 
15337   MachineFunction &MF = DAG.getMachineFunction();
15338   MachineFrameInfo &MFI = MF.getFrameInfo();
15339   MFI.setFrameAddressIsTaken(true);
15340 
15341   EVT PtrVT = getPointerTy(MF.getDataLayout());
15342   bool isPPC64 = PtrVT == MVT::i64;
15343 
15344   // Naked functions never have a frame pointer, and so we use r1. For all
15345   // other functions, this decision must be delayed until during PEI.
15346   unsigned FrameReg;
15347   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15348     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15349   else
15350     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15351 
15352   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15353                                          PtrVT);
15354   while (Depth--)
15355     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15356                             FrameAddr, MachinePointerInfo());
15357   return FrameAddr;
15358 }
15359 
15360 // FIXME? Maybe this could be a TableGen attribute on some registers and
15361 // this table could be generated automatically from RegInfo.
15362 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15363                                               const MachineFunction &MF) const {
15364   bool isPPC64 = Subtarget.isPPC64();
15365 
15366   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15367   if (!is64Bit && VT != LLT::scalar(32))
15368     report_fatal_error("Invalid register global variable type");
15369 
15370   Register Reg = StringSwitch<Register>(RegName)
15371                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15372                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15373                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15374                      .Default(Register());
15375 
15376   if (Reg)
15377     return Reg;
15378   report_fatal_error("Invalid register name global variable");
15379 }
15380 
15381 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15382   // 32-bit SVR4 ABI access everything as got-indirect.
15383   if (Subtarget.is32BitELFABI())
15384     return true;
15385 
15386   // AIX accesses everything indirectly through the TOC, which is similar to
15387   // the GOT.
15388   if (Subtarget.isAIXABI())
15389     return true;
15390 
15391   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15392   // If it is small or large code model, module locals are accessed
15393   // indirectly by loading their address from .toc/.got.
15394   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15395     return true;
15396 
15397   // JumpTable and BlockAddress are accessed as got-indirect.
15398   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15399     return true;
15400 
15401   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15402     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15403 
15404   return false;
15405 }
15406 
15407 bool
15408 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15409   // The PowerPC target isn't yet aware of offsets.
15410   return false;
15411 }
15412 
15413 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15414                                            const CallInst &I,
15415                                            MachineFunction &MF,
15416                                            unsigned Intrinsic) const {
15417   switch (Intrinsic) {
15418   case Intrinsic::ppc_altivec_lvx:
15419   case Intrinsic::ppc_altivec_lvxl:
15420   case Intrinsic::ppc_altivec_lvebx:
15421   case Intrinsic::ppc_altivec_lvehx:
15422   case Intrinsic::ppc_altivec_lvewx:
15423   case Intrinsic::ppc_vsx_lxvd2x:
15424   case Intrinsic::ppc_vsx_lxvw4x:
15425   case Intrinsic::ppc_vsx_lxvd2x_be:
15426   case Intrinsic::ppc_vsx_lxvw4x_be:
15427   case Intrinsic::ppc_vsx_lxvl:
15428   case Intrinsic::ppc_vsx_lxvll: {
15429     EVT VT;
15430     switch (Intrinsic) {
15431     case Intrinsic::ppc_altivec_lvebx:
15432       VT = MVT::i8;
15433       break;
15434     case Intrinsic::ppc_altivec_lvehx:
15435       VT = MVT::i16;
15436       break;
15437     case Intrinsic::ppc_altivec_lvewx:
15438       VT = MVT::i32;
15439       break;
15440     case Intrinsic::ppc_vsx_lxvd2x:
15441     case Intrinsic::ppc_vsx_lxvd2x_be:
15442       VT = MVT::v2f64;
15443       break;
15444     default:
15445       VT = MVT::v4i32;
15446       break;
15447     }
15448 
15449     Info.opc = ISD::INTRINSIC_W_CHAIN;
15450     Info.memVT = VT;
15451     Info.ptrVal = I.getArgOperand(0);
15452     Info.offset = -VT.getStoreSize()+1;
15453     Info.size = 2*VT.getStoreSize()-1;
15454     Info.align = Align(1);
15455     Info.flags = MachineMemOperand::MOLoad;
15456     return true;
15457   }
15458   case Intrinsic::ppc_altivec_stvx:
15459   case Intrinsic::ppc_altivec_stvxl:
15460   case Intrinsic::ppc_altivec_stvebx:
15461   case Intrinsic::ppc_altivec_stvehx:
15462   case Intrinsic::ppc_altivec_stvewx:
15463   case Intrinsic::ppc_vsx_stxvd2x:
15464   case Intrinsic::ppc_vsx_stxvw4x:
15465   case Intrinsic::ppc_vsx_stxvd2x_be:
15466   case Intrinsic::ppc_vsx_stxvw4x_be:
15467   case Intrinsic::ppc_vsx_stxvl:
15468   case Intrinsic::ppc_vsx_stxvll: {
15469     EVT VT;
15470     switch (Intrinsic) {
15471     case Intrinsic::ppc_altivec_stvebx:
15472       VT = MVT::i8;
15473       break;
15474     case Intrinsic::ppc_altivec_stvehx:
15475       VT = MVT::i16;
15476       break;
15477     case Intrinsic::ppc_altivec_stvewx:
15478       VT = MVT::i32;
15479       break;
15480     case Intrinsic::ppc_vsx_stxvd2x:
15481     case Intrinsic::ppc_vsx_stxvd2x_be:
15482       VT = MVT::v2f64;
15483       break;
15484     default:
15485       VT = MVT::v4i32;
15486       break;
15487     }
15488 
15489     Info.opc = ISD::INTRINSIC_VOID;
15490     Info.memVT = VT;
15491     Info.ptrVal = I.getArgOperand(1);
15492     Info.offset = -VT.getStoreSize()+1;
15493     Info.size = 2*VT.getStoreSize()-1;
15494     Info.align = Align(1);
15495     Info.flags = MachineMemOperand::MOStore;
15496     return true;
15497   }
15498   default:
15499     break;
15500   }
15501 
15502   return false;
15503 }
15504 
15505 /// It returns EVT::Other if the type should be determined using generic
15506 /// target-independent logic.
15507 EVT PPCTargetLowering::getOptimalMemOpType(
15508     const MemOp &Op, const AttributeList &FuncAttributes) const {
15509   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15510     // We should use Altivec/VSX loads and stores when available. For unaligned
15511     // addresses, unaligned VSX loads are only fast starting with the P8.
15512     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15513         (Op.isAligned(Align(16)) ||
15514          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15515       return MVT::v4i32;
15516   }
15517 
15518   if (Subtarget.isPPC64()) {
15519     return MVT::i64;
15520   }
15521 
15522   return MVT::i32;
15523 }
15524 
15525 /// Returns true if it is beneficial to convert a load of a constant
15526 /// to just the constant itself.
15527 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15528                                                           Type *Ty) const {
15529   assert(Ty->isIntegerTy());
15530 
15531   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15532   return !(BitSize == 0 || BitSize > 64);
15533 }
15534 
15535 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15536   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15537     return false;
15538   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15539   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15540   return NumBits1 == 64 && NumBits2 == 32;
15541 }
15542 
15543 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15544   if (!VT1.isInteger() || !VT2.isInteger())
15545     return false;
15546   unsigned NumBits1 = VT1.getSizeInBits();
15547   unsigned NumBits2 = VT2.getSizeInBits();
15548   return NumBits1 == 64 && NumBits2 == 32;
15549 }
15550 
15551 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15552   // Generally speaking, zexts are not free, but they are free when they can be
15553   // folded with other operations.
15554   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15555     EVT MemVT = LD->getMemoryVT();
15556     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15557          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15558         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15559          LD->getExtensionType() == ISD::ZEXTLOAD))
15560       return true;
15561   }
15562 
15563   // FIXME: Add other cases...
15564   //  - 32-bit shifts with a zext to i64
15565   //  - zext after ctlz, bswap, etc.
15566   //  - zext after and by a constant mask
15567 
15568   return TargetLowering::isZExtFree(Val, VT2);
15569 }
15570 
15571 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15572   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15573          "invalid fpext types");
15574   // Extending to float128 is not free.
15575   if (DestVT == MVT::f128)
15576     return false;
15577   return true;
15578 }
15579 
15580 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15581   return isInt<16>(Imm) || isUInt<16>(Imm);
15582 }
15583 
15584 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15585   return isInt<16>(Imm) || isUInt<16>(Imm);
15586 }
15587 
15588 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
15589                                                        MachineMemOperand::Flags,
15590                                                        bool *Fast) const {
15591   if (DisablePPCUnaligned)
15592     return false;
15593 
15594   // PowerPC supports unaligned memory access for simple non-vector types.
15595   // Although accessing unaligned addresses is not as efficient as accessing
15596   // aligned addresses, it is generally more efficient than manual expansion,
15597   // and generally only traps for software emulation when crossing page
15598   // boundaries.
15599 
15600   if (!VT.isSimple())
15601     return false;
15602 
15603   if (VT.isFloatingPoint() && !VT.isVector() &&
15604       !Subtarget.allowsUnalignedFPAccess())
15605     return false;
15606 
15607   if (VT.getSimpleVT().isVector()) {
15608     if (Subtarget.hasVSX()) {
15609       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15610           VT != MVT::v4f32 && VT != MVT::v4i32)
15611         return false;
15612     } else {
15613       return false;
15614     }
15615   }
15616 
15617   if (VT == MVT::ppcf128)
15618     return false;
15619 
15620   if (Fast)
15621     *Fast = true;
15622 
15623   return true;
15624 }
15625 
15626 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
15627                                                SDValue C) const {
15628   // Check integral scalar types.
15629   if (!VT.isScalarInteger())
15630     return false;
15631   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
15632     if (!ConstNode->getAPIntValue().isSignedIntN(64))
15633       return false;
15634     // This transformation will generate >= 2 operations. But the following
15635     // cases will generate <= 2 instructions during ISEL. So exclude them.
15636     // 1. If the constant multiplier fits 16 bits, it can be handled by one
15637     // HW instruction, ie. MULLI
15638     // 2. If the multiplier after shifted fits 16 bits, an extra shift
15639     // instruction is needed than case 1, ie. MULLI and RLDICR
15640     int64_t Imm = ConstNode->getSExtValue();
15641     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
15642     Imm >>= Shift;
15643     if (isInt<16>(Imm))
15644       return false;
15645     uint64_t UImm = static_cast<uint64_t>(Imm);
15646     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
15647         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
15648       return true;
15649   }
15650   return false;
15651 }
15652 
15653 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15654                                                    EVT VT) const {
15655   return isFMAFasterThanFMulAndFAdd(
15656       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15657 }
15658 
15659 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15660                                                    Type *Ty) const {
15661   switch (Ty->getScalarType()->getTypeID()) {
15662   case Type::FloatTyID:
15663   case Type::DoubleTyID:
15664     return true;
15665   case Type::FP128TyID:
15666     return Subtarget.hasP9Vector();
15667   default:
15668     return false;
15669   }
15670 }
15671 
15672 // FIXME: add more patterns which are not profitable to hoist.
15673 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15674   if (!I->hasOneUse())
15675     return true;
15676 
15677   Instruction *User = I->user_back();
15678   assert(User && "A single use instruction with no uses.");
15679 
15680   switch (I->getOpcode()) {
15681   case Instruction::FMul: {
15682     // Don't break FMA, PowerPC prefers FMA.
15683     if (User->getOpcode() != Instruction::FSub &&
15684         User->getOpcode() != Instruction::FAdd)
15685       return true;
15686 
15687     const TargetOptions &Options = getTargetMachine().Options;
15688     const Function *F = I->getFunction();
15689     const DataLayout &DL = F->getParent()->getDataLayout();
15690     Type *Ty = User->getOperand(0)->getType();
15691 
15692     return !(
15693         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15694         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15695         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15696   }
15697   case Instruction::Load: {
15698     // Don't break "store (load float*)" pattern, this pattern will be combined
15699     // to "store (load int32)" in later InstCombine pass. See function
15700     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15701     // cycles than loading a 32 bit integer.
15702     LoadInst *LI = cast<LoadInst>(I);
15703     // For the loads that combineLoadToOperationType does nothing, like
15704     // ordered load, it should be profitable to hoist them.
15705     // For swifterror load, it can only be used for pointer to pointer type, so
15706     // later type check should get rid of this case.
15707     if (!LI->isUnordered())
15708       return true;
15709 
15710     if (User->getOpcode() != Instruction::Store)
15711       return true;
15712 
15713     if (I->getType()->getTypeID() != Type::FloatTyID)
15714       return true;
15715 
15716     return false;
15717   }
15718   default:
15719     return true;
15720   }
15721   return true;
15722 }
15723 
15724 const MCPhysReg *
15725 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15726   // LR is a callee-save register, but we must treat it as clobbered by any call
15727   // site. Hence we include LR in the scratch registers, which are in turn added
15728   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15729   // to CTR, which is used by any indirect call.
15730   static const MCPhysReg ScratchRegs[] = {
15731     PPC::X12, PPC::LR8, PPC::CTR8, 0
15732   };
15733 
15734   return ScratchRegs;
15735 }
15736 
15737 Register PPCTargetLowering::getExceptionPointerRegister(
15738     const Constant *PersonalityFn) const {
15739   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15740 }
15741 
15742 Register PPCTargetLowering::getExceptionSelectorRegister(
15743     const Constant *PersonalityFn) const {
15744   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15745 }
15746 
15747 bool
15748 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15749                      EVT VT , unsigned DefinedValues) const {
15750   if (VT == MVT::v2i64)
15751     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15752 
15753   if (Subtarget.hasVSX())
15754     return true;
15755 
15756   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15757 }
15758 
15759 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15760   if (DisableILPPref || Subtarget.enableMachineScheduler())
15761     return TargetLowering::getSchedulingPreference(N);
15762 
15763   return Sched::ILP;
15764 }
15765 
15766 // Create a fast isel object.
15767 FastISel *
15768 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15769                                   const TargetLibraryInfo *LibInfo) const {
15770   return PPC::createFastISel(FuncInfo, LibInfo);
15771 }
15772 
15773 // 'Inverted' means the FMA opcode after negating one multiplicand.
15774 // For example, (fma -a b c) = (fnmsub a b c)
15775 static unsigned invertFMAOpcode(unsigned Opc) {
15776   switch (Opc) {
15777   default:
15778     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15779   case ISD::FMA:
15780     return PPCISD::FNMSUB;
15781   case PPCISD::FNMSUB:
15782     return ISD::FMA;
15783   }
15784 }
15785 
15786 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15787                                                 bool LegalOps, bool OptForSize,
15788                                                 NegatibleCost &Cost,
15789                                                 unsigned Depth) const {
15790   if (Depth > SelectionDAG::MaxRecursionDepth)
15791     return SDValue();
15792 
15793   unsigned Opc = Op.getOpcode();
15794   EVT VT = Op.getValueType();
15795   SDNodeFlags Flags = Op.getNode()->getFlags();
15796 
15797   switch (Opc) {
15798   case PPCISD::FNMSUB:
15799     if (!Op.hasOneUse() || !isTypeLegal(VT))
15800       break;
15801 
15802     const TargetOptions &Options = getTargetMachine().Options;
15803     SDValue N0 = Op.getOperand(0);
15804     SDValue N1 = Op.getOperand(1);
15805     SDValue N2 = Op.getOperand(2);
15806     SDLoc Loc(Op);
15807 
15808     NegatibleCost N2Cost = NegatibleCost::Expensive;
15809     SDValue NegN2 =
15810         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15811 
15812     if (!NegN2)
15813       return SDValue();
15814 
15815     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15816     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15817     // These transformations may change sign of zeroes. For example,
15818     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15819     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15820       // Try and choose the cheaper one to negate.
15821       NegatibleCost N0Cost = NegatibleCost::Expensive;
15822       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15823                                            N0Cost, Depth + 1);
15824 
15825       NegatibleCost N1Cost = NegatibleCost::Expensive;
15826       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15827                                            N1Cost, Depth + 1);
15828 
15829       if (NegN0 && N0Cost <= N1Cost) {
15830         Cost = std::min(N0Cost, N2Cost);
15831         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15832       } else if (NegN1) {
15833         Cost = std::min(N1Cost, N2Cost);
15834         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15835       }
15836     }
15837 
15838     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15839     if (isOperationLegal(ISD::FMA, VT)) {
15840       Cost = N2Cost;
15841       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15842     }
15843 
15844     break;
15845   }
15846 
15847   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15848                                               Cost, Depth);
15849 }
15850 
15851 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15852 bool PPCTargetLowering::useLoadStackGuardNode() const {
15853   if (!Subtarget.isTargetLinux())
15854     return TargetLowering::useLoadStackGuardNode();
15855   return true;
15856 }
15857 
15858 // Override to disable global variable loading on Linux.
15859 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15860   if (!Subtarget.isTargetLinux())
15861     return TargetLowering::insertSSPDeclarations(M);
15862 }
15863 
15864 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15865                                      bool ForCodeSize) const {
15866   if (!VT.isSimple() || !Subtarget.hasVSX())
15867     return false;
15868 
15869   switch(VT.getSimpleVT().SimpleTy) {
15870   default:
15871     // For FP types that are currently not supported by PPC backend, return
15872     // false. Examples: f16, f80.
15873     return false;
15874   case MVT::f32:
15875   case MVT::f64:
15876     if (Subtarget.hasPrefixInstrs()) {
15877       // With prefixed instructions, we can materialize anything that can be
15878       // represented with a 32-bit immediate, not just positive zero.
15879       APFloat APFloatOfImm = Imm;
15880       return convertToNonDenormSingle(APFloatOfImm);
15881     }
15882     LLVM_FALLTHROUGH;
15883   case MVT::ppcf128:
15884     return Imm.isPosZero();
15885   }
15886 }
15887 
15888 // For vector shift operation op, fold
15889 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15890 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15891                                   SelectionDAG &DAG) {
15892   SDValue N0 = N->getOperand(0);
15893   SDValue N1 = N->getOperand(1);
15894   EVT VT = N0.getValueType();
15895   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15896   unsigned Opcode = N->getOpcode();
15897   unsigned TargetOpcode;
15898 
15899   switch (Opcode) {
15900   default:
15901     llvm_unreachable("Unexpected shift operation");
15902   case ISD::SHL:
15903     TargetOpcode = PPCISD::SHL;
15904     break;
15905   case ISD::SRL:
15906     TargetOpcode = PPCISD::SRL;
15907     break;
15908   case ISD::SRA:
15909     TargetOpcode = PPCISD::SRA;
15910     break;
15911   }
15912 
15913   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15914       N1->getOpcode() == ISD::AND)
15915     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15916       if (Mask->getZExtValue() == OpSizeInBits - 1)
15917         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15918 
15919   return SDValue();
15920 }
15921 
15922 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15923   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15924     return Value;
15925 
15926   SDValue N0 = N->getOperand(0);
15927   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15928   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
15929       N0.getOpcode() != ISD::SIGN_EXTEND ||
15930       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
15931       N->getValueType(0) != MVT::i64)
15932     return SDValue();
15933 
15934   // We can't save an operation here if the value is already extended, and
15935   // the existing shift is easier to combine.
15936   SDValue ExtsSrc = N0.getOperand(0);
15937   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15938       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15939     return SDValue();
15940 
15941   SDLoc DL(N0);
15942   SDValue ShiftBy = SDValue(CN1, 0);
15943   // We want the shift amount to be i32 on the extswli, but the shift could
15944   // have an i64.
15945   if (ShiftBy.getValueType() == MVT::i64)
15946     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15947 
15948   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15949                          ShiftBy);
15950 }
15951 
15952 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15953   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15954     return Value;
15955 
15956   return SDValue();
15957 }
15958 
15959 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15960   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15961     return Value;
15962 
15963   return SDValue();
15964 }
15965 
15966 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15967 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15968 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15969 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15970 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15971                                  const PPCSubtarget &Subtarget) {
15972   if (!Subtarget.isPPC64())
15973     return SDValue();
15974 
15975   SDValue LHS = N->getOperand(0);
15976   SDValue RHS = N->getOperand(1);
15977 
15978   auto isZextOfCompareWithConstant = [](SDValue Op) {
15979     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15980         Op.getValueType() != MVT::i64)
15981       return false;
15982 
15983     SDValue Cmp = Op.getOperand(0);
15984     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15985         Cmp.getOperand(0).getValueType() != MVT::i64)
15986       return false;
15987 
15988     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15989       int64_t NegConstant = 0 - Constant->getSExtValue();
15990       // Due to the limitations of the addi instruction,
15991       // -C is required to be [-32768, 32767].
15992       return isInt<16>(NegConstant);
15993     }
15994 
15995     return false;
15996   };
15997 
15998   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15999   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16000 
16001   // If there is a pattern, canonicalize a zext operand to the RHS.
16002   if (LHSHasPattern && !RHSHasPattern)
16003     std::swap(LHS, RHS);
16004   else if (!LHSHasPattern && !RHSHasPattern)
16005     return SDValue();
16006 
16007   SDLoc DL(N);
16008   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16009   SDValue Cmp = RHS.getOperand(0);
16010   SDValue Z = Cmp.getOperand(0);
16011   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16012 
16013   assert(Constant && "Constant Should not be a null pointer.");
16014   int64_t NegConstant = 0 - Constant->getSExtValue();
16015 
16016   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16017   default: break;
16018   case ISD::SETNE: {
16019     //                                 when C == 0
16020     //                             --> addze X, (addic Z, -1).carry
16021     //                            /
16022     // add X, (zext(setne Z, C))--
16023     //                            \    when -32768 <= -C <= 32767 && C != 0
16024     //                             --> addze X, (addic (addi Z, -C), -1).carry
16025     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16026                               DAG.getConstant(NegConstant, DL, MVT::i64));
16027     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16028     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16029                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16030     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16031                        SDValue(Addc.getNode(), 1));
16032     }
16033   case ISD::SETEQ: {
16034     //                                 when C == 0
16035     //                             --> addze X, (subfic Z, 0).carry
16036     //                            /
16037     // add X, (zext(sete  Z, C))--
16038     //                            \    when -32768 <= -C <= 32767 && C != 0
16039     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16040     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16041                               DAG.getConstant(NegConstant, DL, MVT::i64));
16042     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16043     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16044                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16045     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16046                        SDValue(Subc.getNode(), 1));
16047     }
16048   }
16049 
16050   return SDValue();
16051 }
16052 
16053 // Transform
16054 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16055 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16056 // In this case both C1 and C2 must be known constants.
16057 // C1+C2 must fit into a 34 bit signed integer.
16058 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16059                                           const PPCSubtarget &Subtarget) {
16060   if (!Subtarget.isUsingPCRelativeCalls())
16061     return SDValue();
16062 
16063   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16064   // If we find that node try to cast the Global Address and the Constant.
16065   SDValue LHS = N->getOperand(0);
16066   SDValue RHS = N->getOperand(1);
16067 
16068   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16069     std::swap(LHS, RHS);
16070 
16071   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16072     return SDValue();
16073 
16074   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16075   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16076   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16077 
16078   // Check that both casts succeeded.
16079   if (!GSDN || !ConstNode)
16080     return SDValue();
16081 
16082   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16083   SDLoc DL(GSDN);
16084 
16085   // The signed int offset needs to fit in 34 bits.
16086   if (!isInt<34>(NewOffset))
16087     return SDValue();
16088 
16089   // The new global address is a copy of the old global address except
16090   // that it has the updated Offset.
16091   SDValue GA =
16092       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16093                                  NewOffset, GSDN->getTargetFlags());
16094   SDValue MatPCRel =
16095       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16096   return MatPCRel;
16097 }
16098 
16099 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16100   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16101     return Value;
16102 
16103   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16104     return Value;
16105 
16106   return SDValue();
16107 }
16108 
16109 // Detect TRUNCATE operations on bitcasts of float128 values.
16110 // What we are looking for here is the situtation where we extract a subset
16111 // of bits from a 128 bit float.
16112 // This can be of two forms:
16113 // 1) BITCAST of f128 feeding TRUNCATE
16114 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16115 // The reason this is required is because we do not have a legal i128 type
16116 // and so we want to prevent having to store the f128 and then reload part
16117 // of it.
16118 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16119                                            DAGCombinerInfo &DCI) const {
16120   // If we are using CRBits then try that first.
16121   if (Subtarget.useCRBits()) {
16122     // Check if CRBits did anything and return that if it did.
16123     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16124       return CRTruncValue;
16125   }
16126 
16127   SDLoc dl(N);
16128   SDValue Op0 = N->getOperand(0);
16129 
16130   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16131   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16132     EVT VT = N->getValueType(0);
16133     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16134       return SDValue();
16135     SDValue Sub = Op0.getOperand(0);
16136     if (Sub.getOpcode() == ISD::SUB) {
16137       SDValue SubOp0 = Sub.getOperand(0);
16138       SDValue SubOp1 = Sub.getOperand(1);
16139       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16140           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16141         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16142                                SubOp1.getOperand(0),
16143                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16144       }
16145     }
16146   }
16147 
16148   // Looking for a truncate of i128 to i64.
16149   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16150     return SDValue();
16151 
16152   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16153 
16154   // SRL feeding TRUNCATE.
16155   if (Op0.getOpcode() == ISD::SRL) {
16156     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16157     // The right shift has to be by 64 bits.
16158     if (!ConstNode || ConstNode->getZExtValue() != 64)
16159       return SDValue();
16160 
16161     // Switch the element number to extract.
16162     EltToExtract = EltToExtract ? 0 : 1;
16163     // Update Op0 past the SRL.
16164     Op0 = Op0.getOperand(0);
16165   }
16166 
16167   // BITCAST feeding a TRUNCATE possibly via SRL.
16168   if (Op0.getOpcode() == ISD::BITCAST &&
16169       Op0.getValueType() == MVT::i128 &&
16170       Op0.getOperand(0).getValueType() == MVT::f128) {
16171     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16172     return DCI.DAG.getNode(
16173         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16174         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16175   }
16176   return SDValue();
16177 }
16178 
16179 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16180   SelectionDAG &DAG = DCI.DAG;
16181 
16182   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16183   if (!ConstOpOrElement)
16184     return SDValue();
16185 
16186   // An imul is usually smaller than the alternative sequence for legal type.
16187   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16188       isOperationLegal(ISD::MUL, N->getValueType(0)))
16189     return SDValue();
16190 
16191   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16192     switch (this->Subtarget.getCPUDirective()) {
16193     default:
16194       // TODO: enhance the condition for subtarget before pwr8
16195       return false;
16196     case PPC::DIR_PWR8:
16197       //  type        mul     add    shl
16198       // scalar        4       1      1
16199       // vector        7       2      2
16200       return true;
16201     case PPC::DIR_PWR9:
16202     case PPC::DIR_PWR10:
16203     case PPC::DIR_PWR_FUTURE:
16204       //  type        mul     add    shl
16205       // scalar        5       2      2
16206       // vector        7       2      2
16207 
16208       // The cycle RATIO of related operations are showed as a table above.
16209       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16210       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16211       // are 4, it is always profitable; but for 3 instrs patterns
16212       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16213       // So we should only do it for vector type.
16214       return IsAddOne && IsNeg ? VT.isVector() : true;
16215     }
16216   };
16217 
16218   EVT VT = N->getValueType(0);
16219   SDLoc DL(N);
16220 
16221   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16222   bool IsNeg = MulAmt.isNegative();
16223   APInt MulAmtAbs = MulAmt.abs();
16224 
16225   if ((MulAmtAbs - 1).isPowerOf2()) {
16226     // (mul x, 2^N + 1) => (add (shl x, N), x)
16227     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16228 
16229     if (!IsProfitable(IsNeg, true, VT))
16230       return SDValue();
16231 
16232     SDValue Op0 = N->getOperand(0);
16233     SDValue Op1 =
16234         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16235                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16236     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16237 
16238     if (!IsNeg)
16239       return Res;
16240 
16241     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16242   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16243     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16244     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16245 
16246     if (!IsProfitable(IsNeg, false, VT))
16247       return SDValue();
16248 
16249     SDValue Op0 = N->getOperand(0);
16250     SDValue Op1 =
16251         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16252                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16253 
16254     if (!IsNeg)
16255       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16256     else
16257       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16258 
16259   } else {
16260     return SDValue();
16261   }
16262 }
16263 
16264 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16265 // in combiner since we need to check SD flags and other subtarget features.
16266 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16267                                           DAGCombinerInfo &DCI) const {
16268   SDValue N0 = N->getOperand(0);
16269   SDValue N1 = N->getOperand(1);
16270   SDValue N2 = N->getOperand(2);
16271   SDNodeFlags Flags = N->getFlags();
16272   EVT VT = N->getValueType(0);
16273   SelectionDAG &DAG = DCI.DAG;
16274   const TargetOptions &Options = getTargetMachine().Options;
16275   unsigned Opc = N->getOpcode();
16276   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16277   bool LegalOps = !DCI.isBeforeLegalizeOps();
16278   SDLoc Loc(N);
16279 
16280   if (!isOperationLegal(ISD::FMA, VT))
16281     return SDValue();
16282 
16283   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16284   // since (fnmsub a b c)=-0 while c-ab=+0.
16285   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16286     return SDValue();
16287 
16288   // (fma (fneg a) b c) => (fnmsub a b c)
16289   // (fnmsub (fneg a) b c) => (fma a b c)
16290   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16291     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16292 
16293   // (fma a (fneg b) c) => (fnmsub a b c)
16294   // (fnmsub a (fneg b) c) => (fma a b c)
16295   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16296     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16297 
16298   return SDValue();
16299 }
16300 
16301 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16302   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16303   if (!Subtarget.is64BitELFABI())
16304     return false;
16305 
16306   // If not a tail call then no need to proceed.
16307   if (!CI->isTailCall())
16308     return false;
16309 
16310   // If sibling calls have been disabled and tail-calls aren't guaranteed
16311   // there is no reason to duplicate.
16312   auto &TM = getTargetMachine();
16313   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16314     return false;
16315 
16316   // Can't tail call a function called indirectly, or if it has variadic args.
16317   const Function *Callee = CI->getCalledFunction();
16318   if (!Callee || Callee->isVarArg())
16319     return false;
16320 
16321   // Make sure the callee and caller calling conventions are eligible for tco.
16322   const Function *Caller = CI->getParent()->getParent();
16323   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16324                                            CI->getCallingConv()))
16325       return false;
16326 
16327   // If the function is local then we have a good chance at tail-calling it
16328   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16329 }
16330 
16331 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16332   if (!Subtarget.hasVSX())
16333     return false;
16334   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16335     return true;
16336   return VT == MVT::f32 || VT == MVT::f64 ||
16337     VT == MVT::v4f32 || VT == MVT::v2f64;
16338 }
16339 
16340 bool PPCTargetLowering::
16341 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16342   const Value *Mask = AndI.getOperand(1);
16343   // If the mask is suitable for andi. or andis. we should sink the and.
16344   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16345     // Can't handle constants wider than 64-bits.
16346     if (CI->getBitWidth() > 64)
16347       return false;
16348     int64_t ConstVal = CI->getZExtValue();
16349     return isUInt<16>(ConstVal) ||
16350       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16351   }
16352 
16353   // For non-constant masks, we can always use the record-form and.
16354   return true;
16355 }
16356 
16357 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16358 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16359 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16360 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16361 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16362 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16363   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16364   assert(Subtarget.hasP9Altivec() &&
16365          "Only combine this when P9 altivec supported!");
16366   EVT VT = N->getValueType(0);
16367   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16368     return SDValue();
16369 
16370   SelectionDAG &DAG = DCI.DAG;
16371   SDLoc dl(N);
16372   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16373     // Even for signed integers, if it's known to be positive (as signed
16374     // integer) due to zero-extended inputs.
16375     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16376     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16377     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16378          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16379         (SubOpcd1 == ISD::ZERO_EXTEND ||
16380          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16381       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16382                          N->getOperand(0)->getOperand(0),
16383                          N->getOperand(0)->getOperand(1),
16384                          DAG.getTargetConstant(0, dl, MVT::i32));
16385     }
16386 
16387     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16388     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16389         N->getOperand(0).hasOneUse()) {
16390       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16391                          N->getOperand(0)->getOperand(0),
16392                          N->getOperand(0)->getOperand(1),
16393                          DAG.getTargetConstant(1, dl, MVT::i32));
16394     }
16395   }
16396 
16397   return SDValue();
16398 }
16399 
16400 // For type v4i32/v8ii16/v16i8, transform
16401 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16402 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16403 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16404 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16405 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16406                                           DAGCombinerInfo &DCI) const {
16407   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16408   assert(Subtarget.hasP9Altivec() &&
16409          "Only combine this when P9 altivec supported!");
16410 
16411   SelectionDAG &DAG = DCI.DAG;
16412   SDLoc dl(N);
16413   SDValue Cond = N->getOperand(0);
16414   SDValue TrueOpnd = N->getOperand(1);
16415   SDValue FalseOpnd = N->getOperand(2);
16416   EVT VT = N->getOperand(1).getValueType();
16417 
16418   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16419       FalseOpnd.getOpcode() != ISD::SUB)
16420     return SDValue();
16421 
16422   // ABSD only available for type v4i32/v8i16/v16i8
16423   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16424     return SDValue();
16425 
16426   // At least to save one more dependent computation
16427   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16428     return SDValue();
16429 
16430   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16431 
16432   // Can only handle unsigned comparison here
16433   switch (CC) {
16434   default:
16435     return SDValue();
16436   case ISD::SETUGT:
16437   case ISD::SETUGE:
16438     break;
16439   case ISD::SETULT:
16440   case ISD::SETULE:
16441     std::swap(TrueOpnd, FalseOpnd);
16442     break;
16443   }
16444 
16445   SDValue CmpOpnd1 = Cond.getOperand(0);
16446   SDValue CmpOpnd2 = Cond.getOperand(1);
16447 
16448   // SETCC CmpOpnd1 CmpOpnd2 cond
16449   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16450   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16451   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16452       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16453       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16454       FalseOpnd.getOperand(1) == CmpOpnd1) {
16455     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16456                        CmpOpnd1, CmpOpnd2,
16457                        DAG.getTargetConstant(0, dl, MVT::i32));
16458   }
16459 
16460   return SDValue();
16461 }
16462