1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> EnableQuadwordAtomics(
125     "ppc-quadword-atomics",
126     cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127     cl::Hidden);
128 
129 static cl::opt<bool>
130     DisablePerfectShuffle("ppc-disable-perfect-shuffle",
131                           cl::desc("disable vector permute decomposition"),
132                           cl::init(true), cl::Hidden);
133 
134 STATISTIC(NumTailCalls, "Number of tail calls");
135 STATISTIC(NumSiblingCalls, "Number of sibling calls");
136 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
137 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
138 
139 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
140 
141 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
142 
143 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
144 
145 // FIXME: Remove this once the bug has been fixed!
146 extern cl::opt<bool> ANDIGlueBug;
147 
148 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
149                                      const PPCSubtarget &STI)
150     : TargetLowering(TM), Subtarget(STI) {
151   // Initialize map that relates the PPC addressing modes to the computed flags
152   // of a load/store instruction. The map is used to determine the optimal
153   // addressing mode when selecting load and stores.
154   initializeAddrModeMap();
155   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
156   // arguments are at least 4/8 bytes aligned.
157   bool isPPC64 = Subtarget.isPPC64();
158   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
159 
160   // Set up the register classes.
161   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
162   if (!useSoftFloat()) {
163     if (hasSPE()) {
164       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
165       // EFPU2 APU only supports f32
166       if (!Subtarget.hasEFPU2())
167         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
168     } else {
169       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
170       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
171     }
172   }
173 
174   // Match BITREVERSE to customized fast code sequence in the td file.
175   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
176   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
177 
178   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
179   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
180 
181   // Custom lower inline assembly to check for special registers.
182   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
183   setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
184 
185   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
186   for (MVT VT : MVT::integer_valuetypes()) {
187     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
188     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
189   }
190 
191   if (Subtarget.isISA3_0()) {
192     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
193     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
194     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
195     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
196   } else {
197     // No extending loads from f16 or HW conversions back and forth.
198     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
199     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
200     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
201     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
202     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
203     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
204     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
205     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
206   }
207 
208   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
209 
210   // PowerPC has pre-inc load and store's.
211   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
212   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
213   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
214   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
215   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
216   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
217   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
218   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
219   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
220   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
221   if (!Subtarget.hasSPE()) {
222     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
223     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
224     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
225     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
226   }
227 
228   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
229   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
230   for (MVT VT : ScalarIntVTs) {
231     setOperationAction(ISD::ADDC, VT, Legal);
232     setOperationAction(ISD::ADDE, VT, Legal);
233     setOperationAction(ISD::SUBC, VT, Legal);
234     setOperationAction(ISD::SUBE, VT, Legal);
235   }
236 
237   if (Subtarget.useCRBits()) {
238     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
239 
240     if (isPPC64 || Subtarget.hasFPCVT()) {
241       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
242       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
243                         isPPC64 ? MVT::i64 : MVT::i32);
244       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
245       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
246                         isPPC64 ? MVT::i64 : MVT::i32);
247 
248       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
249       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
250                          isPPC64 ? MVT::i64 : MVT::i32);
251       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
252       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
253                         isPPC64 ? MVT::i64 : MVT::i32);
254 
255       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
256       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
257                         isPPC64 ? MVT::i64 : MVT::i32);
258       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
259       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
260                         isPPC64 ? MVT::i64 : MVT::i32);
261 
262       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
263       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
264                         isPPC64 ? MVT::i64 : MVT::i32);
265       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
266       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
267                         isPPC64 ? MVT::i64 : MVT::i32);
268     } else {
269       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
270       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
271       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
272       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
273     }
274 
275     // PowerPC does not support direct load/store of condition registers.
276     setOperationAction(ISD::LOAD, MVT::i1, Custom);
277     setOperationAction(ISD::STORE, MVT::i1, Custom);
278 
279     // FIXME: Remove this once the ANDI glue bug is fixed:
280     if (ANDIGlueBug)
281       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
282 
283     for (MVT VT : MVT::integer_valuetypes()) {
284       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
285       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
286       setTruncStoreAction(VT, MVT::i1, Expand);
287     }
288 
289     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
290   }
291 
292   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
293   // PPC (the libcall is not available).
294   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
295   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
296   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
297   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
298 
299   // We do not currently implement these libm ops for PowerPC.
300   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
301   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
302   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
303   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
304   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
305   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
306 
307   // PowerPC has no SREM/UREM instructions unless we are on P9
308   // On P9 we may use a hardware instruction to compute the remainder.
309   // When the result of both the remainder and the division is required it is
310   // more efficient to compute the remainder from the result of the division
311   // rather than use the remainder instruction. The instructions are legalized
312   // directly because the DivRemPairsPass performs the transformation at the IR
313   // level.
314   if (Subtarget.isISA3_0()) {
315     setOperationAction(ISD::SREM, MVT::i32, Legal);
316     setOperationAction(ISD::UREM, MVT::i32, Legal);
317     setOperationAction(ISD::SREM, MVT::i64, Legal);
318     setOperationAction(ISD::UREM, MVT::i64, Legal);
319   } else {
320     setOperationAction(ISD::SREM, MVT::i32, Expand);
321     setOperationAction(ISD::UREM, MVT::i32, Expand);
322     setOperationAction(ISD::SREM, MVT::i64, Expand);
323     setOperationAction(ISD::UREM, MVT::i64, Expand);
324   }
325 
326   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
327   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
328   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
329   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
330   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
331   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
332   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
333   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
334   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
335 
336   // Handle constrained floating-point operations of scalar.
337   // TODO: Handle SPE specific operation.
338   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
339   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
340   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
341   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
342   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
343 
344   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
345   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
346   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
347   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
348 
349   if (!Subtarget.hasSPE()) {
350     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
352   }
353 
354   if (Subtarget.hasVSX()) {
355     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
357   }
358 
359   if (Subtarget.hasFSQRT()) {
360     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
361     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
362   }
363 
364   if (Subtarget.hasFPRND()) {
365     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
366     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
367     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
368     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
369 
370     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
371     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
372     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
373     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
374   }
375 
376   // We don't support sin/cos/sqrt/fmod/pow
377   setOperationAction(ISD::FSIN , MVT::f64, Expand);
378   setOperationAction(ISD::FCOS , MVT::f64, Expand);
379   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
380   setOperationAction(ISD::FREM , MVT::f64, Expand);
381   setOperationAction(ISD::FPOW , MVT::f64, Expand);
382   setOperationAction(ISD::FSIN , MVT::f32, Expand);
383   setOperationAction(ISD::FCOS , MVT::f32, Expand);
384   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
385   setOperationAction(ISD::FREM , MVT::f32, Expand);
386   setOperationAction(ISD::FPOW , MVT::f32, Expand);
387 
388   // MASS transformation for LLVM intrinsics with replicating fast-math flag
389   // to be consistent to PPCGenScalarMASSEntries pass
390   if (TM.getOptLevel() == CodeGenOpt::Aggressive &&
391       TM.Options.PPCGenScalarMASSEntries) {
392     setOperationAction(ISD::FSIN , MVT::f64, Custom);
393     setOperationAction(ISD::FCOS , MVT::f64, Custom);
394     setOperationAction(ISD::FPOW , MVT::f64, Custom);
395     setOperationAction(ISD::FLOG, MVT::f64, Custom);
396     setOperationAction(ISD::FLOG10, MVT::f64, Custom);
397     setOperationAction(ISD::FEXP, MVT::f64, Custom);
398     setOperationAction(ISD::FSIN , MVT::f32, Custom);
399     setOperationAction(ISD::FCOS , MVT::f32, Custom);
400     setOperationAction(ISD::FPOW , MVT::f32, Custom);
401     setOperationAction(ISD::FLOG, MVT::f32, Custom);
402     setOperationAction(ISD::FLOG10, MVT::f32, Custom);
403     setOperationAction(ISD::FEXP, MVT::f32, Custom);
404   }
405 
406   if (Subtarget.hasSPE()) {
407     setOperationAction(ISD::FMA  , MVT::f64, Expand);
408     setOperationAction(ISD::FMA  , MVT::f32, Expand);
409   } else {
410     setOperationAction(ISD::FMA  , MVT::f64, Legal);
411     setOperationAction(ISD::FMA  , MVT::f32, Legal);
412   }
413 
414   if (Subtarget.hasSPE())
415     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
416 
417   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
418 
419   // If we're enabling GP optimizations, use hardware square root
420   if (!Subtarget.hasFSQRT() &&
421       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
422         Subtarget.hasFRE()))
423     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
424 
425   if (!Subtarget.hasFSQRT() &&
426       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
427         Subtarget.hasFRES()))
428     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
429 
430   if (Subtarget.hasFCPSGN()) {
431     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
432     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
433   } else {
434     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
435     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
436   }
437 
438   if (Subtarget.hasFPRND()) {
439     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
440     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
441     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
442     setOperationAction(ISD::FROUND, MVT::f64, Legal);
443 
444     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
445     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
446     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
447     setOperationAction(ISD::FROUND, MVT::f32, Legal);
448   }
449 
450   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
451   // to speed up scalar BSWAP64.
452   // CTPOP or CTTZ were introduced in P8/P9 respectively
453   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
454   if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
455     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
456   else
457     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
458   if (Subtarget.isISA3_0()) {
459     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
460     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
461   } else {
462     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
463     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
464   }
465 
466   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
467     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
468     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
469   } else {
470     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
471     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
472   }
473 
474   // PowerPC does not have ROTR
475   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
476   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
477 
478   if (!Subtarget.useCRBits()) {
479     // PowerPC does not have Select
480     setOperationAction(ISD::SELECT, MVT::i32, Expand);
481     setOperationAction(ISD::SELECT, MVT::i64, Expand);
482     setOperationAction(ISD::SELECT, MVT::f32, Expand);
483     setOperationAction(ISD::SELECT, MVT::f64, Expand);
484   }
485 
486   // PowerPC wants to turn select_cc of FP into fsel when possible.
487   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
488   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
489 
490   // PowerPC wants to optimize integer setcc a bit
491   if (!Subtarget.useCRBits())
492     setOperationAction(ISD::SETCC, MVT::i32, Custom);
493 
494   if (Subtarget.hasFPU()) {
495     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
496     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
497     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
498 
499     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
500     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
501     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
502   }
503 
504   // PowerPC does not have BRCOND which requires SetCC
505   if (!Subtarget.useCRBits())
506     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
507 
508   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
509 
510   if (Subtarget.hasSPE()) {
511     // SPE has built-in conversions
512     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
513     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
514     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
515     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
516     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
517     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
518 
519     // SPE supports signaling compare of f32/f64.
520     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
521     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
522   } else {
523     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
524     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
525     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
526 
527     // PowerPC does not have [U|S]INT_TO_FP
528     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
529     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
530     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
531     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
532   }
533 
534   if (Subtarget.hasDirectMove() && isPPC64) {
535     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
536     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
537     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
538     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
539     if (TM.Options.UnsafeFPMath) {
540       setOperationAction(ISD::LRINT, MVT::f64, Legal);
541       setOperationAction(ISD::LRINT, MVT::f32, Legal);
542       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
543       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
544       setOperationAction(ISD::LROUND, MVT::f64, Legal);
545       setOperationAction(ISD::LROUND, MVT::f32, Legal);
546       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
547       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
548     }
549   } else {
550     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
551     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
552     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
553     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
554   }
555 
556   // We cannot sextinreg(i1).  Expand to shifts.
557   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
558 
559   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
560   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
561   // support continuation, user-level threading, and etc.. As a result, no
562   // other SjLj exception interfaces are implemented and please don't build
563   // your own exception handling based on them.
564   // LLVM/Clang supports zero-cost DWARF exception handling.
565   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
566   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
567 
568   // We want to legalize GlobalAddress and ConstantPool nodes into the
569   // appropriate instructions to materialize the address.
570   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
571   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
572   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
573   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
574   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
575   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
576   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
578   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
579   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
580 
581   // TRAP is legal.
582   setOperationAction(ISD::TRAP, MVT::Other, Legal);
583 
584   // TRAMPOLINE is custom lowered.
585   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
586   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
587 
588   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
589   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
590 
591   if (Subtarget.is64BitELFABI()) {
592     // VAARG always uses double-word chunks, so promote anything smaller.
593     setOperationAction(ISD::VAARG, MVT::i1, Promote);
594     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
595     setOperationAction(ISD::VAARG, MVT::i8, Promote);
596     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
597     setOperationAction(ISD::VAARG, MVT::i16, Promote);
598     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
599     setOperationAction(ISD::VAARG, MVT::i32, Promote);
600     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
601     setOperationAction(ISD::VAARG, MVT::Other, Expand);
602   } else if (Subtarget.is32BitELFABI()) {
603     // VAARG is custom lowered with the 32-bit SVR4 ABI.
604     setOperationAction(ISD::VAARG, MVT::Other, Custom);
605     setOperationAction(ISD::VAARG, MVT::i64, Custom);
606   } else
607     setOperationAction(ISD::VAARG, MVT::Other, Expand);
608 
609   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
610   if (Subtarget.is32BitELFABI())
611     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
612   else
613     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
614 
615   // Use the default implementation.
616   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
617   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
618   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
619   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
620   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
621   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
622   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
623   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
624   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
625 
626   // We want to custom lower some of our intrinsics.
627   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
628   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
629   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
630   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
631   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
632 
633   // To handle counter-based loop conditions.
634   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
635 
636   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
637   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
638   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
639   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
640 
641   // Comparisons that require checking two conditions.
642   if (Subtarget.hasSPE()) {
643     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
644     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
645     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
646     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
647   }
648   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
649   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
650   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
651   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
652   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
653   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
654   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
655   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
656   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
657   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
658   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
659   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
660 
661   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
662   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
663 
664   if (Subtarget.has64BitSupport()) {
665     // They also have instructions for converting between i64 and fp.
666     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
667     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
668     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
669     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
670     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
671     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
672     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
673     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
674     // This is just the low 32 bits of a (signed) fp->i64 conversion.
675     // We cannot do this with Promote because i64 is not a legal type.
676     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
677     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
678 
679     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
680       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
681       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
682     }
683   } else {
684     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
685     if (Subtarget.hasSPE()) {
686       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
687       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
688     } else {
689       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
690       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
691     }
692   }
693 
694   // With the instructions enabled under FPCVT, we can do everything.
695   if (Subtarget.hasFPCVT()) {
696     if (Subtarget.has64BitSupport()) {
697       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
698       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
699       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
700       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
701       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
702       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
703       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
704       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
705     }
706 
707     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
708     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
709     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
710     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
711     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
712     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
713     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
714     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
715   }
716 
717   if (Subtarget.use64BitRegs()) {
718     // 64-bit PowerPC implementations can support i64 types directly
719     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
720     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
721     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
722     // 64-bit PowerPC wants to expand i128 shifts itself.
723     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
724     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
725     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
726   } else {
727     // 32-bit PowerPC wants to expand i64 shifts itself.
728     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
729     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
730     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
731   }
732 
733   // PowerPC has better expansions for funnel shifts than the generic
734   // TargetLowering::expandFunnelShift.
735   if (Subtarget.has64BitSupport()) {
736     setOperationAction(ISD::FSHL, MVT::i64, Custom);
737     setOperationAction(ISD::FSHR, MVT::i64, Custom);
738   }
739   setOperationAction(ISD::FSHL, MVT::i32, Custom);
740   setOperationAction(ISD::FSHR, MVT::i32, Custom);
741 
742   if (Subtarget.hasVSX()) {
743     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
744     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
745     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
746     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
747   }
748 
749   if (Subtarget.hasAltivec()) {
750     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
751       setOperationAction(ISD::SADDSAT, VT, Legal);
752       setOperationAction(ISD::SSUBSAT, VT, Legal);
753       setOperationAction(ISD::UADDSAT, VT, Legal);
754       setOperationAction(ISD::USUBSAT, VT, Legal);
755     }
756     // First set operation action for all vector types to expand. Then we
757     // will selectively turn on ones that can be effectively codegen'd.
758     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
759       // add/sub are legal for all supported vector VT's.
760       setOperationAction(ISD::ADD, VT, Legal);
761       setOperationAction(ISD::SUB, VT, Legal);
762 
763       // For v2i64, these are only valid with P8Vector. This is corrected after
764       // the loop.
765       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
766         setOperationAction(ISD::SMAX, VT, Legal);
767         setOperationAction(ISD::SMIN, VT, Legal);
768         setOperationAction(ISD::UMAX, VT, Legal);
769         setOperationAction(ISD::UMIN, VT, Legal);
770       }
771       else {
772         setOperationAction(ISD::SMAX, VT, Expand);
773         setOperationAction(ISD::SMIN, VT, Expand);
774         setOperationAction(ISD::UMAX, VT, Expand);
775         setOperationAction(ISD::UMIN, VT, Expand);
776       }
777 
778       if (Subtarget.hasVSX()) {
779         setOperationAction(ISD::FMAXNUM, VT, Legal);
780         setOperationAction(ISD::FMINNUM, VT, Legal);
781       }
782 
783       // Vector instructions introduced in P8
784       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
785         setOperationAction(ISD::CTPOP, VT, Legal);
786         setOperationAction(ISD::CTLZ, VT, Legal);
787       }
788       else {
789         setOperationAction(ISD::CTPOP, VT, Expand);
790         setOperationAction(ISD::CTLZ, VT, Expand);
791       }
792 
793       // Vector instructions introduced in P9
794       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
795         setOperationAction(ISD::CTTZ, VT, Legal);
796       else
797         setOperationAction(ISD::CTTZ, VT, Expand);
798 
799       // We promote all shuffles to v16i8.
800       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
801       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
802 
803       // We promote all non-typed operations to v4i32.
804       setOperationAction(ISD::AND   , VT, Promote);
805       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
806       setOperationAction(ISD::OR    , VT, Promote);
807       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
808       setOperationAction(ISD::XOR   , VT, Promote);
809       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
810       setOperationAction(ISD::LOAD  , VT, Promote);
811       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
812       setOperationAction(ISD::SELECT, VT, Promote);
813       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
814       setOperationAction(ISD::VSELECT, VT, Legal);
815       setOperationAction(ISD::SELECT_CC, VT, Promote);
816       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
817       setOperationAction(ISD::STORE, VT, Promote);
818       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
819 
820       // No other operations are legal.
821       setOperationAction(ISD::MUL , VT, Expand);
822       setOperationAction(ISD::SDIV, VT, Expand);
823       setOperationAction(ISD::SREM, VT, Expand);
824       setOperationAction(ISD::UDIV, VT, Expand);
825       setOperationAction(ISD::UREM, VT, Expand);
826       setOperationAction(ISD::FDIV, VT, Expand);
827       setOperationAction(ISD::FREM, VT, Expand);
828       setOperationAction(ISD::FNEG, VT, Expand);
829       setOperationAction(ISD::FSQRT, VT, Expand);
830       setOperationAction(ISD::FLOG, VT, Expand);
831       setOperationAction(ISD::FLOG10, VT, Expand);
832       setOperationAction(ISD::FLOG2, VT, Expand);
833       setOperationAction(ISD::FEXP, VT, Expand);
834       setOperationAction(ISD::FEXP2, VT, Expand);
835       setOperationAction(ISD::FSIN, VT, Expand);
836       setOperationAction(ISD::FCOS, VT, Expand);
837       setOperationAction(ISD::FABS, VT, Expand);
838       setOperationAction(ISD::FFLOOR, VT, Expand);
839       setOperationAction(ISD::FCEIL,  VT, Expand);
840       setOperationAction(ISD::FTRUNC, VT, Expand);
841       setOperationAction(ISD::FRINT,  VT, Expand);
842       setOperationAction(ISD::FNEARBYINT, VT, Expand);
843       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
844       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
845       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
846       setOperationAction(ISD::MULHU, VT, Expand);
847       setOperationAction(ISD::MULHS, VT, Expand);
848       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
849       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
850       setOperationAction(ISD::UDIVREM, VT, Expand);
851       setOperationAction(ISD::SDIVREM, VT, Expand);
852       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
853       setOperationAction(ISD::FPOW, VT, Expand);
854       setOperationAction(ISD::BSWAP, VT, Expand);
855       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
856       setOperationAction(ISD::ROTL, VT, Expand);
857       setOperationAction(ISD::ROTR, VT, Expand);
858 
859       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
860         setTruncStoreAction(VT, InnerVT, Expand);
861         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
862         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
863         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
864       }
865     }
866     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
867     if (!Subtarget.hasP8Vector()) {
868       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
869       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
870       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
871       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
872     }
873 
874     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
875     // with merges, splats, etc.
876     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
877 
878     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
879     // are cheap, so handle them before they get expanded to scalar.
880     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
881     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
882     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
883     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
884     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
885 
886     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
887     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
888     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
889     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
890     setOperationAction(ISD::SELECT, MVT::v4i32,
891                        Subtarget.useCRBits() ? Legal : Expand);
892     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
893     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
894     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
895     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
896     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
897     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
898     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
899     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
900     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
901     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
902     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
903     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
904     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
905 
906     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
907     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
908     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
909     if (Subtarget.hasAltivec())
910       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
911         setOperationAction(ISD::ROTL, VT, Legal);
912     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
913     if (Subtarget.hasP8Altivec())
914       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
915 
916     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
917     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
918     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
919     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
920 
921     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
922     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
923 
924     if (Subtarget.hasVSX()) {
925       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
926       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
927       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
928     }
929 
930     if (Subtarget.hasP8Altivec())
931       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
932     else
933       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
934 
935     if (Subtarget.isISA3_1()) {
936       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
937       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
938       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
939       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
940       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
941       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
942       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
943       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
944       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
945       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
946       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
947       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
948       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
949       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
950       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
951       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
952       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
953       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
954     }
955 
956     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
957     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
958 
959     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
960     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
961 
962     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
963     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
964     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
965     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
966 
967     // Altivec does not contain unordered floating-point compare instructions
968     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
969     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
970     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
971     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
972 
973     if (Subtarget.hasVSX()) {
974       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
975       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
976       if (Subtarget.hasP8Vector()) {
977         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
978         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
979       }
980       if (Subtarget.hasDirectMove() && isPPC64) {
981         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
982         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
983         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
984         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
985         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
986         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
987         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
988         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
989       }
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
991 
992       // The nearbyint variants are not allowed to raise the inexact exception
993       // so we can only code-gen them with unsafe math.
994       if (TM.Options.UnsafeFPMath) {
995         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
996         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
997       }
998 
999       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1000       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1001       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1002       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1003       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1004       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1005       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1006       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1007 
1008       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1009       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1010       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1011       setOperationAction(ISD::FROUND, MVT::f32, Legal);
1012       setOperationAction(ISD::FRINT, MVT::f32, Legal);
1013 
1014       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1015       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1016 
1017       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1018       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1019 
1020       // Share the Altivec comparison restrictions.
1021       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1022       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1023       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
1024       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1025 
1026       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1027       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1028 
1029       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1030 
1031       if (Subtarget.hasP8Vector())
1032         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1033 
1034       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1035 
1036       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1037       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1038       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1039 
1040       if (Subtarget.hasP8Altivec()) {
1041         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1042         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1043         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1044 
1045         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1046         // SRL, but not for SRA because of the instructions available:
1047         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1048         // doing
1049         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1050         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1051         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1052 
1053         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1054       }
1055       else {
1056         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1057         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1058         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1059 
1060         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1061 
1062         // VSX v2i64 only supports non-arithmetic operations.
1063         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1064         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1065       }
1066 
1067       if (Subtarget.isISA3_1())
1068         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1069       else
1070         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1071 
1072       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1073       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1074       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1075       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1076 
1077       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1078 
1079       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1080       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1081       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1082       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1083       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1084       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1085       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1086       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1087 
1088       // Custom handling for partial vectors of integers converted to
1089       // floating point. We already have optimal handling for v2i32 through
1090       // the DAG combine, so those aren't necessary.
1091       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1092       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1093       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1094       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1095       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1096       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1097       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1098       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1099       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1100       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1101       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1102       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1103       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1104       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1105       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1106       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1107 
1108       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1109       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1110       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1111       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1112       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1113       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1114 
1115       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1116       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1117 
1118       // Handle constrained floating-point operations of vector.
1119       // The predictor is `hasVSX` because altivec instruction has
1120       // no exception but VSX vector instruction has.
1121       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1122       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1123       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1124       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1125       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1126       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1127       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1128       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1129       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1130       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1131       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1132       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1133       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1134 
1135       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1136       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1137       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1138       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1139       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1140       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1141       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1142       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1143       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1144       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1145       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1146       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1147       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1148 
1149       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1150       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1151 
1152       for (MVT FPT : MVT::fp_valuetypes())
1153         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1154 
1155       // Expand the SELECT to SELECT_CC
1156       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1157 
1158       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1159       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1160 
1161       // No implementation for these ops for PowerPC.
1162       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1163       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1164       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1165       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1166       setOperationAction(ISD::FREM, MVT::f128, Expand);
1167     }
1168 
1169     if (Subtarget.hasP8Altivec()) {
1170       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1171       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1172     }
1173 
1174     if (Subtarget.hasP9Vector()) {
1175       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1176       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1177 
1178       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1179       // SRL, but not for SRA because of the instructions available:
1180       // VS{RL} and VS{RL}O.
1181       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1182       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1183       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1184 
1185       setOperationAction(ISD::FADD, MVT::f128, Legal);
1186       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1187       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1188       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1189       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1190 
1191       setOperationAction(ISD::FMA, MVT::f128, Legal);
1192       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1193       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1194       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1195       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1196       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1197       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1198 
1199       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1200       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1201       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1202       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1203       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1204       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1205 
1206       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1207       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1208       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1209 
1210       // Handle constrained floating-point operations of fp128
1211       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1212       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1213       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1214       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1215       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1216       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1217       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1218       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1219       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1220       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1221       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1222       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1223       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1224       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1225       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1226       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1227       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1228       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1229       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1230       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1231     } else if (Subtarget.hasVSX()) {
1232       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1233       setOperationAction(ISD::STORE, MVT::f128, Promote);
1234 
1235       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1236       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1237 
1238       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1239       // fp_to_uint and int_to_fp.
1240       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1241       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1242 
1243       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1244       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1245       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1246       setOperationAction(ISD::FABS, MVT::f128, Expand);
1247       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1248       setOperationAction(ISD::FMA, MVT::f128, Expand);
1249       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1250 
1251       // Expand the fp_extend if the target type is fp128.
1252       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1253       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1254 
1255       // Expand the fp_round if the source type is fp128.
1256       for (MVT VT : {MVT::f32, MVT::f64}) {
1257         setOperationAction(ISD::FP_ROUND, VT, Custom);
1258         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1259       }
1260 
1261       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1262       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1263       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1264       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1265 
1266       // Lower following f128 select_cc pattern:
1267       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1268       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1269 
1270       // We need to handle f128 SELECT_CC with integer result type.
1271       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1272       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1273     }
1274 
1275     if (Subtarget.hasP9Altivec()) {
1276       if (Subtarget.isISA3_1()) {
1277         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
1278         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
1279         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
1280         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
1281       } else {
1282         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1283         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1284       }
1285       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1286       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1287       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1288       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1289       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1290       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1291       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1292     }
1293 
1294     if (Subtarget.hasP10Vector()) {
1295       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1296     }
1297   }
1298 
1299   if (Subtarget.pairedVectorMemops()) {
1300     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1301     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1302     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1303   }
1304   if (Subtarget.hasMMA()) {
1305     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1306     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1307     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1308     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1309   }
1310 
1311   if (Subtarget.has64BitSupport())
1312     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1313 
1314   if (Subtarget.isISA3_1())
1315     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1316 
1317   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1318 
1319   if (!isPPC64) {
1320     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1321     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1322   }
1323 
1324   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1325     setMaxAtomicSizeInBitsSupported(128);
1326     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1327     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1328     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1329   }
1330 
1331   setBooleanContents(ZeroOrOneBooleanContent);
1332 
1333   if (Subtarget.hasAltivec()) {
1334     // Altivec instructions set fields to all zeros or all ones.
1335     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1336   }
1337 
1338   setLibcallName(RTLIB::MULO_I128, nullptr);
1339   if (!isPPC64) {
1340     // These libcalls are not available in 32-bit.
1341     setLibcallName(RTLIB::SHL_I128, nullptr);
1342     setLibcallName(RTLIB::SRL_I128, nullptr);
1343     setLibcallName(RTLIB::SRA_I128, nullptr);
1344     setLibcallName(RTLIB::MUL_I128, nullptr);
1345     setLibcallName(RTLIB::MULO_I64, nullptr);
1346   }
1347 
1348   if (!isPPC64)
1349     setMaxAtomicSizeInBitsSupported(32);
1350 
1351   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1352 
1353   // We have target-specific dag combine patterns for the following nodes:
1354   setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL,
1355                        ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR});
1356   if (Subtarget.hasFPCVT())
1357     setTargetDAGCombine(ISD::UINT_TO_FP);
1358   setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC});
1359   if (Subtarget.useCRBits())
1360     setTargetDAGCombine(ISD::BRCOND);
1361   setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN,
1362                        ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID});
1363 
1364   setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND});
1365 
1366   setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE});
1367 
1368   if (Subtarget.useCRBits()) {
1369     setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC});
1370   }
1371 
1372   if (Subtarget.hasP9Altivec()) {
1373     setTargetDAGCombine({ISD::ABS, ISD::VSELECT});
1374   }
1375 
1376   setLibcallName(RTLIB::LOG_F128, "logf128");
1377   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1378   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1379   setLibcallName(RTLIB::EXP_F128, "expf128");
1380   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1381   setLibcallName(RTLIB::SIN_F128, "sinf128");
1382   setLibcallName(RTLIB::COS_F128, "cosf128");
1383   setLibcallName(RTLIB::POW_F128, "powf128");
1384   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1385   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1386   setLibcallName(RTLIB::REM_F128, "fmodf128");
1387   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1388   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1389   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1390   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1391   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1392   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1393   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1394   setLibcallName(RTLIB::RINT_F128, "rintf128");
1395   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1396   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1397   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1398   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1399 
1400   // With 32 condition bits, we don't need to sink (and duplicate) compares
1401   // aggressively in CodeGenPrep.
1402   if (Subtarget.useCRBits()) {
1403     setHasMultipleConditionRegisters();
1404     setJumpIsExpensive();
1405   }
1406 
1407   setMinFunctionAlignment(Align(4));
1408 
1409   switch (Subtarget.getCPUDirective()) {
1410   default: break;
1411   case PPC::DIR_970:
1412   case PPC::DIR_A2:
1413   case PPC::DIR_E500:
1414   case PPC::DIR_E500mc:
1415   case PPC::DIR_E5500:
1416   case PPC::DIR_PWR4:
1417   case PPC::DIR_PWR5:
1418   case PPC::DIR_PWR5X:
1419   case PPC::DIR_PWR6:
1420   case PPC::DIR_PWR6X:
1421   case PPC::DIR_PWR7:
1422   case PPC::DIR_PWR8:
1423   case PPC::DIR_PWR9:
1424   case PPC::DIR_PWR10:
1425   case PPC::DIR_PWR_FUTURE:
1426     setPrefLoopAlignment(Align(16));
1427     setPrefFunctionAlignment(Align(16));
1428     break;
1429   }
1430 
1431   if (Subtarget.enableMachineScheduler())
1432     setSchedulingPreference(Sched::Source);
1433   else
1434     setSchedulingPreference(Sched::Hybrid);
1435 
1436   computeRegisterProperties(STI.getRegisterInfo());
1437 
1438   // The Freescale cores do better with aggressive inlining of memcpy and
1439   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1440   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1441       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1442     MaxStoresPerMemset = 32;
1443     MaxStoresPerMemsetOptSize = 16;
1444     MaxStoresPerMemcpy = 32;
1445     MaxStoresPerMemcpyOptSize = 8;
1446     MaxStoresPerMemmove = 32;
1447     MaxStoresPerMemmoveOptSize = 8;
1448   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1449     // The A2 also benefits from (very) aggressive inlining of memcpy and
1450     // friends. The overhead of a the function call, even when warm, can be
1451     // over one hundred cycles.
1452     MaxStoresPerMemset = 128;
1453     MaxStoresPerMemcpy = 128;
1454     MaxStoresPerMemmove = 128;
1455     MaxLoadsPerMemcmp = 128;
1456   } else {
1457     MaxLoadsPerMemcmp = 8;
1458     MaxLoadsPerMemcmpOptSize = 4;
1459   }
1460 
1461   IsStrictFPEnabled = true;
1462 
1463   // Let the subtarget (CPU) decide if a predictable select is more expensive
1464   // than the corresponding branch. This information is used in CGP to decide
1465   // when to convert selects into branches.
1466   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1467 }
1468 
1469 // *********************************** NOTE ************************************
1470 // For selecting load and store instructions, the addressing modes are defined
1471 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1472 // patterns to match the load the store instructions.
1473 //
1474 // The TD definitions for the addressing modes correspond to their respective
1475 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1476 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1477 // address mode flags of a particular node. Afterwards, the computed address
1478 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1479 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1480 // accordingly, based on the preferred addressing mode.
1481 //
1482 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1483 // MemOpFlags contains all the possible flags that can be used to compute the
1484 // optimal addressing mode for load and store instructions.
1485 // AddrMode contains all the possible load and store addressing modes available
1486 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1487 //
1488 // When adding new load and store instructions, it is possible that new address
1489 // flags may need to be added into MemOpFlags, and a new addressing mode will
1490 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1491 // of the minimal and main distinguishing address flags for the new load/store
1492 // instructions) will need to be added into initializeAddrModeMap() below.
1493 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1494 // need to be updated to account for selecting the optimal addressing mode.
1495 // *****************************************************************************
1496 /// Initialize the map that relates the different addressing modes of the load
1497 /// and store instructions to a set of flags. This ensures the load/store
1498 /// instruction is correctly matched during instruction selection.
1499 void PPCTargetLowering::initializeAddrModeMap() {
1500   AddrModesMap[PPC::AM_DForm] = {
1501       // LWZ, STW
1502       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1503       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1504       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1505       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1506       // LBZ, LHZ, STB, STH
1507       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1508       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1509       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1510       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1511       // LHA
1512       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1513       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1514       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1515       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1516       // LFS, LFD, STFS, STFD
1517       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1518       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1519       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1520       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1521   };
1522   AddrModesMap[PPC::AM_DSForm] = {
1523       // LWA
1524       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1525       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1526       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1527       // LD, STD
1528       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1529       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1530       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1531       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1532       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1533       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1534       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1535   };
1536   AddrModesMap[PPC::AM_DQForm] = {
1537       // LXV, STXV
1538       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1539       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1540       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1541   };
1542   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1543                                        PPC::MOF_SubtargetP10};
1544   // TODO: Add mapping for quadword load/store.
1545 }
1546 
1547 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1548 /// the desired ByVal argument alignment.
1549 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1550   if (MaxAlign == MaxMaxAlign)
1551     return;
1552   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1553     if (MaxMaxAlign >= 32 &&
1554         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1555       MaxAlign = Align(32);
1556     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1557              MaxAlign < 16)
1558       MaxAlign = Align(16);
1559   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1560     Align EltAlign;
1561     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1562     if (EltAlign > MaxAlign)
1563       MaxAlign = EltAlign;
1564   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1565     for (auto *EltTy : STy->elements()) {
1566       Align EltAlign;
1567       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1568       if (EltAlign > MaxAlign)
1569         MaxAlign = EltAlign;
1570       if (MaxAlign == MaxMaxAlign)
1571         break;
1572     }
1573   }
1574 }
1575 
1576 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1577 /// function arguments in the caller parameter area.
1578 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1579                                                   const DataLayout &DL) const {
1580   // 16byte and wider vectors are passed on 16byte boundary.
1581   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1582   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1583   if (Subtarget.hasAltivec())
1584     getMaxByValAlign(Ty, Alignment, Align(16));
1585   return Alignment.value();
1586 }
1587 
1588 bool PPCTargetLowering::useSoftFloat() const {
1589   return Subtarget.useSoftFloat();
1590 }
1591 
1592 bool PPCTargetLowering::hasSPE() const {
1593   return Subtarget.hasSPE();
1594 }
1595 
1596 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1597   return VT.isScalarInteger();
1598 }
1599 
1600 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1601   switch ((PPCISD::NodeType)Opcode) {
1602   case PPCISD::FIRST_NUMBER:    break;
1603   case PPCISD::FSEL:            return "PPCISD::FSEL";
1604   case PPCISD::XSMAXC:          return "PPCISD::XSMAXC";
1605   case PPCISD::XSMINC:          return "PPCISD::XSMINC";
1606   case PPCISD::FCFID:           return "PPCISD::FCFID";
1607   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1608   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1609   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1610   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1611   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1612   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1613   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1614   case PPCISD::FP_TO_UINT_IN_VSR:
1615                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1616   case PPCISD::FP_TO_SINT_IN_VSR:
1617                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1618   case PPCISD::FRE:             return "PPCISD::FRE";
1619   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1620   case PPCISD::FTSQRT:
1621     return "PPCISD::FTSQRT";
1622   case PPCISD::FSQRT:
1623     return "PPCISD::FSQRT";
1624   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1625   case PPCISD::VPERM:           return "PPCISD::VPERM";
1626   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1627   case PPCISD::XXSPLTI_SP_TO_DP:
1628     return "PPCISD::XXSPLTI_SP_TO_DP";
1629   case PPCISD::XXSPLTI32DX:
1630     return "PPCISD::XXSPLTI32DX";
1631   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1632   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1633   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1634   case PPCISD::CMPB:            return "PPCISD::CMPB";
1635   case PPCISD::Hi:              return "PPCISD::Hi";
1636   case PPCISD::Lo:              return "PPCISD::Lo";
1637   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1638   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1639   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1640   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1641   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1642   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1643   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1644   case PPCISD::SRL:             return "PPCISD::SRL";
1645   case PPCISD::SRA:             return "PPCISD::SRA";
1646   case PPCISD::SHL:             return "PPCISD::SHL";
1647   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1648   case PPCISD::CALL:            return "PPCISD::CALL";
1649   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1650   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1651   case PPCISD::CALL_RM:
1652     return "PPCISD::CALL_RM";
1653   case PPCISD::CALL_NOP_RM:
1654     return "PPCISD::CALL_NOP_RM";
1655   case PPCISD::CALL_NOTOC_RM:
1656     return "PPCISD::CALL_NOTOC_RM";
1657   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1658   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1659   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1660   case PPCISD::BCTRL_RM:
1661     return "PPCISD::BCTRL_RM";
1662   case PPCISD::BCTRL_LOAD_TOC_RM:
1663     return "PPCISD::BCTRL_LOAD_TOC_RM";
1664   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1665   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1666   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1667   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1668   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1669   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1670   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1671   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1672   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1673   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1674   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1675     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1676   case PPCISD::ANDI_rec_1_EQ_BIT:
1677     return "PPCISD::ANDI_rec_1_EQ_BIT";
1678   case PPCISD::ANDI_rec_1_GT_BIT:
1679     return "PPCISD::ANDI_rec_1_GT_BIT";
1680   case PPCISD::VCMP:            return "PPCISD::VCMP";
1681   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1682   case PPCISD::LBRX:            return "PPCISD::LBRX";
1683   case PPCISD::STBRX:           return "PPCISD::STBRX";
1684   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1685   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1686   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1687   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1688   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1689   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1690   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1691   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1692   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1693   case PPCISD::ST_VSR_SCAL_INT:
1694                                 return "PPCISD::ST_VSR_SCAL_INT";
1695   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1696   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1697   case PPCISD::BDZ:             return "PPCISD::BDZ";
1698   case PPCISD::MFFS:            return "PPCISD::MFFS";
1699   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1700   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1701   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1702   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1703   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1704   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1705   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1706   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1707   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1708   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1709   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1710   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1711   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1712   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1713   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1714   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1715   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1716   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1717   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1718   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1719   case PPCISD::PADDI_DTPREL:
1720     return "PPCISD::PADDI_DTPREL";
1721   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1722   case PPCISD::SC:              return "PPCISD::SC";
1723   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1724   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1725   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1726   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1727   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1728   case PPCISD::VABSD:           return "PPCISD::VABSD";
1729   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1730   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1731   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1732   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1733   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1734   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1735   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1736   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1737     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1738   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1739     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1740   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1741   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1742   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1743   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1744   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1745   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1746   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1747   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1748   case PPCISD::STRICT_FADDRTZ:
1749     return "PPCISD::STRICT_FADDRTZ";
1750   case PPCISD::STRICT_FCTIDZ:
1751     return "PPCISD::STRICT_FCTIDZ";
1752   case PPCISD::STRICT_FCTIWZ:
1753     return "PPCISD::STRICT_FCTIWZ";
1754   case PPCISD::STRICT_FCTIDUZ:
1755     return "PPCISD::STRICT_FCTIDUZ";
1756   case PPCISD::STRICT_FCTIWUZ:
1757     return "PPCISD::STRICT_FCTIWUZ";
1758   case PPCISD::STRICT_FCFID:
1759     return "PPCISD::STRICT_FCFID";
1760   case PPCISD::STRICT_FCFIDU:
1761     return "PPCISD::STRICT_FCFIDU";
1762   case PPCISD::STRICT_FCFIDS:
1763     return "PPCISD::STRICT_FCFIDS";
1764   case PPCISD::STRICT_FCFIDUS:
1765     return "PPCISD::STRICT_FCFIDUS";
1766   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1767   }
1768   return nullptr;
1769 }
1770 
1771 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1772                                           EVT VT) const {
1773   if (!VT.isVector())
1774     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1775 
1776   return VT.changeVectorElementTypeToInteger();
1777 }
1778 
1779 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1780   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1781   return true;
1782 }
1783 
1784 //===----------------------------------------------------------------------===//
1785 // Node matching predicates, for use by the tblgen matching code.
1786 //===----------------------------------------------------------------------===//
1787 
1788 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1789 static bool isFloatingPointZero(SDValue Op) {
1790   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1791     return CFP->getValueAPF().isZero();
1792   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1793     // Maybe this has already been legalized into the constant pool?
1794     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1795       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1796         return CFP->getValueAPF().isZero();
1797   }
1798   return false;
1799 }
1800 
1801 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1802 /// true if Op is undef or if it matches the specified value.
1803 static bool isConstantOrUndef(int Op, int Val) {
1804   return Op < 0 || Op == Val;
1805 }
1806 
1807 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1808 /// VPKUHUM instruction.
1809 /// The ShuffleKind distinguishes between big-endian operations with
1810 /// two different inputs (0), either-endian operations with two identical
1811 /// inputs (1), and little-endian operations with two different inputs (2).
1812 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1813 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1814                                SelectionDAG &DAG) {
1815   bool IsLE = DAG.getDataLayout().isLittleEndian();
1816   if (ShuffleKind == 0) {
1817     if (IsLE)
1818       return false;
1819     for (unsigned i = 0; i != 16; ++i)
1820       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1821         return false;
1822   } else if (ShuffleKind == 2) {
1823     if (!IsLE)
1824       return false;
1825     for (unsigned i = 0; i != 16; ++i)
1826       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1827         return false;
1828   } else if (ShuffleKind == 1) {
1829     unsigned j = IsLE ? 0 : 1;
1830     for (unsigned i = 0; i != 8; ++i)
1831       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1832           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1833         return false;
1834   }
1835   return true;
1836 }
1837 
1838 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1839 /// VPKUWUM instruction.
1840 /// The ShuffleKind distinguishes between big-endian operations with
1841 /// two different inputs (0), either-endian operations with two identical
1842 /// inputs (1), and little-endian operations with two different inputs (2).
1843 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1844 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1845                                SelectionDAG &DAG) {
1846   bool IsLE = DAG.getDataLayout().isLittleEndian();
1847   if (ShuffleKind == 0) {
1848     if (IsLE)
1849       return false;
1850     for (unsigned i = 0; i != 16; i += 2)
1851       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1852           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1853         return false;
1854   } else if (ShuffleKind == 2) {
1855     if (!IsLE)
1856       return false;
1857     for (unsigned i = 0; i != 16; i += 2)
1858       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1859           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1860         return false;
1861   } else if (ShuffleKind == 1) {
1862     unsigned j = IsLE ? 0 : 2;
1863     for (unsigned i = 0; i != 8; i += 2)
1864       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1865           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1866           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1867           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1868         return false;
1869   }
1870   return true;
1871 }
1872 
1873 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1874 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1875 /// current subtarget.
1876 ///
1877 /// The ShuffleKind distinguishes between big-endian operations with
1878 /// two different inputs (0), either-endian operations with two identical
1879 /// inputs (1), and little-endian operations with two different inputs (2).
1880 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1881 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1882                                SelectionDAG &DAG) {
1883   const PPCSubtarget& Subtarget =
1884       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1885   if (!Subtarget.hasP8Vector())
1886     return false;
1887 
1888   bool IsLE = DAG.getDataLayout().isLittleEndian();
1889   if (ShuffleKind == 0) {
1890     if (IsLE)
1891       return false;
1892     for (unsigned i = 0; i != 16; i += 4)
1893       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1894           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1895           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1896           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1897         return false;
1898   } else if (ShuffleKind == 2) {
1899     if (!IsLE)
1900       return false;
1901     for (unsigned i = 0; i != 16; i += 4)
1902       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1903           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1904           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1905           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1906         return false;
1907   } else if (ShuffleKind == 1) {
1908     unsigned j = IsLE ? 0 : 4;
1909     for (unsigned i = 0; i != 8; i += 4)
1910       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1911           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1912           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1913           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1914           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1915           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1916           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1917           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1918         return false;
1919   }
1920   return true;
1921 }
1922 
1923 /// isVMerge - Common function, used to match vmrg* shuffles.
1924 ///
1925 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1926                      unsigned LHSStart, unsigned RHSStart) {
1927   if (N->getValueType(0) != MVT::v16i8)
1928     return false;
1929   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1930          "Unsupported merge size!");
1931 
1932   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1933     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1934       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1935                              LHSStart+j+i*UnitSize) ||
1936           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1937                              RHSStart+j+i*UnitSize))
1938         return false;
1939     }
1940   return true;
1941 }
1942 
1943 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1944 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1945 /// The ShuffleKind distinguishes between big-endian merges with two
1946 /// different inputs (0), either-endian merges with two identical inputs (1),
1947 /// and little-endian merges with two different inputs (2).  For the latter,
1948 /// the input operands are swapped (see PPCInstrAltivec.td).
1949 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1950                              unsigned ShuffleKind, SelectionDAG &DAG) {
1951   if (DAG.getDataLayout().isLittleEndian()) {
1952     if (ShuffleKind == 1) // unary
1953       return isVMerge(N, UnitSize, 0, 0);
1954     else if (ShuffleKind == 2) // swapped
1955       return isVMerge(N, UnitSize, 0, 16);
1956     else
1957       return false;
1958   } else {
1959     if (ShuffleKind == 1) // unary
1960       return isVMerge(N, UnitSize, 8, 8);
1961     else if (ShuffleKind == 0) // normal
1962       return isVMerge(N, UnitSize, 8, 24);
1963     else
1964       return false;
1965   }
1966 }
1967 
1968 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1969 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1970 /// The ShuffleKind distinguishes between big-endian merges with two
1971 /// different inputs (0), either-endian merges with two identical inputs (1),
1972 /// and little-endian merges with two different inputs (2).  For the latter,
1973 /// the input operands are swapped (see PPCInstrAltivec.td).
1974 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1975                              unsigned ShuffleKind, SelectionDAG &DAG) {
1976   if (DAG.getDataLayout().isLittleEndian()) {
1977     if (ShuffleKind == 1) // unary
1978       return isVMerge(N, UnitSize, 8, 8);
1979     else if (ShuffleKind == 2) // swapped
1980       return isVMerge(N, UnitSize, 8, 24);
1981     else
1982       return false;
1983   } else {
1984     if (ShuffleKind == 1) // unary
1985       return isVMerge(N, UnitSize, 0, 0);
1986     else if (ShuffleKind == 0) // normal
1987       return isVMerge(N, UnitSize, 0, 16);
1988     else
1989       return false;
1990   }
1991 }
1992 
1993 /**
1994  * Common function used to match vmrgew and vmrgow shuffles
1995  *
1996  * The indexOffset determines whether to look for even or odd words in
1997  * the shuffle mask. This is based on the of the endianness of the target
1998  * machine.
1999  *   - Little Endian:
2000  *     - Use offset of 0 to check for odd elements
2001  *     - Use offset of 4 to check for even elements
2002  *   - Big Endian:
2003  *     - Use offset of 0 to check for even elements
2004  *     - Use offset of 4 to check for odd elements
2005  * A detailed description of the vector element ordering for little endian and
2006  * big endian can be found at
2007  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2008  * Targeting your applications - what little endian and big endian IBM XL C/C++
2009  * compiler differences mean to you
2010  *
2011  * The mask to the shuffle vector instruction specifies the indices of the
2012  * elements from the two input vectors to place in the result. The elements are
2013  * numbered in array-access order, starting with the first vector. These vectors
2014  * are always of type v16i8, thus each vector will contain 16 elements of size
2015  * 8. More info on the shuffle vector can be found in the
2016  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2017  * Language Reference.
2018  *
2019  * The RHSStartValue indicates whether the same input vectors are used (unary)
2020  * or two different input vectors are used, based on the following:
2021  *   - If the instruction uses the same vector for both inputs, the range of the
2022  *     indices will be 0 to 15. In this case, the RHSStart value passed should
2023  *     be 0.
2024  *   - If the instruction has two different vectors then the range of the
2025  *     indices will be 0 to 31. In this case, the RHSStart value passed should
2026  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
2027  *     to 31 specify elements in the second vector).
2028  *
2029  * \param[in] N The shuffle vector SD Node to analyze
2030  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2031  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2032  * vector to the shuffle_vector instruction
2033  * \return true iff this shuffle vector represents an even or odd word merge
2034  */
2035 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2036                      unsigned RHSStartValue) {
2037   if (N->getValueType(0) != MVT::v16i8)
2038     return false;
2039 
2040   for (unsigned i = 0; i < 2; ++i)
2041     for (unsigned j = 0; j < 4; ++j)
2042       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2043                              i*RHSStartValue+j+IndexOffset) ||
2044           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2045                              i*RHSStartValue+j+IndexOffset+8))
2046         return false;
2047   return true;
2048 }
2049 
2050 /**
2051  * Determine if the specified shuffle mask is suitable for the vmrgew or
2052  * vmrgow instructions.
2053  *
2054  * \param[in] N The shuffle vector SD Node to analyze
2055  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2056  * \param[in] ShuffleKind Identify the type of merge:
2057  *   - 0 = big-endian merge with two different inputs;
2058  *   - 1 = either-endian merge with two identical inputs;
2059  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2060  *     little-endian merges).
2061  * \param[in] DAG The current SelectionDAG
2062  * \return true iff this shuffle mask
2063  */
2064 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2065                               unsigned ShuffleKind, SelectionDAG &DAG) {
2066   if (DAG.getDataLayout().isLittleEndian()) {
2067     unsigned indexOffset = CheckEven ? 4 : 0;
2068     if (ShuffleKind == 1) // Unary
2069       return isVMerge(N, indexOffset, 0);
2070     else if (ShuffleKind == 2) // swapped
2071       return isVMerge(N, indexOffset, 16);
2072     else
2073       return false;
2074   }
2075   else {
2076     unsigned indexOffset = CheckEven ? 0 : 4;
2077     if (ShuffleKind == 1) // Unary
2078       return isVMerge(N, indexOffset, 0);
2079     else if (ShuffleKind == 0) // Normal
2080       return isVMerge(N, indexOffset, 16);
2081     else
2082       return false;
2083   }
2084   return false;
2085 }
2086 
2087 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2088 /// amount, otherwise return -1.
2089 /// The ShuffleKind distinguishes between big-endian operations with two
2090 /// different inputs (0), either-endian operations with two identical inputs
2091 /// (1), and little-endian operations with two different inputs (2).  For the
2092 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2093 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2094                              SelectionDAG &DAG) {
2095   if (N->getValueType(0) != MVT::v16i8)
2096     return -1;
2097 
2098   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2099 
2100   // Find the first non-undef value in the shuffle mask.
2101   unsigned i;
2102   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2103     /*search*/;
2104 
2105   if (i == 16) return -1;  // all undef.
2106 
2107   // Otherwise, check to see if the rest of the elements are consecutively
2108   // numbered from this value.
2109   unsigned ShiftAmt = SVOp->getMaskElt(i);
2110   if (ShiftAmt < i) return -1;
2111 
2112   ShiftAmt -= i;
2113   bool isLE = DAG.getDataLayout().isLittleEndian();
2114 
2115   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2116     // Check the rest of the elements to see if they are consecutive.
2117     for (++i; i != 16; ++i)
2118       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2119         return -1;
2120   } else if (ShuffleKind == 1) {
2121     // Check the rest of the elements to see if they are consecutive.
2122     for (++i; i != 16; ++i)
2123       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2124         return -1;
2125   } else
2126     return -1;
2127 
2128   if (isLE)
2129     ShiftAmt = 16 - ShiftAmt;
2130 
2131   return ShiftAmt;
2132 }
2133 
2134 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2135 /// specifies a splat of a single element that is suitable for input to
2136 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2137 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2138   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2139          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2140 
2141   // The consecutive indices need to specify an element, not part of two
2142   // different elements.  So abandon ship early if this isn't the case.
2143   if (N->getMaskElt(0) % EltSize != 0)
2144     return false;
2145 
2146   // This is a splat operation if each element of the permute is the same, and
2147   // if the value doesn't reference the second vector.
2148   unsigned ElementBase = N->getMaskElt(0);
2149 
2150   // FIXME: Handle UNDEF elements too!
2151   if (ElementBase >= 16)
2152     return false;
2153 
2154   // Check that the indices are consecutive, in the case of a multi-byte element
2155   // splatted with a v16i8 mask.
2156   for (unsigned i = 1; i != EltSize; ++i)
2157     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2158       return false;
2159 
2160   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2161     if (N->getMaskElt(i) < 0) continue;
2162     for (unsigned j = 0; j != EltSize; ++j)
2163       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2164         return false;
2165   }
2166   return true;
2167 }
2168 
2169 /// Check that the mask is shuffling N byte elements. Within each N byte
2170 /// element of the mask, the indices could be either in increasing or
2171 /// decreasing order as long as they are consecutive.
2172 /// \param[in] N the shuffle vector SD Node to analyze
2173 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2174 /// Word/DoubleWord/QuadWord).
2175 /// \param[in] StepLen the delta indices number among the N byte element, if
2176 /// the mask is in increasing/decreasing order then it is 1/-1.
2177 /// \return true iff the mask is shuffling N byte elements.
2178 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2179                                    int StepLen) {
2180   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2181          "Unexpected element width.");
2182   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2183 
2184   unsigned NumOfElem = 16 / Width;
2185   unsigned MaskVal[16]; //  Width is never greater than 16
2186   for (unsigned i = 0; i < NumOfElem; ++i) {
2187     MaskVal[0] = N->getMaskElt(i * Width);
2188     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2189       return false;
2190     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2191       return false;
2192     }
2193 
2194     for (unsigned int j = 1; j < Width; ++j) {
2195       MaskVal[j] = N->getMaskElt(i * Width + j);
2196       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2197         return false;
2198       }
2199     }
2200   }
2201 
2202   return true;
2203 }
2204 
2205 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2206                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2207   if (!isNByteElemShuffleMask(N, 4, 1))
2208     return false;
2209 
2210   // Now we look at mask elements 0,4,8,12
2211   unsigned M0 = N->getMaskElt(0) / 4;
2212   unsigned M1 = N->getMaskElt(4) / 4;
2213   unsigned M2 = N->getMaskElt(8) / 4;
2214   unsigned M3 = N->getMaskElt(12) / 4;
2215   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2216   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2217 
2218   // Below, let H and L be arbitrary elements of the shuffle mask
2219   // where H is in the range [4,7] and L is in the range [0,3].
2220   // H, 1, 2, 3 or L, 5, 6, 7
2221   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2222       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2223     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2224     InsertAtByte = IsLE ? 12 : 0;
2225     Swap = M0 < 4;
2226     return true;
2227   }
2228   // 0, H, 2, 3 or 4, L, 6, 7
2229   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2230       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2231     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2232     InsertAtByte = IsLE ? 8 : 4;
2233     Swap = M1 < 4;
2234     return true;
2235   }
2236   // 0, 1, H, 3 or 4, 5, L, 7
2237   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2238       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2239     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2240     InsertAtByte = IsLE ? 4 : 8;
2241     Swap = M2 < 4;
2242     return true;
2243   }
2244   // 0, 1, 2, H or 4, 5, 6, L
2245   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2246       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2247     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2248     InsertAtByte = IsLE ? 0 : 12;
2249     Swap = M3 < 4;
2250     return true;
2251   }
2252 
2253   // If both vector operands for the shuffle are the same vector, the mask will
2254   // contain only elements from the first one and the second one will be undef.
2255   if (N->getOperand(1).isUndef()) {
2256     ShiftElts = 0;
2257     Swap = true;
2258     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2259     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2260       InsertAtByte = IsLE ? 12 : 0;
2261       return true;
2262     }
2263     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2264       InsertAtByte = IsLE ? 8 : 4;
2265       return true;
2266     }
2267     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2268       InsertAtByte = IsLE ? 4 : 8;
2269       return true;
2270     }
2271     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2272       InsertAtByte = IsLE ? 0 : 12;
2273       return true;
2274     }
2275   }
2276 
2277   return false;
2278 }
2279 
2280 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2281                                bool &Swap, bool IsLE) {
2282   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2283   // Ensure each byte index of the word is consecutive.
2284   if (!isNByteElemShuffleMask(N, 4, 1))
2285     return false;
2286 
2287   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2288   unsigned M0 = N->getMaskElt(0) / 4;
2289   unsigned M1 = N->getMaskElt(4) / 4;
2290   unsigned M2 = N->getMaskElt(8) / 4;
2291   unsigned M3 = N->getMaskElt(12) / 4;
2292 
2293   // If both vector operands for the shuffle are the same vector, the mask will
2294   // contain only elements from the first one and the second one will be undef.
2295   if (N->getOperand(1).isUndef()) {
2296     assert(M0 < 4 && "Indexing into an undef vector?");
2297     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2298       return false;
2299 
2300     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2301     Swap = false;
2302     return true;
2303   }
2304 
2305   // Ensure each word index of the ShuffleVector Mask is consecutive.
2306   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2307     return false;
2308 
2309   if (IsLE) {
2310     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2311       // Input vectors don't need to be swapped if the leading element
2312       // of the result is one of the 3 left elements of the second vector
2313       // (or if there is no shift to be done at all).
2314       Swap = false;
2315       ShiftElts = (8 - M0) % 8;
2316     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2317       // Input vectors need to be swapped if the leading element
2318       // of the result is one of the 3 left elements of the first vector
2319       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2320       Swap = true;
2321       ShiftElts = (4 - M0) % 4;
2322     }
2323 
2324     return true;
2325   } else {                                          // BE
2326     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2327       // Input vectors don't need to be swapped if the leading element
2328       // of the result is one of the 4 elements of the first vector.
2329       Swap = false;
2330       ShiftElts = M0;
2331     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2332       // Input vectors need to be swapped if the leading element
2333       // of the result is one of the 4 elements of the right vector.
2334       Swap = true;
2335       ShiftElts = M0 - 4;
2336     }
2337 
2338     return true;
2339   }
2340 }
2341 
2342 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2343   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2344 
2345   if (!isNByteElemShuffleMask(N, Width, -1))
2346     return false;
2347 
2348   for (int i = 0; i < 16; i += Width)
2349     if (N->getMaskElt(i) != i + Width - 1)
2350       return false;
2351 
2352   return true;
2353 }
2354 
2355 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2356   return isXXBRShuffleMaskHelper(N, 2);
2357 }
2358 
2359 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2360   return isXXBRShuffleMaskHelper(N, 4);
2361 }
2362 
2363 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2364   return isXXBRShuffleMaskHelper(N, 8);
2365 }
2366 
2367 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2368   return isXXBRShuffleMaskHelper(N, 16);
2369 }
2370 
2371 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2372 /// if the inputs to the instruction should be swapped and set \p DM to the
2373 /// value for the immediate.
2374 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2375 /// AND element 0 of the result comes from the first input (LE) or second input
2376 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2377 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2378 /// mask.
2379 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2380                                bool &Swap, bool IsLE) {
2381   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2382 
2383   // Ensure each byte index of the double word is consecutive.
2384   if (!isNByteElemShuffleMask(N, 8, 1))
2385     return false;
2386 
2387   unsigned M0 = N->getMaskElt(0) / 8;
2388   unsigned M1 = N->getMaskElt(8) / 8;
2389   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2390 
2391   // If both vector operands for the shuffle are the same vector, the mask will
2392   // contain only elements from the first one and the second one will be undef.
2393   if (N->getOperand(1).isUndef()) {
2394     if ((M0 | M1) < 2) {
2395       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2396       Swap = false;
2397       return true;
2398     } else
2399       return false;
2400   }
2401 
2402   if (IsLE) {
2403     if (M0 > 1 && M1 < 2) {
2404       Swap = false;
2405     } else if (M0 < 2 && M1 > 1) {
2406       M0 = (M0 + 2) % 4;
2407       M1 = (M1 + 2) % 4;
2408       Swap = true;
2409     } else
2410       return false;
2411 
2412     // Note: if control flow comes here that means Swap is already set above
2413     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2414     return true;
2415   } else { // BE
2416     if (M0 < 2 && M1 > 1) {
2417       Swap = false;
2418     } else if (M0 > 1 && M1 < 2) {
2419       M0 = (M0 + 2) % 4;
2420       M1 = (M1 + 2) % 4;
2421       Swap = true;
2422     } else
2423       return false;
2424 
2425     // Note: if control flow comes here that means Swap is already set above
2426     DM = (M0 << 1) + (M1 & 1);
2427     return true;
2428   }
2429 }
2430 
2431 
2432 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2433 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2434 /// elements are counted from the left of the vector register).
2435 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2436                                          SelectionDAG &DAG) {
2437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2438   assert(isSplatShuffleMask(SVOp, EltSize));
2439   if (DAG.getDataLayout().isLittleEndian())
2440     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2441   else
2442     return SVOp->getMaskElt(0) / EltSize;
2443 }
2444 
2445 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2446 /// by using a vspltis[bhw] instruction of the specified element size, return
2447 /// the constant being splatted.  The ByteSize field indicates the number of
2448 /// bytes of each element [124] -> [bhw].
2449 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2450   SDValue OpVal;
2451 
2452   // If ByteSize of the splat is bigger than the element size of the
2453   // build_vector, then we have a case where we are checking for a splat where
2454   // multiple elements of the buildvector are folded together into a single
2455   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2456   unsigned EltSize = 16/N->getNumOperands();
2457   if (EltSize < ByteSize) {
2458     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2459     SDValue UniquedVals[4];
2460     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2461 
2462     // See if all of the elements in the buildvector agree across.
2463     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2464       if (N->getOperand(i).isUndef()) continue;
2465       // If the element isn't a constant, bail fully out.
2466       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2467 
2468       if (!UniquedVals[i&(Multiple-1)].getNode())
2469         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2470       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2471         return SDValue();  // no match.
2472     }
2473 
2474     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2475     // either constant or undef values that are identical for each chunk.  See
2476     // if these chunks can form into a larger vspltis*.
2477 
2478     // Check to see if all of the leading entries are either 0 or -1.  If
2479     // neither, then this won't fit into the immediate field.
2480     bool LeadingZero = true;
2481     bool LeadingOnes = true;
2482     for (unsigned i = 0; i != Multiple-1; ++i) {
2483       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2484 
2485       LeadingZero &= isNullConstant(UniquedVals[i]);
2486       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2487     }
2488     // Finally, check the least significant entry.
2489     if (LeadingZero) {
2490       if (!UniquedVals[Multiple-1].getNode())
2491         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2492       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2493       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2494         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2495     }
2496     if (LeadingOnes) {
2497       if (!UniquedVals[Multiple-1].getNode())
2498         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2499       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2500       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2501         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2502     }
2503 
2504     return SDValue();
2505   }
2506 
2507   // Check to see if this buildvec has a single non-undef value in its elements.
2508   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2509     if (N->getOperand(i).isUndef()) continue;
2510     if (!OpVal.getNode())
2511       OpVal = N->getOperand(i);
2512     else if (OpVal != N->getOperand(i))
2513       return SDValue();
2514   }
2515 
2516   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2517 
2518   unsigned ValSizeInBytes = EltSize;
2519   uint64_t Value = 0;
2520   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2521     Value = CN->getZExtValue();
2522   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2523     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2524     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2525   }
2526 
2527   // If the splat value is larger than the element value, then we can never do
2528   // this splat.  The only case that we could fit the replicated bits into our
2529   // immediate field for would be zero, and we prefer to use vxor for it.
2530   if (ValSizeInBytes < ByteSize) return SDValue();
2531 
2532   // If the element value is larger than the splat value, check if it consists
2533   // of a repeated bit pattern of size ByteSize.
2534   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2535     return SDValue();
2536 
2537   // Properly sign extend the value.
2538   int MaskVal = SignExtend32(Value, ByteSize * 8);
2539 
2540   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2541   if (MaskVal == 0) return SDValue();
2542 
2543   // Finally, if this value fits in a 5 bit sext field, return it
2544   if (SignExtend32<5>(MaskVal) == MaskVal)
2545     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2546   return SDValue();
2547 }
2548 
2549 //===----------------------------------------------------------------------===//
2550 //  Addressing Mode Selection
2551 //===----------------------------------------------------------------------===//
2552 
2553 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2554 /// or 64-bit immediate, and if the value can be accurately represented as a
2555 /// sign extension from a 16-bit value.  If so, this returns true and the
2556 /// immediate.
2557 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2558   if (!isa<ConstantSDNode>(N))
2559     return false;
2560 
2561   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2562   if (N->getValueType(0) == MVT::i32)
2563     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2564   else
2565     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2566 }
2567 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2568   return isIntS16Immediate(Op.getNode(), Imm);
2569 }
2570 
2571 /// Used when computing address flags for selecting loads and stores.
2572 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2573 /// An OR of two provably disjoint values is equivalent to an ADD.
2574 /// Most PPC load/store instructions compute the effective address as a sum,
2575 /// so doing this conversion is useful.
2576 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2577   if (N.getOpcode() != ISD::OR)
2578     return false;
2579   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2580   if (!LHSKnown.Zero.getBoolValue())
2581     return false;
2582   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2583   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2584 }
2585 
2586 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2587 /// be represented as an indexed [r+r] operation.
2588 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2589                                                SDValue &Index,
2590                                                SelectionDAG &DAG) const {
2591   for (SDNode *U : N->uses()) {
2592     if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2593       if (Memop->getMemoryVT() == MVT::f64) {
2594           Base = N.getOperand(0);
2595           Index = N.getOperand(1);
2596           return true;
2597       }
2598     }
2599   }
2600   return false;
2601 }
2602 
2603 /// isIntS34Immediate - This method tests if value of node given can be
2604 /// accurately represented as a sign extension from a 34-bit value.  If so,
2605 /// this returns true and the immediate.
2606 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2607   if (!isa<ConstantSDNode>(N))
2608     return false;
2609 
2610   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2611   return isInt<34>(Imm);
2612 }
2613 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2614   return isIntS34Immediate(Op.getNode(), Imm);
2615 }
2616 
2617 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2618 /// can be represented as an indexed [r+r] operation.  Returns false if it
2619 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2620 /// non-zero and N can be represented by a base register plus a signed 16-bit
2621 /// displacement, make a more precise judgement by checking (displacement % \p
2622 /// EncodingAlignment).
2623 bool PPCTargetLowering::SelectAddressRegReg(
2624     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2625     MaybeAlign EncodingAlignment) const {
2626   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2627   // a [pc+imm].
2628   if (SelectAddressPCRel(N, Base))
2629     return false;
2630 
2631   int16_t Imm = 0;
2632   if (N.getOpcode() == ISD::ADD) {
2633     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2634     // SPE load/store can only handle 8-bit offsets.
2635     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2636         return true;
2637     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2638         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2639       return false; // r+i
2640     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2641       return false;    // r+i
2642 
2643     Base = N.getOperand(0);
2644     Index = N.getOperand(1);
2645     return true;
2646   } else if (N.getOpcode() == ISD::OR) {
2647     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2648         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2649       return false; // r+i can fold it if we can.
2650 
2651     // If this is an or of disjoint bitfields, we can codegen this as an add
2652     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2653     // disjoint.
2654     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2655 
2656     if (LHSKnown.Zero.getBoolValue()) {
2657       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2658       // If all of the bits are known zero on the LHS or RHS, the add won't
2659       // carry.
2660       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2661         Base = N.getOperand(0);
2662         Index = N.getOperand(1);
2663         return true;
2664       }
2665     }
2666   }
2667 
2668   return false;
2669 }
2670 
2671 // If we happen to be doing an i64 load or store into a stack slot that has
2672 // less than a 4-byte alignment, then the frame-index elimination may need to
2673 // use an indexed load or store instruction (because the offset may not be a
2674 // multiple of 4). The extra register needed to hold the offset comes from the
2675 // register scavenger, and it is possible that the scavenger will need to use
2676 // an emergency spill slot. As a result, we need to make sure that a spill slot
2677 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2678 // stack slot.
2679 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2680   // FIXME: This does not handle the LWA case.
2681   if (VT != MVT::i64)
2682     return;
2683 
2684   // NOTE: We'll exclude negative FIs here, which come from argument
2685   // lowering, because there are no known test cases triggering this problem
2686   // using packed structures (or similar). We can remove this exclusion if
2687   // we find such a test case. The reason why this is so test-case driven is
2688   // because this entire 'fixup' is only to prevent crashes (from the
2689   // register scavenger) on not-really-valid inputs. For example, if we have:
2690   //   %a = alloca i1
2691   //   %b = bitcast i1* %a to i64*
2692   //   store i64* a, i64 b
2693   // then the store should really be marked as 'align 1', but is not. If it
2694   // were marked as 'align 1' then the indexed form would have been
2695   // instruction-selected initially, and the problem this 'fixup' is preventing
2696   // won't happen regardless.
2697   if (FrameIdx < 0)
2698     return;
2699 
2700   MachineFunction &MF = DAG.getMachineFunction();
2701   MachineFrameInfo &MFI = MF.getFrameInfo();
2702 
2703   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2704     return;
2705 
2706   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2707   FuncInfo->setHasNonRISpills();
2708 }
2709 
2710 /// Returns true if the address N can be represented by a base register plus
2711 /// a signed 16-bit displacement [r+imm], and if it is not better
2712 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2713 /// displacements that are multiples of that value.
2714 bool PPCTargetLowering::SelectAddressRegImm(
2715     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2716     MaybeAlign EncodingAlignment) const {
2717   // FIXME dl should come from parent load or store, not from address
2718   SDLoc dl(N);
2719 
2720   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2721   // a [pc+imm].
2722   if (SelectAddressPCRel(N, Base))
2723     return false;
2724 
2725   // If this can be more profitably realized as r+r, fail.
2726   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2727     return false;
2728 
2729   if (N.getOpcode() == ISD::ADD) {
2730     int16_t imm = 0;
2731     if (isIntS16Immediate(N.getOperand(1), imm) &&
2732         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2733       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2734       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2735         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2736         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2737       } else {
2738         Base = N.getOperand(0);
2739       }
2740       return true; // [r+i]
2741     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2742       // Match LOAD (ADD (X, Lo(G))).
2743       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2744              && "Cannot handle constant offsets yet!");
2745       Disp = N.getOperand(1).getOperand(0);  // The global address.
2746       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2747              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2748              Disp.getOpcode() == ISD::TargetConstantPool ||
2749              Disp.getOpcode() == ISD::TargetJumpTable);
2750       Base = N.getOperand(0);
2751       return true;  // [&g+r]
2752     }
2753   } else if (N.getOpcode() == ISD::OR) {
2754     int16_t imm = 0;
2755     if (isIntS16Immediate(N.getOperand(1), imm) &&
2756         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2757       // If this is an or of disjoint bitfields, we can codegen this as an add
2758       // (for better address arithmetic) if the LHS and RHS of the OR are
2759       // provably disjoint.
2760       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2761 
2762       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2763         // If all of the bits are known zero on the LHS or RHS, the add won't
2764         // carry.
2765         if (FrameIndexSDNode *FI =
2766               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2767           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2768           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2769         } else {
2770           Base = N.getOperand(0);
2771         }
2772         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2773         return true;
2774       }
2775     }
2776   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2777     // Loading from a constant address.
2778 
2779     // If this address fits entirely in a 16-bit sext immediate field, codegen
2780     // this as "d, 0"
2781     int16_t Imm;
2782     if (isIntS16Immediate(CN, Imm) &&
2783         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2784       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2785       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2786                              CN->getValueType(0));
2787       return true;
2788     }
2789 
2790     // Handle 32-bit sext immediates with LIS + addr mode.
2791     if ((CN->getValueType(0) == MVT::i32 ||
2792          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2793         (!EncodingAlignment ||
2794          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2795       int Addr = (int)CN->getZExtValue();
2796 
2797       // Otherwise, break this down into an LIS + disp.
2798       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2799 
2800       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2801                                    MVT::i32);
2802       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2803       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2804       return true;
2805     }
2806   }
2807 
2808   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2809   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2810     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2811     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2812   } else
2813     Base = N;
2814   return true;      // [r+0]
2815 }
2816 
2817 /// Similar to the 16-bit case but for instructions that take a 34-bit
2818 /// displacement field (prefixed loads/stores).
2819 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2820                                               SDValue &Base,
2821                                               SelectionDAG &DAG) const {
2822   // Only on 64-bit targets.
2823   if (N.getValueType() != MVT::i64)
2824     return false;
2825 
2826   SDLoc dl(N);
2827   int64_t Imm = 0;
2828 
2829   if (N.getOpcode() == ISD::ADD) {
2830     if (!isIntS34Immediate(N.getOperand(1), Imm))
2831       return false;
2832     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2833     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2834       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2835     else
2836       Base = N.getOperand(0);
2837     return true;
2838   }
2839 
2840   if (N.getOpcode() == ISD::OR) {
2841     if (!isIntS34Immediate(N.getOperand(1), Imm))
2842       return false;
2843     // If this is an or of disjoint bitfields, we can codegen this as an add
2844     // (for better address arithmetic) if the LHS and RHS of the OR are
2845     // provably disjoint.
2846     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2847     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2848       return false;
2849     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2850       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2851     else
2852       Base = N.getOperand(0);
2853     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2854     return true;
2855   }
2856 
2857   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2858     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2859     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2860     return true;
2861   }
2862 
2863   return false;
2864 }
2865 
2866 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2867 /// represented as an indexed [r+r] operation.
2868 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2869                                                 SDValue &Index,
2870                                                 SelectionDAG &DAG) const {
2871   // Check to see if we can easily represent this as an [r+r] address.  This
2872   // will fail if it thinks that the address is more profitably represented as
2873   // reg+imm, e.g. where imm = 0.
2874   if (SelectAddressRegReg(N, Base, Index, DAG))
2875     return true;
2876 
2877   // If the address is the result of an add, we will utilize the fact that the
2878   // address calculation includes an implicit add.  However, we can reduce
2879   // register pressure if we do not materialize a constant just for use as the
2880   // index register.  We only get rid of the add if it is not an add of a
2881   // value and a 16-bit signed constant and both have a single use.
2882   int16_t imm = 0;
2883   if (N.getOpcode() == ISD::ADD &&
2884       (!isIntS16Immediate(N.getOperand(1), imm) ||
2885        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2886     Base = N.getOperand(0);
2887     Index = N.getOperand(1);
2888     return true;
2889   }
2890 
2891   // Otherwise, do it the hard way, using R0 as the base register.
2892   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2893                          N.getValueType());
2894   Index = N;
2895   return true;
2896 }
2897 
2898 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2899   Ty *PCRelCand = dyn_cast<Ty>(N);
2900   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2901 }
2902 
2903 /// Returns true if this address is a PC Relative address.
2904 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2905 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2906 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2907   // This is a materialize PC Relative node. Always select this as PC Relative.
2908   Base = N;
2909   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2910     return true;
2911   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2912       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2913       isValidPCRelNode<JumpTableSDNode>(N) ||
2914       isValidPCRelNode<BlockAddressSDNode>(N))
2915     return true;
2916   return false;
2917 }
2918 
2919 /// Returns true if we should use a direct load into vector instruction
2920 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2921 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2922 
2923   // If there are any other uses other than scalar to vector, then we should
2924   // keep it as a scalar load -> direct move pattern to prevent multiple
2925   // loads.
2926   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2927   if (!LD)
2928     return false;
2929 
2930   EVT MemVT = LD->getMemoryVT();
2931   if (!MemVT.isSimple())
2932     return false;
2933   switch(MemVT.getSimpleVT().SimpleTy) {
2934   case MVT::i64:
2935     break;
2936   case MVT::i32:
2937     if (!ST.hasP8Vector())
2938       return false;
2939     break;
2940   case MVT::i16:
2941   case MVT::i8:
2942     if (!ST.hasP9Vector())
2943       return false;
2944     break;
2945   default:
2946     return false;
2947   }
2948 
2949   SDValue LoadedVal(N, 0);
2950   if (!LoadedVal.hasOneUse())
2951     return false;
2952 
2953   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2954        UI != UE; ++UI)
2955     if (UI.getUse().get().getResNo() == 0 &&
2956         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2957         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2958       return false;
2959 
2960   return true;
2961 }
2962 
2963 /// getPreIndexedAddressParts - returns true by value, base pointer and
2964 /// offset pointer and addressing mode by reference if the node's address
2965 /// can be legally represented as pre-indexed load / store address.
2966 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2967                                                   SDValue &Offset,
2968                                                   ISD::MemIndexedMode &AM,
2969                                                   SelectionDAG &DAG) const {
2970   if (DisablePPCPreinc) return false;
2971 
2972   bool isLoad = true;
2973   SDValue Ptr;
2974   EVT VT;
2975   unsigned Alignment;
2976   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2977     Ptr = LD->getBasePtr();
2978     VT = LD->getMemoryVT();
2979     Alignment = LD->getAlignment();
2980   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2981     Ptr = ST->getBasePtr();
2982     VT  = ST->getMemoryVT();
2983     Alignment = ST->getAlignment();
2984     isLoad = false;
2985   } else
2986     return false;
2987 
2988   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2989   // instructions because we can fold these into a more efficient instruction
2990   // instead, (such as LXSD).
2991   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2992     return false;
2993   }
2994 
2995   // PowerPC doesn't have preinc load/store instructions for vectors
2996   if (VT.isVector())
2997     return false;
2998 
2999   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3000     // Common code will reject creating a pre-inc form if the base pointer
3001     // is a frame index, or if N is a store and the base pointer is either
3002     // the same as or a predecessor of the value being stored.  Check for
3003     // those situations here, and try with swapped Base/Offset instead.
3004     bool Swap = false;
3005 
3006     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3007       Swap = true;
3008     else if (!isLoad) {
3009       SDValue Val = cast<StoreSDNode>(N)->getValue();
3010       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3011         Swap = true;
3012     }
3013 
3014     if (Swap)
3015       std::swap(Base, Offset);
3016 
3017     AM = ISD::PRE_INC;
3018     return true;
3019   }
3020 
3021   // LDU/STU can only handle immediates that are a multiple of 4.
3022   if (VT != MVT::i64) {
3023     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
3024       return false;
3025   } else {
3026     // LDU/STU need an address with at least 4-byte alignment.
3027     if (Alignment < 4)
3028       return false;
3029 
3030     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3031       return false;
3032   }
3033 
3034   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3035     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3036     // sext i32 to i64 when addr mode is r+i.
3037     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3038         LD->getExtensionType() == ISD::SEXTLOAD &&
3039         isa<ConstantSDNode>(Offset))
3040       return false;
3041   }
3042 
3043   AM = ISD::PRE_INC;
3044   return true;
3045 }
3046 
3047 //===----------------------------------------------------------------------===//
3048 //  LowerOperation implementation
3049 //===----------------------------------------------------------------------===//
3050 
3051 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3052 /// and LoOpFlags to the target MO flags.
3053 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3054                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3055                                const GlobalValue *GV = nullptr) {
3056   HiOpFlags = PPCII::MO_HA;
3057   LoOpFlags = PPCII::MO_LO;
3058 
3059   // Don't use the pic base if not in PIC relocation model.
3060   if (IsPIC) {
3061     HiOpFlags |= PPCII::MO_PIC_FLAG;
3062     LoOpFlags |= PPCII::MO_PIC_FLAG;
3063   }
3064 }
3065 
3066 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3067                              SelectionDAG &DAG) {
3068   SDLoc DL(HiPart);
3069   EVT PtrVT = HiPart.getValueType();
3070   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3071 
3072   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3073   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3074 
3075   // With PIC, the first instruction is actually "GR+hi(&G)".
3076   if (isPIC)
3077     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3078                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3079 
3080   // Generate non-pic code that has direct accesses to the constant pool.
3081   // The address of the global is just (hi(&g)+lo(&g)).
3082   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3083 }
3084 
3085 static void setUsesTOCBasePtr(MachineFunction &MF) {
3086   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3087   FuncInfo->setUsesTOCBasePtr();
3088 }
3089 
3090 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3091   setUsesTOCBasePtr(DAG.getMachineFunction());
3092 }
3093 
3094 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3095                                        SDValue GA) const {
3096   const bool Is64Bit = Subtarget.isPPC64();
3097   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3098   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3099                         : Subtarget.isAIXABI()
3100                               ? DAG.getRegister(PPC::R2, VT)
3101                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3102   SDValue Ops[] = { GA, Reg };
3103   return DAG.getMemIntrinsicNode(
3104       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3105       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3106       MachineMemOperand::MOLoad);
3107 }
3108 
3109 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3110                                              SelectionDAG &DAG) const {
3111   EVT PtrVT = Op.getValueType();
3112   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3113   const Constant *C = CP->getConstVal();
3114 
3115   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3116   // The actual address of the GlobalValue is stored in the TOC.
3117   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3118     if (Subtarget.isUsingPCRelativeCalls()) {
3119       SDLoc DL(CP);
3120       EVT Ty = getPointerTy(DAG.getDataLayout());
3121       SDValue ConstPool = DAG.getTargetConstantPool(
3122           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3123       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3124     }
3125     setUsesTOCBasePtr(DAG);
3126     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3127     return getTOCEntry(DAG, SDLoc(CP), GA);
3128   }
3129 
3130   unsigned MOHiFlag, MOLoFlag;
3131   bool IsPIC = isPositionIndependent();
3132   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3133 
3134   if (IsPIC && Subtarget.isSVR4ABI()) {
3135     SDValue GA =
3136         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3137     return getTOCEntry(DAG, SDLoc(CP), GA);
3138   }
3139 
3140   SDValue CPIHi =
3141       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3142   SDValue CPILo =
3143       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3144   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3145 }
3146 
3147 // For 64-bit PowerPC, prefer the more compact relative encodings.
3148 // This trades 32 bits per jump table entry for one or two instructions
3149 // on the jump site.
3150 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3151   if (isJumpTableRelative())
3152     return MachineJumpTableInfo::EK_LabelDifference32;
3153 
3154   return TargetLowering::getJumpTableEncoding();
3155 }
3156 
3157 bool PPCTargetLowering::isJumpTableRelative() const {
3158   if (UseAbsoluteJumpTables)
3159     return false;
3160   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3161     return true;
3162   return TargetLowering::isJumpTableRelative();
3163 }
3164 
3165 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3166                                                     SelectionDAG &DAG) const {
3167   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3168     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3169 
3170   switch (getTargetMachine().getCodeModel()) {
3171   case CodeModel::Small:
3172   case CodeModel::Medium:
3173     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3174   default:
3175     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3176                        getPointerTy(DAG.getDataLayout()));
3177   }
3178 }
3179 
3180 const MCExpr *
3181 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3182                                                 unsigned JTI,
3183                                                 MCContext &Ctx) const {
3184   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3185     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3186 
3187   switch (getTargetMachine().getCodeModel()) {
3188   case CodeModel::Small:
3189   case CodeModel::Medium:
3190     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3191   default:
3192     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3193   }
3194 }
3195 
3196 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3197   EVT PtrVT = Op.getValueType();
3198   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3199 
3200   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3201   if (Subtarget.isUsingPCRelativeCalls()) {
3202     SDLoc DL(JT);
3203     EVT Ty = getPointerTy(DAG.getDataLayout());
3204     SDValue GA =
3205         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3206     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3207     return MatAddr;
3208   }
3209 
3210   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3211   // The actual address of the GlobalValue is stored in the TOC.
3212   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3213     setUsesTOCBasePtr(DAG);
3214     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3215     return getTOCEntry(DAG, SDLoc(JT), GA);
3216   }
3217 
3218   unsigned MOHiFlag, MOLoFlag;
3219   bool IsPIC = isPositionIndependent();
3220   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3221 
3222   if (IsPIC && Subtarget.isSVR4ABI()) {
3223     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3224                                         PPCII::MO_PIC_FLAG);
3225     return getTOCEntry(DAG, SDLoc(GA), GA);
3226   }
3227 
3228   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3229   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3230   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3231 }
3232 
3233 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3234                                              SelectionDAG &DAG) const {
3235   EVT PtrVT = Op.getValueType();
3236   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3237   const BlockAddress *BA = BASDN->getBlockAddress();
3238 
3239   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3240   if (Subtarget.isUsingPCRelativeCalls()) {
3241     SDLoc DL(BASDN);
3242     EVT Ty = getPointerTy(DAG.getDataLayout());
3243     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3244                                            PPCII::MO_PCREL_FLAG);
3245     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3246     return MatAddr;
3247   }
3248 
3249   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3250   // The actual BlockAddress is stored in the TOC.
3251   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3252     setUsesTOCBasePtr(DAG);
3253     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3254     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3255   }
3256 
3257   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3258   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3259     return getTOCEntry(
3260         DAG, SDLoc(BASDN),
3261         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3262 
3263   unsigned MOHiFlag, MOLoFlag;
3264   bool IsPIC = isPositionIndependent();
3265   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3266   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3267   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3268   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3269 }
3270 
3271 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3272                                               SelectionDAG &DAG) const {
3273   if (Subtarget.isAIXABI())
3274     return LowerGlobalTLSAddressAIX(Op, DAG);
3275 
3276   return LowerGlobalTLSAddressLinux(Op, DAG);
3277 }
3278 
3279 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3280                                                     SelectionDAG &DAG) const {
3281   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3282 
3283   if (DAG.getTarget().useEmulatedTLS())
3284     report_fatal_error("Emulated TLS is not yet supported on AIX");
3285 
3286   SDLoc dl(GA);
3287   const GlobalValue *GV = GA->getGlobal();
3288   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3289 
3290   // The general-dynamic model is the only access model supported for now, so
3291   // all the GlobalTLSAddress nodes are lowered with this model.
3292   // We need to generate two TOC entries, one for the variable offset, one for
3293   // the region handle. The global address for the TOC entry of the region
3294   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3295   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3296   SDValue VariableOffsetTGA =
3297       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3298   SDValue RegionHandleTGA =
3299       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3300   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3301   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3302   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3303                      RegionHandle);
3304 }
3305 
3306 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3307                                                       SelectionDAG &DAG) const {
3308   // FIXME: TLS addresses currently use medium model code sequences,
3309   // which is the most useful form.  Eventually support for small and
3310   // large models could be added if users need it, at the cost of
3311   // additional complexity.
3312   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3313   if (DAG.getTarget().useEmulatedTLS())
3314     return LowerToTLSEmulatedModel(GA, DAG);
3315 
3316   SDLoc dl(GA);
3317   const GlobalValue *GV = GA->getGlobal();
3318   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3319   bool is64bit = Subtarget.isPPC64();
3320   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3321   PICLevel::Level picLevel = M->getPICLevel();
3322 
3323   const TargetMachine &TM = getTargetMachine();
3324   TLSModel::Model Model = TM.getTLSModel(GV);
3325 
3326   if (Model == TLSModel::LocalExec) {
3327     if (Subtarget.isUsingPCRelativeCalls()) {
3328       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3329       SDValue TGA = DAG.getTargetGlobalAddress(
3330           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3331       SDValue MatAddr =
3332           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3333       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3334     }
3335 
3336     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3337                                                PPCII::MO_TPREL_HA);
3338     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3339                                                PPCII::MO_TPREL_LO);
3340     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3341                              : DAG.getRegister(PPC::R2, MVT::i32);
3342 
3343     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3344     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3345   }
3346 
3347   if (Model == TLSModel::InitialExec) {
3348     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3349     SDValue TGA = DAG.getTargetGlobalAddress(
3350         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3351     SDValue TGATLS = DAG.getTargetGlobalAddress(
3352         GV, dl, PtrVT, 0,
3353         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3354     SDValue TPOffset;
3355     if (IsPCRel) {
3356       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3357       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3358                              MachinePointerInfo());
3359     } else {
3360       SDValue GOTPtr;
3361       if (is64bit) {
3362         setUsesTOCBasePtr(DAG);
3363         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3364         GOTPtr =
3365             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3366       } else {
3367         if (!TM.isPositionIndependent())
3368           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3369         else if (picLevel == PICLevel::SmallPIC)
3370           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3371         else
3372           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3373       }
3374       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3375     }
3376     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3377   }
3378 
3379   if (Model == TLSModel::GeneralDynamic) {
3380     if (Subtarget.isUsingPCRelativeCalls()) {
3381       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3382                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3383       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3384     }
3385 
3386     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3387     SDValue GOTPtr;
3388     if (is64bit) {
3389       setUsesTOCBasePtr(DAG);
3390       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3391       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3392                                    GOTReg, TGA);
3393     } else {
3394       if (picLevel == PICLevel::SmallPIC)
3395         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3396       else
3397         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3398     }
3399     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3400                        GOTPtr, TGA, TGA);
3401   }
3402 
3403   if (Model == TLSModel::LocalDynamic) {
3404     if (Subtarget.isUsingPCRelativeCalls()) {
3405       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3406                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3407       SDValue MatPCRel =
3408           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3409       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3410     }
3411 
3412     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3413     SDValue GOTPtr;
3414     if (is64bit) {
3415       setUsesTOCBasePtr(DAG);
3416       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3417       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3418                            GOTReg, TGA);
3419     } else {
3420       if (picLevel == PICLevel::SmallPIC)
3421         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3422       else
3423         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3424     }
3425     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3426                                   PtrVT, GOTPtr, TGA, TGA);
3427     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3428                                       PtrVT, TLSAddr, TGA);
3429     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3430   }
3431 
3432   llvm_unreachable("Unknown TLS model!");
3433 }
3434 
3435 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3436                                               SelectionDAG &DAG) const {
3437   EVT PtrVT = Op.getValueType();
3438   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3439   SDLoc DL(GSDN);
3440   const GlobalValue *GV = GSDN->getGlobal();
3441 
3442   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3443   // The actual address of the GlobalValue is stored in the TOC.
3444   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3445     if (Subtarget.isUsingPCRelativeCalls()) {
3446       EVT Ty = getPointerTy(DAG.getDataLayout());
3447       if (isAccessedAsGotIndirect(Op)) {
3448         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3449                                                 PPCII::MO_PCREL_FLAG |
3450                                                     PPCII::MO_GOT_FLAG);
3451         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3452         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3453                                    MachinePointerInfo());
3454         return Load;
3455       } else {
3456         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3457                                                 PPCII::MO_PCREL_FLAG);
3458         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3459       }
3460     }
3461     setUsesTOCBasePtr(DAG);
3462     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3463     return getTOCEntry(DAG, DL, GA);
3464   }
3465 
3466   unsigned MOHiFlag, MOLoFlag;
3467   bool IsPIC = isPositionIndependent();
3468   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3469 
3470   if (IsPIC && Subtarget.isSVR4ABI()) {
3471     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3472                                             GSDN->getOffset(),
3473                                             PPCII::MO_PIC_FLAG);
3474     return getTOCEntry(DAG, DL, GA);
3475   }
3476 
3477   SDValue GAHi =
3478     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3479   SDValue GALo =
3480     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3481 
3482   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3483 }
3484 
3485 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3486   bool IsStrict = Op->isStrictFPOpcode();
3487   ISD::CondCode CC =
3488       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3489   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3490   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3491   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3492   EVT LHSVT = LHS.getValueType();
3493   SDLoc dl(Op);
3494 
3495   // Soften the setcc with libcall if it is fp128.
3496   if (LHSVT == MVT::f128) {
3497     assert(!Subtarget.hasP9Vector() &&
3498            "SETCC for f128 is already legal under Power9!");
3499     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3500                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3501     if (RHS.getNode())
3502       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3503                         DAG.getCondCode(CC));
3504     if (IsStrict)
3505       return DAG.getMergeValues({LHS, Chain}, dl);
3506     return LHS;
3507   }
3508 
3509   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3510 
3511   if (Op.getValueType() == MVT::v2i64) {
3512     // When the operands themselves are v2i64 values, we need to do something
3513     // special because VSX has no underlying comparison operations for these.
3514     if (LHS.getValueType() == MVT::v2i64) {
3515       // Equality can be handled by casting to the legal type for Altivec
3516       // comparisons, everything else needs to be expanded.
3517       if (CC != ISD::SETEQ && CC != ISD::SETNE)
3518         return SDValue();
3519       SDValue SetCC32 = DAG.getSetCC(
3520           dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3521           DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3522       int ShuffV[] = {1, 0, 3, 2};
3523       SDValue Shuff =
3524           DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3525       return DAG.getBitcast(MVT::v2i64,
3526                             DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3527                                         dl, MVT::v4i32, Shuff, SetCC32));
3528     }
3529 
3530     // We handle most of these in the usual way.
3531     return Op;
3532   }
3533 
3534   // If we're comparing for equality to zero, expose the fact that this is
3535   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3536   // fold the new nodes.
3537   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3538     return V;
3539 
3540   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3541     // Leave comparisons against 0 and -1 alone for now, since they're usually
3542     // optimized.  FIXME: revisit this when we can custom lower all setcc
3543     // optimizations.
3544     if (C->isAllOnes() || C->isZero())
3545       return SDValue();
3546   }
3547 
3548   // If we have an integer seteq/setne, turn it into a compare against zero
3549   // by xor'ing the rhs with the lhs, which is faster than setting a
3550   // condition register, reading it back out, and masking the correct bit.  The
3551   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3552   // the result to other bit-twiddling opportunities.
3553   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3554     EVT VT = Op.getValueType();
3555     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3556     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3557   }
3558   return SDValue();
3559 }
3560 
3561 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3562   SDNode *Node = Op.getNode();
3563   EVT VT = Node->getValueType(0);
3564   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3565   SDValue InChain = Node->getOperand(0);
3566   SDValue VAListPtr = Node->getOperand(1);
3567   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3568   SDLoc dl(Node);
3569 
3570   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3571 
3572   // gpr_index
3573   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3574                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3575   InChain = GprIndex.getValue(1);
3576 
3577   if (VT == MVT::i64) {
3578     // Check if GprIndex is even
3579     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3580                                  DAG.getConstant(1, dl, MVT::i32));
3581     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3582                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3583     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3584                                           DAG.getConstant(1, dl, MVT::i32));
3585     // Align GprIndex to be even if it isn't
3586     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3587                            GprIndex);
3588   }
3589 
3590   // fpr index is 1 byte after gpr
3591   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3592                                DAG.getConstant(1, dl, MVT::i32));
3593 
3594   // fpr
3595   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3596                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3597   InChain = FprIndex.getValue(1);
3598 
3599   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3600                                        DAG.getConstant(8, dl, MVT::i32));
3601 
3602   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3603                                         DAG.getConstant(4, dl, MVT::i32));
3604 
3605   // areas
3606   SDValue OverflowArea =
3607       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3608   InChain = OverflowArea.getValue(1);
3609 
3610   SDValue RegSaveArea =
3611       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3612   InChain = RegSaveArea.getValue(1);
3613 
3614   // select overflow_area if index > 8
3615   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3616                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3617 
3618   // adjustment constant gpr_index * 4/8
3619   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3620                                     VT.isInteger() ? GprIndex : FprIndex,
3621                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3622                                                     MVT::i32));
3623 
3624   // OurReg = RegSaveArea + RegConstant
3625   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3626                                RegConstant);
3627 
3628   // Floating types are 32 bytes into RegSaveArea
3629   if (VT.isFloatingPoint())
3630     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3631                          DAG.getConstant(32, dl, MVT::i32));
3632 
3633   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3634   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3635                                    VT.isInteger() ? GprIndex : FprIndex,
3636                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3637                                                    MVT::i32));
3638 
3639   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3640                               VT.isInteger() ? VAListPtr : FprPtr,
3641                               MachinePointerInfo(SV), MVT::i8);
3642 
3643   // determine if we should load from reg_save_area or overflow_area
3644   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3645 
3646   // increase overflow_area by 4/8 if gpr/fpr > 8
3647   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3648                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3649                                           dl, MVT::i32));
3650 
3651   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3652                              OverflowAreaPlusN);
3653 
3654   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3655                               MachinePointerInfo(), MVT::i32);
3656 
3657   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3658 }
3659 
3660 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3661   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3662 
3663   // We have to copy the entire va_list struct:
3664   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3665   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3666                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3667                        false, true, false, MachinePointerInfo(),
3668                        MachinePointerInfo());
3669 }
3670 
3671 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3672                                                   SelectionDAG &DAG) const {
3673   if (Subtarget.isAIXABI())
3674     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3675 
3676   return Op.getOperand(0);
3677 }
3678 
3679 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3680   MachineFunction &MF = DAG.getMachineFunction();
3681   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3682 
3683   assert((Op.getOpcode() == ISD::INLINEASM ||
3684           Op.getOpcode() == ISD::INLINEASM_BR) &&
3685          "Expecting Inline ASM node.");
3686 
3687   // If an LR store is already known to be required then there is not point in
3688   // checking this ASM as well.
3689   if (MFI.isLRStoreRequired())
3690     return Op;
3691 
3692   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3693   // type MVT::Glue. We want to ignore this last operand if that is the case.
3694   unsigned NumOps = Op.getNumOperands();
3695   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3696     --NumOps;
3697 
3698   // Check all operands that may contain the LR.
3699   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3700     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3701     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3702     ++i; // Skip the ID value.
3703 
3704     switch (InlineAsm::getKind(Flags)) {
3705     default:
3706       llvm_unreachable("Bad flags!");
3707     case InlineAsm::Kind_RegUse:
3708     case InlineAsm::Kind_Imm:
3709     case InlineAsm::Kind_Mem:
3710       i += NumVals;
3711       break;
3712     case InlineAsm::Kind_Clobber:
3713     case InlineAsm::Kind_RegDef:
3714     case InlineAsm::Kind_RegDefEarlyClobber: {
3715       for (; NumVals; --NumVals, ++i) {
3716         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3717         if (Reg != PPC::LR && Reg != PPC::LR8)
3718           continue;
3719         MFI.setLRStoreRequired();
3720         return Op;
3721       }
3722       break;
3723     }
3724     }
3725   }
3726 
3727   return Op;
3728 }
3729 
3730 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3731                                                 SelectionDAG &DAG) const {
3732   if (Subtarget.isAIXABI())
3733     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3734 
3735   SDValue Chain = Op.getOperand(0);
3736   SDValue Trmp = Op.getOperand(1); // trampoline
3737   SDValue FPtr = Op.getOperand(2); // nested function
3738   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3739   SDLoc dl(Op);
3740 
3741   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3742   bool isPPC64 = (PtrVT == MVT::i64);
3743   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3744 
3745   TargetLowering::ArgListTy Args;
3746   TargetLowering::ArgListEntry Entry;
3747 
3748   Entry.Ty = IntPtrTy;
3749   Entry.Node = Trmp; Args.push_back(Entry);
3750 
3751   // TrampSize == (isPPC64 ? 48 : 40);
3752   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3753                                isPPC64 ? MVT::i64 : MVT::i32);
3754   Args.push_back(Entry);
3755 
3756   Entry.Node = FPtr; Args.push_back(Entry);
3757   Entry.Node = Nest; Args.push_back(Entry);
3758 
3759   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3760   TargetLowering::CallLoweringInfo CLI(DAG);
3761   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3762       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3763       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3764 
3765   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3766   return CallResult.second;
3767 }
3768 
3769 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3770   MachineFunction &MF = DAG.getMachineFunction();
3771   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3772   EVT PtrVT = getPointerTy(MF.getDataLayout());
3773 
3774   SDLoc dl(Op);
3775 
3776   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3777     // vastart just stores the address of the VarArgsFrameIndex slot into the
3778     // memory location argument.
3779     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3780     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3781     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3782                         MachinePointerInfo(SV));
3783   }
3784 
3785   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3786   // We suppose the given va_list is already allocated.
3787   //
3788   // typedef struct {
3789   //  char gpr;     /* index into the array of 8 GPRs
3790   //                 * stored in the register save area
3791   //                 * gpr=0 corresponds to r3,
3792   //                 * gpr=1 to r4, etc.
3793   //                 */
3794   //  char fpr;     /* index into the array of 8 FPRs
3795   //                 * stored in the register save area
3796   //                 * fpr=0 corresponds to f1,
3797   //                 * fpr=1 to f2, etc.
3798   //                 */
3799   //  char *overflow_arg_area;
3800   //                /* location on stack that holds
3801   //                 * the next overflow argument
3802   //                 */
3803   //  char *reg_save_area;
3804   //               /* where r3:r10 and f1:f8 (if saved)
3805   //                * are stored
3806   //                */
3807   // } va_list[1];
3808 
3809   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3810   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3811   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3812                                             PtrVT);
3813   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3814                                  PtrVT);
3815 
3816   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3817   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3818 
3819   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3820   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3821 
3822   uint64_t FPROffset = 1;
3823   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3824 
3825   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3826 
3827   // Store first byte : number of int regs
3828   SDValue firstStore =
3829       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3830                         MachinePointerInfo(SV), MVT::i8);
3831   uint64_t nextOffset = FPROffset;
3832   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3833                                   ConstFPROffset);
3834 
3835   // Store second byte : number of float regs
3836   SDValue secondStore =
3837       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3838                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3839   nextOffset += StackOffset;
3840   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3841 
3842   // Store second word : arguments given on stack
3843   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3844                                     MachinePointerInfo(SV, nextOffset));
3845   nextOffset += FrameOffset;
3846   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3847 
3848   // Store third word : arguments given in registers
3849   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3850                       MachinePointerInfo(SV, nextOffset));
3851 }
3852 
3853 /// FPR - The set of FP registers that should be allocated for arguments
3854 /// on Darwin and AIX.
3855 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3856                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3857                                 PPC::F11, PPC::F12, PPC::F13};
3858 
3859 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3860 /// the stack.
3861 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3862                                        unsigned PtrByteSize) {
3863   unsigned ArgSize = ArgVT.getStoreSize();
3864   if (Flags.isByVal())
3865     ArgSize = Flags.getByValSize();
3866 
3867   // Round up to multiples of the pointer size, except for array members,
3868   // which are always packed.
3869   if (!Flags.isInConsecutiveRegs())
3870     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3871 
3872   return ArgSize;
3873 }
3874 
3875 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3876 /// on the stack.
3877 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3878                                          ISD::ArgFlagsTy Flags,
3879                                          unsigned PtrByteSize) {
3880   Align Alignment(PtrByteSize);
3881 
3882   // Altivec parameters are padded to a 16 byte boundary.
3883   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3884       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3885       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3886       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3887     Alignment = Align(16);
3888 
3889   // ByVal parameters are aligned as requested.
3890   if (Flags.isByVal()) {
3891     auto BVAlign = Flags.getNonZeroByValAlign();
3892     if (BVAlign > PtrByteSize) {
3893       if (BVAlign.value() % PtrByteSize != 0)
3894         llvm_unreachable(
3895             "ByVal alignment is not a multiple of the pointer size");
3896 
3897       Alignment = BVAlign;
3898     }
3899   }
3900 
3901   // Array members are always packed to their original alignment.
3902   if (Flags.isInConsecutiveRegs()) {
3903     // If the array member was split into multiple registers, the first
3904     // needs to be aligned to the size of the full type.  (Except for
3905     // ppcf128, which is only aligned as its f64 components.)
3906     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3907       Alignment = Align(OrigVT.getStoreSize());
3908     else
3909       Alignment = Align(ArgVT.getStoreSize());
3910   }
3911 
3912   return Alignment;
3913 }
3914 
3915 /// CalculateStackSlotUsed - Return whether this argument will use its
3916 /// stack slot (instead of being passed in registers).  ArgOffset,
3917 /// AvailableFPRs, and AvailableVRs must hold the current argument
3918 /// position, and will be updated to account for this argument.
3919 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3920                                    unsigned PtrByteSize, unsigned LinkageSize,
3921                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3922                                    unsigned &AvailableFPRs,
3923                                    unsigned &AvailableVRs) {
3924   bool UseMemory = false;
3925 
3926   // Respect alignment of argument on the stack.
3927   Align Alignment =
3928       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3929   ArgOffset = alignTo(ArgOffset, Alignment);
3930   // If there's no space left in the argument save area, we must
3931   // use memory (this check also catches zero-sized arguments).
3932   if (ArgOffset >= LinkageSize + ParamAreaSize)
3933     UseMemory = true;
3934 
3935   // Allocate argument on the stack.
3936   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3937   if (Flags.isInConsecutiveRegsLast())
3938     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3939   // If we overran the argument save area, we must use memory
3940   // (this check catches arguments passed partially in memory)
3941   if (ArgOffset > LinkageSize + ParamAreaSize)
3942     UseMemory = true;
3943 
3944   // However, if the argument is actually passed in an FPR or a VR,
3945   // we don't use memory after all.
3946   if (!Flags.isByVal()) {
3947     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3948       if (AvailableFPRs > 0) {
3949         --AvailableFPRs;
3950         return false;
3951       }
3952     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3953         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3954         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3955         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3956       if (AvailableVRs > 0) {
3957         --AvailableVRs;
3958         return false;
3959       }
3960   }
3961 
3962   return UseMemory;
3963 }
3964 
3965 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3966 /// ensure minimum alignment required for target.
3967 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3968                                      unsigned NumBytes) {
3969   return alignTo(NumBytes, Lowering->getStackAlign());
3970 }
3971 
3972 SDValue PPCTargetLowering::LowerFormalArguments(
3973     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3974     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3975     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3976   if (Subtarget.isAIXABI())
3977     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3978                                     InVals);
3979   if (Subtarget.is64BitELFABI())
3980     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3981                                        InVals);
3982   assert(Subtarget.is32BitELFABI());
3983   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3984                                      InVals);
3985 }
3986 
3987 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3988     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3989     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3990     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3991 
3992   // 32-bit SVR4 ABI Stack Frame Layout:
3993   //              +-----------------------------------+
3994   //        +-->  |            Back chain             |
3995   //        |     +-----------------------------------+
3996   //        |     | Floating-point register save area |
3997   //        |     +-----------------------------------+
3998   //        |     |    General register save area     |
3999   //        |     +-----------------------------------+
4000   //        |     |          CR save word             |
4001   //        |     +-----------------------------------+
4002   //        |     |         VRSAVE save word          |
4003   //        |     +-----------------------------------+
4004   //        |     |         Alignment padding         |
4005   //        |     +-----------------------------------+
4006   //        |     |     Vector register save area     |
4007   //        |     +-----------------------------------+
4008   //        |     |       Local variable space        |
4009   //        |     +-----------------------------------+
4010   //        |     |        Parameter list area        |
4011   //        |     +-----------------------------------+
4012   //        |     |           LR save word            |
4013   //        |     +-----------------------------------+
4014   // SP-->  +---  |            Back chain             |
4015   //              +-----------------------------------+
4016   //
4017   // Specifications:
4018   //   System V Application Binary Interface PowerPC Processor Supplement
4019   //   AltiVec Technology Programming Interface Manual
4020 
4021   MachineFunction &MF = DAG.getMachineFunction();
4022   MachineFrameInfo &MFI = MF.getFrameInfo();
4023   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4024 
4025   EVT PtrVT = getPointerTy(MF.getDataLayout());
4026   // Potential tail calls could cause overwriting of argument stack slots.
4027   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4028                        (CallConv == CallingConv::Fast));
4029   const Align PtrAlign(4);
4030 
4031   // Assign locations to all of the incoming arguments.
4032   SmallVector<CCValAssign, 16> ArgLocs;
4033   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4034                  *DAG.getContext());
4035 
4036   // Reserve space for the linkage area on the stack.
4037   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4038   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4039   if (useSoftFloat())
4040     CCInfo.PreAnalyzeFormalArguments(Ins);
4041 
4042   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4043   CCInfo.clearWasPPCF128();
4044 
4045   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4046     CCValAssign &VA = ArgLocs[i];
4047 
4048     // Arguments stored in registers.
4049     if (VA.isRegLoc()) {
4050       const TargetRegisterClass *RC;
4051       EVT ValVT = VA.getValVT();
4052 
4053       switch (ValVT.getSimpleVT().SimpleTy) {
4054         default:
4055           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4056         case MVT::i1:
4057         case MVT::i32:
4058           RC = &PPC::GPRCRegClass;
4059           break;
4060         case MVT::f32:
4061           if (Subtarget.hasP8Vector())
4062             RC = &PPC::VSSRCRegClass;
4063           else if (Subtarget.hasSPE())
4064             RC = &PPC::GPRCRegClass;
4065           else
4066             RC = &PPC::F4RCRegClass;
4067           break;
4068         case MVT::f64:
4069           if (Subtarget.hasVSX())
4070             RC = &PPC::VSFRCRegClass;
4071           else if (Subtarget.hasSPE())
4072             // SPE passes doubles in GPR pairs.
4073             RC = &PPC::GPRCRegClass;
4074           else
4075             RC = &PPC::F8RCRegClass;
4076           break;
4077         case MVT::v16i8:
4078         case MVT::v8i16:
4079         case MVT::v4i32:
4080           RC = &PPC::VRRCRegClass;
4081           break;
4082         case MVT::v4f32:
4083           RC = &PPC::VRRCRegClass;
4084           break;
4085         case MVT::v2f64:
4086         case MVT::v2i64:
4087           RC = &PPC::VRRCRegClass;
4088           break;
4089       }
4090 
4091       SDValue ArgValue;
4092       // Transform the arguments stored in physical registers into
4093       // virtual ones.
4094       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4095         assert(i + 1 < e && "No second half of double precision argument");
4096         Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4097         Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4098         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4099         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4100         if (!Subtarget.isLittleEndian())
4101           std::swap (ArgValueLo, ArgValueHi);
4102         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4103                                ArgValueHi);
4104       } else {
4105         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4106         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4107                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4108         if (ValVT == MVT::i1)
4109           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4110       }
4111 
4112       InVals.push_back(ArgValue);
4113     } else {
4114       // Argument stored in memory.
4115       assert(VA.isMemLoc());
4116 
4117       // Get the extended size of the argument type in stack
4118       unsigned ArgSize = VA.getLocVT().getStoreSize();
4119       // Get the actual size of the argument type
4120       unsigned ObjSize = VA.getValVT().getStoreSize();
4121       unsigned ArgOffset = VA.getLocMemOffset();
4122       // Stack objects in PPC32 are right justified.
4123       ArgOffset += ArgSize - ObjSize;
4124       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4125 
4126       // Create load nodes to retrieve arguments from the stack.
4127       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4128       InVals.push_back(
4129           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4130     }
4131   }
4132 
4133   // Assign locations to all of the incoming aggregate by value arguments.
4134   // Aggregates passed by value are stored in the local variable space of the
4135   // caller's stack frame, right above the parameter list area.
4136   SmallVector<CCValAssign, 16> ByValArgLocs;
4137   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4138                       ByValArgLocs, *DAG.getContext());
4139 
4140   // Reserve stack space for the allocations in CCInfo.
4141   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4142 
4143   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4144 
4145   // Area that is at least reserved in the caller of this function.
4146   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4147   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4148 
4149   // Set the size that is at least reserved in caller of this function.  Tail
4150   // call optimized function's reserved stack space needs to be aligned so that
4151   // taking the difference between two stack areas will result in an aligned
4152   // stack.
4153   MinReservedArea =
4154       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4155   FuncInfo->setMinReservedArea(MinReservedArea);
4156 
4157   SmallVector<SDValue, 8> MemOps;
4158 
4159   // If the function takes variable number of arguments, make a frame index for
4160   // the start of the first vararg value... for expansion of llvm.va_start.
4161   if (isVarArg) {
4162     static const MCPhysReg GPArgRegs[] = {
4163       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4164       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4165     };
4166     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4167 
4168     static const MCPhysReg FPArgRegs[] = {
4169       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4170       PPC::F8
4171     };
4172     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4173 
4174     if (useSoftFloat() || hasSPE())
4175        NumFPArgRegs = 0;
4176 
4177     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4178     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4179 
4180     // Make room for NumGPArgRegs and NumFPArgRegs.
4181     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4182                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4183 
4184     FuncInfo->setVarArgsStackOffset(
4185       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4186                             CCInfo.getNextStackOffset(), true));
4187 
4188     FuncInfo->setVarArgsFrameIndex(
4189         MFI.CreateStackObject(Depth, Align(8), false));
4190     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4191 
4192     // The fixed integer arguments of a variadic function are stored to the
4193     // VarArgsFrameIndex on the stack so that they may be loaded by
4194     // dereferencing the result of va_next.
4195     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4196       // Get an existing live-in vreg, or add a new one.
4197       Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4198       if (!VReg)
4199         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4200 
4201       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4202       SDValue Store =
4203           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4204       MemOps.push_back(Store);
4205       // Increment the address by four for the next argument to store
4206       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4207       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4208     }
4209 
4210     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4211     // is set.
4212     // The double arguments are stored to the VarArgsFrameIndex
4213     // on the stack.
4214     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4215       // Get an existing live-in vreg, or add a new one.
4216       Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4217       if (!VReg)
4218         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4219 
4220       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4221       SDValue Store =
4222           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4223       MemOps.push_back(Store);
4224       // Increment the address by eight for the next argument to store
4225       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4226                                          PtrVT);
4227       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4228     }
4229   }
4230 
4231   if (!MemOps.empty())
4232     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4233 
4234   return Chain;
4235 }
4236 
4237 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4238 // value to MVT::i64 and then truncate to the correct register size.
4239 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4240                                              EVT ObjectVT, SelectionDAG &DAG,
4241                                              SDValue ArgVal,
4242                                              const SDLoc &dl) const {
4243   if (Flags.isSExt())
4244     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4245                          DAG.getValueType(ObjectVT));
4246   else if (Flags.isZExt())
4247     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4248                          DAG.getValueType(ObjectVT));
4249 
4250   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4251 }
4252 
4253 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4254     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4255     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4256     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4257   // TODO: add description of PPC stack frame format, or at least some docs.
4258   //
4259   bool isELFv2ABI = Subtarget.isELFv2ABI();
4260   bool isLittleEndian = Subtarget.isLittleEndian();
4261   MachineFunction &MF = DAG.getMachineFunction();
4262   MachineFrameInfo &MFI = MF.getFrameInfo();
4263   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4264 
4265   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4266          "fastcc not supported on varargs functions");
4267 
4268   EVT PtrVT = getPointerTy(MF.getDataLayout());
4269   // Potential tail calls could cause overwriting of argument stack slots.
4270   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4271                        (CallConv == CallingConv::Fast));
4272   unsigned PtrByteSize = 8;
4273   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4274 
4275   static const MCPhysReg GPR[] = {
4276     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4277     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4278   };
4279   static const MCPhysReg VR[] = {
4280     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4281     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4282   };
4283 
4284   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4285   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4286   const unsigned Num_VR_Regs  = array_lengthof(VR);
4287 
4288   // Do a first pass over the arguments to determine whether the ABI
4289   // guarantees that our caller has allocated the parameter save area
4290   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4291   // in the ELFv2 ABI, it is true if this is a vararg function or if
4292   // any parameter is located in a stack slot.
4293 
4294   bool HasParameterArea = !isELFv2ABI || isVarArg;
4295   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4296   unsigned NumBytes = LinkageSize;
4297   unsigned AvailableFPRs = Num_FPR_Regs;
4298   unsigned AvailableVRs = Num_VR_Regs;
4299   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4300     if (Ins[i].Flags.isNest())
4301       continue;
4302 
4303     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4304                                PtrByteSize, LinkageSize, ParamAreaSize,
4305                                NumBytes, AvailableFPRs, AvailableVRs))
4306       HasParameterArea = true;
4307   }
4308 
4309   // Add DAG nodes to load the arguments or copy them out of registers.  On
4310   // entry to a function on PPC, the arguments start after the linkage area,
4311   // although the first ones are often in registers.
4312 
4313   unsigned ArgOffset = LinkageSize;
4314   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4315   SmallVector<SDValue, 8> MemOps;
4316   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4317   unsigned CurArgIdx = 0;
4318   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4319     SDValue ArgVal;
4320     bool needsLoad = false;
4321     EVT ObjectVT = Ins[ArgNo].VT;
4322     EVT OrigVT = Ins[ArgNo].ArgVT;
4323     unsigned ObjSize = ObjectVT.getStoreSize();
4324     unsigned ArgSize = ObjSize;
4325     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4326     if (Ins[ArgNo].isOrigArg()) {
4327       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4328       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4329     }
4330     // We re-align the argument offset for each argument, except when using the
4331     // fast calling convention, when we need to make sure we do that only when
4332     // we'll actually use a stack slot.
4333     unsigned CurArgOffset;
4334     Align Alignment;
4335     auto ComputeArgOffset = [&]() {
4336       /* Respect alignment of argument on the stack.  */
4337       Alignment =
4338           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4339       ArgOffset = alignTo(ArgOffset, Alignment);
4340       CurArgOffset = ArgOffset;
4341     };
4342 
4343     if (CallConv != CallingConv::Fast) {
4344       ComputeArgOffset();
4345 
4346       /* Compute GPR index associated with argument offset.  */
4347       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4348       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4349     }
4350 
4351     // FIXME the codegen can be much improved in some cases.
4352     // We do not have to keep everything in memory.
4353     if (Flags.isByVal()) {
4354       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4355 
4356       if (CallConv == CallingConv::Fast)
4357         ComputeArgOffset();
4358 
4359       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4360       ObjSize = Flags.getByValSize();
4361       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4362       // Empty aggregate parameters do not take up registers.  Examples:
4363       //   struct { } a;
4364       //   union  { } b;
4365       //   int c[0];
4366       // etc.  However, we have to provide a place-holder in InVals, so
4367       // pretend we have an 8-byte item at the current address for that
4368       // purpose.
4369       if (!ObjSize) {
4370         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4371         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4372         InVals.push_back(FIN);
4373         continue;
4374       }
4375 
4376       // Create a stack object covering all stack doublewords occupied
4377       // by the argument.  If the argument is (fully or partially) on
4378       // the stack, or if the argument is fully in registers but the
4379       // caller has allocated the parameter save anyway, we can refer
4380       // directly to the caller's stack frame.  Otherwise, create a
4381       // local copy in our own frame.
4382       int FI;
4383       if (HasParameterArea ||
4384           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4385         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4386       else
4387         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4388       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4389 
4390       // Handle aggregates smaller than 8 bytes.
4391       if (ObjSize < PtrByteSize) {
4392         // The value of the object is its address, which differs from the
4393         // address of the enclosing doubleword on big-endian systems.
4394         SDValue Arg = FIN;
4395         if (!isLittleEndian) {
4396           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4397           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4398         }
4399         InVals.push_back(Arg);
4400 
4401         if (GPR_idx != Num_GPR_Regs) {
4402           Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4403           FuncInfo->addLiveInAttr(VReg, Flags);
4404           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4405           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4406           SDValue Store =
4407               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4408                                 MachinePointerInfo(&*FuncArg), ObjType);
4409           MemOps.push_back(Store);
4410         }
4411         // Whether we copied from a register or not, advance the offset
4412         // into the parameter save area by a full doubleword.
4413         ArgOffset += PtrByteSize;
4414         continue;
4415       }
4416 
4417       // The value of the object is its address, which is the address of
4418       // its first stack doubleword.
4419       InVals.push_back(FIN);
4420 
4421       // Store whatever pieces of the object are in registers to memory.
4422       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4423         if (GPR_idx == Num_GPR_Regs)
4424           break;
4425 
4426         Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4427         FuncInfo->addLiveInAttr(VReg, Flags);
4428         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4429         SDValue Addr = FIN;
4430         if (j) {
4431           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4432           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4433         }
4434         unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4435         EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4436         SDValue Store =
4437             DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4438                               MachinePointerInfo(&*FuncArg, j), ObjType);
4439         MemOps.push_back(Store);
4440         ++GPR_idx;
4441       }
4442       ArgOffset += ArgSize;
4443       continue;
4444     }
4445 
4446     switch (ObjectVT.getSimpleVT().SimpleTy) {
4447     default: llvm_unreachable("Unhandled argument type!");
4448     case MVT::i1:
4449     case MVT::i32:
4450     case MVT::i64:
4451       if (Flags.isNest()) {
4452         // The 'nest' parameter, if any, is passed in R11.
4453         Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4454         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4455 
4456         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4457           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4458 
4459         break;
4460       }
4461 
4462       // These can be scalar arguments or elements of an integer array type
4463       // passed directly.  Clang may use those instead of "byval" aggregate
4464       // types to avoid forcing arguments to memory unnecessarily.
4465       if (GPR_idx != Num_GPR_Regs) {
4466         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4467         FuncInfo->addLiveInAttr(VReg, Flags);
4468         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4469 
4470         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4471           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4472           // value to MVT::i64 and then truncate to the correct register size.
4473           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4474       } else {
4475         if (CallConv == CallingConv::Fast)
4476           ComputeArgOffset();
4477 
4478         needsLoad = true;
4479         ArgSize = PtrByteSize;
4480       }
4481       if (CallConv != CallingConv::Fast || needsLoad)
4482         ArgOffset += 8;
4483       break;
4484 
4485     case MVT::f32:
4486     case MVT::f64:
4487       // These can be scalar arguments or elements of a float array type
4488       // passed directly.  The latter are used to implement ELFv2 homogenous
4489       // float aggregates.
4490       if (FPR_idx != Num_FPR_Regs) {
4491         unsigned VReg;
4492 
4493         if (ObjectVT == MVT::f32)
4494           VReg = MF.addLiveIn(FPR[FPR_idx],
4495                               Subtarget.hasP8Vector()
4496                                   ? &PPC::VSSRCRegClass
4497                                   : &PPC::F4RCRegClass);
4498         else
4499           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4500                                                 ? &PPC::VSFRCRegClass
4501                                                 : &PPC::F8RCRegClass);
4502 
4503         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4504         ++FPR_idx;
4505       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4506         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4507         // once we support fp <-> gpr moves.
4508 
4509         // This can only ever happen in the presence of f32 array types,
4510         // since otherwise we never run out of FPRs before running out
4511         // of GPRs.
4512         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4513         FuncInfo->addLiveInAttr(VReg, Flags);
4514         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4515 
4516         if (ObjectVT == MVT::f32) {
4517           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4518             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4519                                  DAG.getConstant(32, dl, MVT::i32));
4520           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4521         }
4522 
4523         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4524       } else {
4525         if (CallConv == CallingConv::Fast)
4526           ComputeArgOffset();
4527 
4528         needsLoad = true;
4529       }
4530 
4531       // When passing an array of floats, the array occupies consecutive
4532       // space in the argument area; only round up to the next doubleword
4533       // at the end of the array.  Otherwise, each float takes 8 bytes.
4534       if (CallConv != CallingConv::Fast || needsLoad) {
4535         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4536         ArgOffset += ArgSize;
4537         if (Flags.isInConsecutiveRegsLast())
4538           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4539       }
4540       break;
4541     case MVT::v4f32:
4542     case MVT::v4i32:
4543     case MVT::v8i16:
4544     case MVT::v16i8:
4545     case MVT::v2f64:
4546     case MVT::v2i64:
4547     case MVT::v1i128:
4548     case MVT::f128:
4549       // These can be scalar arguments or elements of a vector array type
4550       // passed directly.  The latter are used to implement ELFv2 homogenous
4551       // vector aggregates.
4552       if (VR_idx != Num_VR_Regs) {
4553         Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4554         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4555         ++VR_idx;
4556       } else {
4557         if (CallConv == CallingConv::Fast)
4558           ComputeArgOffset();
4559         needsLoad = true;
4560       }
4561       if (CallConv != CallingConv::Fast || needsLoad)
4562         ArgOffset += 16;
4563       break;
4564     }
4565 
4566     // We need to load the argument to a virtual register if we determined
4567     // above that we ran out of physical registers of the appropriate type.
4568     if (needsLoad) {
4569       if (ObjSize < ArgSize && !isLittleEndian)
4570         CurArgOffset += ArgSize - ObjSize;
4571       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4572       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4573       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4574     }
4575 
4576     InVals.push_back(ArgVal);
4577   }
4578 
4579   // Area that is at least reserved in the caller of this function.
4580   unsigned MinReservedArea;
4581   if (HasParameterArea)
4582     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4583   else
4584     MinReservedArea = LinkageSize;
4585 
4586   // Set the size that is at least reserved in caller of this function.  Tail
4587   // call optimized functions' reserved stack space needs to be aligned so that
4588   // taking the difference between two stack areas will result in an aligned
4589   // stack.
4590   MinReservedArea =
4591       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4592   FuncInfo->setMinReservedArea(MinReservedArea);
4593 
4594   // If the function takes variable number of arguments, make a frame index for
4595   // the start of the first vararg value... for expansion of llvm.va_start.
4596   // On ELFv2ABI spec, it writes:
4597   // C programs that are intended to be *portable* across different compilers
4598   // and architectures must use the header file <stdarg.h> to deal with variable
4599   // argument lists.
4600   if (isVarArg && MFI.hasVAStart()) {
4601     int Depth = ArgOffset;
4602 
4603     FuncInfo->setVarArgsFrameIndex(
4604       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4605     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4606 
4607     // If this function is vararg, store any remaining integer argument regs
4608     // to their spots on the stack so that they may be loaded by dereferencing
4609     // the result of va_next.
4610     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4611          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4612       Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4613       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4614       SDValue Store =
4615           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4616       MemOps.push_back(Store);
4617       // Increment the address by four for the next argument to store
4618       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4619       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4620     }
4621   }
4622 
4623   if (!MemOps.empty())
4624     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4625 
4626   return Chain;
4627 }
4628 
4629 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4630 /// adjusted to accommodate the arguments for the tailcall.
4631 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4632                                    unsigned ParamSize) {
4633 
4634   if (!isTailCall) return 0;
4635 
4636   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4637   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4638   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4639   // Remember only if the new adjustment is bigger.
4640   if (SPDiff < FI->getTailCallSPDelta())
4641     FI->setTailCallSPDelta(SPDiff);
4642 
4643   return SPDiff;
4644 }
4645 
4646 static bool isFunctionGlobalAddress(SDValue Callee);
4647 
4648 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4649                               const TargetMachine &TM) {
4650   // It does not make sense to call callsShareTOCBase() with a caller that
4651   // is PC Relative since PC Relative callers do not have a TOC.
4652 #ifndef NDEBUG
4653   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4654   assert(!STICaller->isUsingPCRelativeCalls() &&
4655          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4656 #endif
4657 
4658   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4659   // don't have enough information to determine if the caller and callee share
4660   // the same  TOC base, so we have to pessimistically assume they don't for
4661   // correctness.
4662   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4663   if (!G)
4664     return false;
4665 
4666   const GlobalValue *GV = G->getGlobal();
4667 
4668   // If the callee is preemptable, then the static linker will use a plt-stub
4669   // which saves the toc to the stack, and needs a nop after the call
4670   // instruction to convert to a toc-restore.
4671   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4672     return false;
4673 
4674   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4675   // We may need a TOC restore in the situation where the caller requires a
4676   // valid TOC but the callee is PC Relative and does not.
4677   const Function *F = dyn_cast<Function>(GV);
4678   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4679 
4680   // If we have an Alias we can try to get the function from there.
4681   if (Alias) {
4682     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4683     F = dyn_cast<Function>(GlobalObj);
4684   }
4685 
4686   // If we still have no valid function pointer we do not have enough
4687   // information to determine if the callee uses PC Relative calls so we must
4688   // assume that it does.
4689   if (!F)
4690     return false;
4691 
4692   // If the callee uses PC Relative we cannot guarantee that the callee won't
4693   // clobber the TOC of the caller and so we must assume that the two
4694   // functions do not share a TOC base.
4695   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4696   if (STICallee->isUsingPCRelativeCalls())
4697     return false;
4698 
4699   // If the GV is not a strong definition then we need to assume it can be
4700   // replaced by another function at link time. The function that replaces
4701   // it may not share the same TOC as the caller since the callee may be
4702   // replaced by a PC Relative version of the same function.
4703   if (!GV->isStrongDefinitionForLinker())
4704     return false;
4705 
4706   // The medium and large code models are expected to provide a sufficiently
4707   // large TOC to provide all data addressing needs of a module with a
4708   // single TOC.
4709   if (CodeModel::Medium == TM.getCodeModel() ||
4710       CodeModel::Large == TM.getCodeModel())
4711     return true;
4712 
4713   // Any explicitly-specified sections and section prefixes must also match.
4714   // Also, if we're using -ffunction-sections, then each function is always in
4715   // a different section (the same is true for COMDAT functions).
4716   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4717       GV->getSection() != Caller->getSection())
4718     return false;
4719   if (const auto *F = dyn_cast<Function>(GV)) {
4720     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4721       return false;
4722   }
4723 
4724   return true;
4725 }
4726 
4727 static bool
4728 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4729                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4730   assert(Subtarget.is64BitELFABI());
4731 
4732   const unsigned PtrByteSize = 8;
4733   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4734 
4735   static const MCPhysReg GPR[] = {
4736     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4737     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4738   };
4739   static const MCPhysReg VR[] = {
4740     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4741     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4742   };
4743 
4744   const unsigned NumGPRs = array_lengthof(GPR);
4745   const unsigned NumFPRs = 13;
4746   const unsigned NumVRs = array_lengthof(VR);
4747   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4748 
4749   unsigned NumBytes = LinkageSize;
4750   unsigned AvailableFPRs = NumFPRs;
4751   unsigned AvailableVRs = NumVRs;
4752 
4753   for (const ISD::OutputArg& Param : Outs) {
4754     if (Param.Flags.isNest()) continue;
4755 
4756     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4757                                LinkageSize, ParamAreaSize, NumBytes,
4758                                AvailableFPRs, AvailableVRs))
4759       return true;
4760   }
4761   return false;
4762 }
4763 
4764 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4765   if (CB.arg_size() != CallerFn->arg_size())
4766     return false;
4767 
4768   auto CalleeArgIter = CB.arg_begin();
4769   auto CalleeArgEnd = CB.arg_end();
4770   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4771 
4772   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4773     const Value* CalleeArg = *CalleeArgIter;
4774     const Value* CallerArg = &(*CallerArgIter);
4775     if (CalleeArg == CallerArg)
4776       continue;
4777 
4778     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4779     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4780     //      }
4781     // 1st argument of callee is undef and has the same type as caller.
4782     if (CalleeArg->getType() == CallerArg->getType() &&
4783         isa<UndefValue>(CalleeArg))
4784       continue;
4785 
4786     return false;
4787   }
4788 
4789   return true;
4790 }
4791 
4792 // Returns true if TCO is possible between the callers and callees
4793 // calling conventions.
4794 static bool
4795 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4796                                     CallingConv::ID CalleeCC) {
4797   // Tail calls are possible with fastcc and ccc.
4798   auto isTailCallableCC  = [] (CallingConv::ID CC){
4799       return  CC == CallingConv::C || CC == CallingConv::Fast;
4800   };
4801   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4802     return false;
4803 
4804   // We can safely tail call both fastcc and ccc callees from a c calling
4805   // convention caller. If the caller is fastcc, we may have less stack space
4806   // than a non-fastcc caller with the same signature so disable tail-calls in
4807   // that case.
4808   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4809 }
4810 
4811 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4812     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4813     const SmallVectorImpl<ISD::OutputArg> &Outs,
4814     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4815   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4816 
4817   if (DisableSCO && !TailCallOpt) return false;
4818 
4819   // Variadic argument functions are not supported.
4820   if (isVarArg) return false;
4821 
4822   auto &Caller = DAG.getMachineFunction().getFunction();
4823   // Check that the calling conventions are compatible for tco.
4824   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4825     return false;
4826 
4827   // Caller contains any byval parameter is not supported.
4828   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4829     return false;
4830 
4831   // Callee contains any byval parameter is not supported, too.
4832   // Note: This is a quick work around, because in some cases, e.g.
4833   // caller's stack size > callee's stack size, we are still able to apply
4834   // sibling call optimization. For example, gcc is able to do SCO for caller1
4835   // in the following example, but not for caller2.
4836   //   struct test {
4837   //     long int a;
4838   //     char ary[56];
4839   //   } gTest;
4840   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4841   //     b->a = v.a;
4842   //     return 0;
4843   //   }
4844   //   void caller1(struct test a, struct test c, struct test *b) {
4845   //     callee(gTest, b); }
4846   //   void caller2(struct test *b) { callee(gTest, b); }
4847   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4848     return false;
4849 
4850   // If callee and caller use different calling conventions, we cannot pass
4851   // parameters on stack since offsets for the parameter area may be different.
4852   if (Caller.getCallingConv() != CalleeCC &&
4853       needStackSlotPassParameters(Subtarget, Outs))
4854     return false;
4855 
4856   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4857   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4858   // callee potentially have different TOC bases then we cannot tail call since
4859   // we need to restore the TOC pointer after the call.
4860   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4861   // We cannot guarantee this for indirect calls or calls to external functions.
4862   // When PC-Relative addressing is used, the concept of the TOC is no longer
4863   // applicable so this check is not required.
4864   // Check first for indirect calls.
4865   if (!Subtarget.isUsingPCRelativeCalls() &&
4866       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4867     return false;
4868 
4869   // Check if we share the TOC base.
4870   if (!Subtarget.isUsingPCRelativeCalls() &&
4871       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4872     return false;
4873 
4874   // TCO allows altering callee ABI, so we don't have to check further.
4875   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4876     return true;
4877 
4878   if (DisableSCO) return false;
4879 
4880   // If callee use the same argument list that caller is using, then we can
4881   // apply SCO on this case. If it is not, then we need to check if callee needs
4882   // stack for passing arguments.
4883   // PC Relative tail calls may not have a CallBase.
4884   // If there is no CallBase we cannot verify if we have the same argument
4885   // list so assume that we don't have the same argument list.
4886   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4887       needStackSlotPassParameters(Subtarget, Outs))
4888     return false;
4889   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4890     return false;
4891 
4892   return true;
4893 }
4894 
4895 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4896 /// for tail call optimization. Targets which want to do tail call
4897 /// optimization should implement this function.
4898 bool
4899 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4900                                                      CallingConv::ID CalleeCC,
4901                                                      bool isVarArg,
4902                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4903                                                      SelectionDAG& DAG) const {
4904   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4905     return false;
4906 
4907   // Variable argument functions are not supported.
4908   if (isVarArg)
4909     return false;
4910 
4911   MachineFunction &MF = DAG.getMachineFunction();
4912   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4913   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4914     // Functions containing by val parameters are not supported.
4915     for (unsigned i = 0; i != Ins.size(); i++) {
4916        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4917        if (Flags.isByVal()) return false;
4918     }
4919 
4920     // Non-PIC/GOT tail calls are supported.
4921     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4922       return true;
4923 
4924     // At the moment we can only do local tail calls (in same module, hidden
4925     // or protected) if we are generating PIC.
4926     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4927       return G->getGlobal()->hasHiddenVisibility()
4928           || G->getGlobal()->hasProtectedVisibility();
4929   }
4930 
4931   return false;
4932 }
4933 
4934 /// isCallCompatibleAddress - Return the immediate to use if the specified
4935 /// 32-bit value is representable in the immediate field of a BxA instruction.
4936 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4937   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4938   if (!C) return nullptr;
4939 
4940   int Addr = C->getZExtValue();
4941   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4942       SignExtend32<26>(Addr) != Addr)
4943     return nullptr;  // Top 6 bits have to be sext of immediate.
4944 
4945   return DAG
4946       .getConstant(
4947           (int)C->getZExtValue() >> 2, SDLoc(Op),
4948           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4949       .getNode();
4950 }
4951 
4952 namespace {
4953 
4954 struct TailCallArgumentInfo {
4955   SDValue Arg;
4956   SDValue FrameIdxOp;
4957   int FrameIdx = 0;
4958 
4959   TailCallArgumentInfo() = default;
4960 };
4961 
4962 } // end anonymous namespace
4963 
4964 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4965 static void StoreTailCallArgumentsToStackSlot(
4966     SelectionDAG &DAG, SDValue Chain,
4967     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4968     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4969   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4970     SDValue Arg = TailCallArgs[i].Arg;
4971     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4972     int FI = TailCallArgs[i].FrameIdx;
4973     // Store relative to framepointer.
4974     MemOpChains.push_back(DAG.getStore(
4975         Chain, dl, Arg, FIN,
4976         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4977   }
4978 }
4979 
4980 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4981 /// the appropriate stack slot for the tail call optimized function call.
4982 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4983                                              SDValue OldRetAddr, SDValue OldFP,
4984                                              int SPDiff, const SDLoc &dl) {
4985   if (SPDiff) {
4986     // Calculate the new stack slot for the return address.
4987     MachineFunction &MF = DAG.getMachineFunction();
4988     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4989     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4990     bool isPPC64 = Subtarget.isPPC64();
4991     int SlotSize = isPPC64 ? 8 : 4;
4992     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4993     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4994                                                          NewRetAddrLoc, true);
4995     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4996     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4997     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4998                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4999   }
5000   return Chain;
5001 }
5002 
5003 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5004 /// the position of the argument.
5005 static void
5006 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5007                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5008                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5009   int Offset = ArgOffset + SPDiff;
5010   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5011   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5012   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5013   SDValue FIN = DAG.getFrameIndex(FI, VT);
5014   TailCallArgumentInfo Info;
5015   Info.Arg = Arg;
5016   Info.FrameIdxOp = FIN;
5017   Info.FrameIdx = FI;
5018   TailCallArguments.push_back(Info);
5019 }
5020 
5021 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5022 /// stack slot. Returns the chain as result and the loaded frame pointers in
5023 /// LROpOut/FPOpout. Used when tail calling.
5024 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5025     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5026     SDValue &FPOpOut, const SDLoc &dl) const {
5027   if (SPDiff) {
5028     // Load the LR and FP stack slot for later adjusting.
5029     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5030     LROpOut = getReturnAddrFrameIndex(DAG);
5031     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5032     Chain = SDValue(LROpOut.getNode(), 1);
5033   }
5034   return Chain;
5035 }
5036 
5037 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5038 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5039 /// specified by the specific parameter attribute. The copy will be passed as
5040 /// a byval function parameter.
5041 /// Sometimes what we are copying is the end of a larger object, the part that
5042 /// does not fit in registers.
5043 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5044                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5045                                          SelectionDAG &DAG, const SDLoc &dl) {
5046   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5047   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5048                        Flags.getNonZeroByValAlign(), false, false, false,
5049                        MachinePointerInfo(), MachinePointerInfo());
5050 }
5051 
5052 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5053 /// tail calls.
5054 static void LowerMemOpCallTo(
5055     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5056     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5057     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5058     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5059   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5060   if (!isTailCall) {
5061     if (isVector) {
5062       SDValue StackPtr;
5063       if (isPPC64)
5064         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5065       else
5066         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5067       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5068                            DAG.getConstant(ArgOffset, dl, PtrVT));
5069     }
5070     MemOpChains.push_back(
5071         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5072     // Calculate and remember argument location.
5073   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5074                                   TailCallArguments);
5075 }
5076 
5077 static void
5078 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5079                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5080                 SDValue FPOp,
5081                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5082   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5083   // might overwrite each other in case of tail call optimization.
5084   SmallVector<SDValue, 8> MemOpChains2;
5085   // Do not flag preceding copytoreg stuff together with the following stuff.
5086   InFlag = SDValue();
5087   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5088                                     MemOpChains2, dl);
5089   if (!MemOpChains2.empty())
5090     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5091 
5092   // Store the return address to the appropriate stack slot.
5093   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5094 
5095   // Emit callseq_end just before tailcall node.
5096   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5097                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5098   InFlag = Chain.getValue(1);
5099 }
5100 
5101 // Is this global address that of a function that can be called by name? (as
5102 // opposed to something that must hold a descriptor for an indirect call).
5103 static bool isFunctionGlobalAddress(SDValue Callee) {
5104   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5105     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5106         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5107       return false;
5108 
5109     return G->getGlobal()->getValueType()->isFunctionTy();
5110   }
5111 
5112   return false;
5113 }
5114 
5115 SDValue PPCTargetLowering::LowerCallResult(
5116     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5117     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5118     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5119   SmallVector<CCValAssign, 16> RVLocs;
5120   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5121                     *DAG.getContext());
5122 
5123   CCRetInfo.AnalyzeCallResult(
5124       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5125                ? RetCC_PPC_Cold
5126                : RetCC_PPC);
5127 
5128   // Copy all of the result registers out of their specified physreg.
5129   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5130     CCValAssign &VA = RVLocs[i];
5131     assert(VA.isRegLoc() && "Can only return in registers!");
5132 
5133     SDValue Val;
5134 
5135     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5136       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5137                                       InFlag);
5138       Chain = Lo.getValue(1);
5139       InFlag = Lo.getValue(2);
5140       VA = RVLocs[++i]; // skip ahead to next loc
5141       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5142                                       InFlag);
5143       Chain = Hi.getValue(1);
5144       InFlag = Hi.getValue(2);
5145       if (!Subtarget.isLittleEndian())
5146         std::swap (Lo, Hi);
5147       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5148     } else {
5149       Val = DAG.getCopyFromReg(Chain, dl,
5150                                VA.getLocReg(), VA.getLocVT(), InFlag);
5151       Chain = Val.getValue(1);
5152       InFlag = Val.getValue(2);
5153     }
5154 
5155     switch (VA.getLocInfo()) {
5156     default: llvm_unreachable("Unknown loc info!");
5157     case CCValAssign::Full: break;
5158     case CCValAssign::AExt:
5159       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5160       break;
5161     case CCValAssign::ZExt:
5162       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5163                         DAG.getValueType(VA.getValVT()));
5164       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5165       break;
5166     case CCValAssign::SExt:
5167       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5168                         DAG.getValueType(VA.getValVT()));
5169       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5170       break;
5171     }
5172 
5173     InVals.push_back(Val);
5174   }
5175 
5176   return Chain;
5177 }
5178 
5179 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5180                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5181   // PatchPoint calls are not indirect.
5182   if (isPatchPoint)
5183     return false;
5184 
5185   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5186     return false;
5187 
5188   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5189   // becuase the immediate function pointer points to a descriptor instead of
5190   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5191   // pointer immediate points to the global entry point, while the BLA would
5192   // need to jump to the local entry point (see rL211174).
5193   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5194       isBLACompatibleAddress(Callee, DAG))
5195     return false;
5196 
5197   return true;
5198 }
5199 
5200 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5201 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5202   return Subtarget.isAIXABI() ||
5203          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5204 }
5205 
5206 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5207                               const Function &Caller, const SDValue &Callee,
5208                               const PPCSubtarget &Subtarget,
5209                               const TargetMachine &TM,
5210                               bool IsStrictFPCall = false) {
5211   if (CFlags.IsTailCall)
5212     return PPCISD::TC_RETURN;
5213 
5214   unsigned RetOpc = 0;
5215   // This is a call through a function pointer.
5216   if (CFlags.IsIndirect) {
5217     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5218     // indirect calls. The save of the caller's TOC pointer to the stack will be
5219     // inserted into the DAG as part of call lowering. The restore of the TOC
5220     // pointer is modeled by using a pseudo instruction for the call opcode that
5221     // represents the 2 instruction sequence of an indirect branch and link,
5222     // immediately followed by a load of the TOC pointer from the the stack save
5223     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5224     // as it is not saved or used.
5225     RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5226                                                  : PPCISD::BCTRL;
5227   } else if (Subtarget.isUsingPCRelativeCalls()) {
5228     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5229     RetOpc = PPCISD::CALL_NOTOC;
5230   } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5231     // The ABIs that maintain a TOC pointer accross calls need to have a nop
5232     // immediately following the call instruction if the caller and callee may
5233     // have different TOC bases. At link time if the linker determines the calls
5234     // may not share a TOC base, the call is redirected to a trampoline inserted
5235     // by the linker. The trampoline will (among other things) save the callers
5236     // TOC pointer at an ABI designated offset in the linkage area and the
5237     // linker will rewrite the nop to be a load of the TOC pointer from the
5238     // linkage area into gpr2.
5239     RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5240                                                     : PPCISD::CALL_NOP;
5241   else
5242     RetOpc = PPCISD::CALL;
5243   if (IsStrictFPCall) {
5244     switch (RetOpc) {
5245     default:
5246       llvm_unreachable("Unknown call opcode");
5247     case PPCISD::BCTRL_LOAD_TOC:
5248       RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5249       break;
5250     case PPCISD::BCTRL:
5251       RetOpc = PPCISD::BCTRL_RM;
5252       break;
5253     case PPCISD::CALL_NOTOC:
5254       RetOpc = PPCISD::CALL_NOTOC_RM;
5255       break;
5256     case PPCISD::CALL:
5257       RetOpc = PPCISD::CALL_RM;
5258       break;
5259     case PPCISD::CALL_NOP:
5260       RetOpc = PPCISD::CALL_NOP_RM;
5261       break;
5262     }
5263   }
5264   return RetOpc;
5265 }
5266 
5267 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5268                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5269   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5270     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5271       return SDValue(Dest, 0);
5272 
5273   // Returns true if the callee is local, and false otherwise.
5274   auto isLocalCallee = [&]() {
5275     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5276     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5277     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5278 
5279     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5280            !isa_and_nonnull<GlobalIFunc>(GV);
5281   };
5282 
5283   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5284   // a static relocation model causes some versions of GNU LD (2.17.50, at
5285   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5286   // built with secure-PLT.
5287   bool UsePlt =
5288       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5289       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5290 
5291   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5292     const TargetMachine &TM = Subtarget.getTargetMachine();
5293     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5294     MCSymbolXCOFF *S =
5295         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5296 
5297     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5298     return DAG.getMCSymbol(S, PtrVT);
5299   };
5300 
5301   if (isFunctionGlobalAddress(Callee)) {
5302     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5303 
5304     if (Subtarget.isAIXABI()) {
5305       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5306       return getAIXFuncEntryPointSymbolSDNode(GV);
5307     }
5308     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5309                                       UsePlt ? PPCII::MO_PLT : 0);
5310   }
5311 
5312   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5313     const char *SymName = S->getSymbol();
5314     if (Subtarget.isAIXABI()) {
5315       // If there exists a user-declared function whose name is the same as the
5316       // ExternalSymbol's, then we pick up the user-declared version.
5317       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5318       if (const Function *F =
5319               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5320         return getAIXFuncEntryPointSymbolSDNode(F);
5321 
5322       // On AIX, direct function calls reference the symbol for the function's
5323       // entry point, which is named by prepending a "." before the function's
5324       // C-linkage name. A Qualname is returned here because an external
5325       // function entry point is a csect with XTY_ER property.
5326       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5327         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5328         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5329             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5330             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5331         return Sec->getQualNameSymbol();
5332       };
5333 
5334       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5335     }
5336     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5337                                        UsePlt ? PPCII::MO_PLT : 0);
5338   }
5339 
5340   // No transformation needed.
5341   assert(Callee.getNode() && "What no callee?");
5342   return Callee;
5343 }
5344 
5345 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5346   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5347          "Expected a CALLSEQ_STARTSDNode.");
5348 
5349   // The last operand is the chain, except when the node has glue. If the node
5350   // has glue, then the last operand is the glue, and the chain is the second
5351   // last operand.
5352   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5353   if (LastValue.getValueType() != MVT::Glue)
5354     return LastValue;
5355 
5356   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5357 }
5358 
5359 // Creates the node that moves a functions address into the count register
5360 // to prepare for an indirect call instruction.
5361 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5362                                 SDValue &Glue, SDValue &Chain,
5363                                 const SDLoc &dl) {
5364   SDValue MTCTROps[] = {Chain, Callee, Glue};
5365   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5366   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5367                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5368   // The glue is the second value produced.
5369   Glue = Chain.getValue(1);
5370 }
5371 
5372 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5373                                           SDValue &Glue, SDValue &Chain,
5374                                           SDValue CallSeqStart,
5375                                           const CallBase *CB, const SDLoc &dl,
5376                                           bool hasNest,
5377                                           const PPCSubtarget &Subtarget) {
5378   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5379   // entry point, but to the function descriptor (the function entry point
5380   // address is part of the function descriptor though).
5381   // The function descriptor is a three doubleword structure with the
5382   // following fields: function entry point, TOC base address and
5383   // environment pointer.
5384   // Thus for a call through a function pointer, the following actions need
5385   // to be performed:
5386   //   1. Save the TOC of the caller in the TOC save area of its stack
5387   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5388   //   2. Load the address of the function entry point from the function
5389   //      descriptor.
5390   //   3. Load the TOC of the callee from the function descriptor into r2.
5391   //   4. Load the environment pointer from the function descriptor into
5392   //      r11.
5393   //   5. Branch to the function entry point address.
5394   //   6. On return of the callee, the TOC of the caller needs to be
5395   //      restored (this is done in FinishCall()).
5396   //
5397   // The loads are scheduled at the beginning of the call sequence, and the
5398   // register copies are flagged together to ensure that no other
5399   // operations can be scheduled in between. E.g. without flagging the
5400   // copies together, a TOC access in the caller could be scheduled between
5401   // the assignment of the callee TOC and the branch to the callee, which leads
5402   // to incorrect code.
5403 
5404   // Start by loading the function address from the descriptor.
5405   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5406   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5407                       ? (MachineMemOperand::MODereferenceable |
5408                          MachineMemOperand::MOInvariant)
5409                       : MachineMemOperand::MONone;
5410 
5411   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5412 
5413   // Registers used in building the DAG.
5414   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5415   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5416 
5417   // Offsets of descriptor members.
5418   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5419   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5420 
5421   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5422   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5423 
5424   // One load for the functions entry point address.
5425   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5426                                     Alignment, MMOFlags);
5427 
5428   // One for loading the TOC anchor for the module that contains the called
5429   // function.
5430   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5431   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5432   SDValue TOCPtr =
5433       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5434                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5435 
5436   // One for loading the environment pointer.
5437   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5438   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5439   SDValue LoadEnvPtr =
5440       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5441                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5442 
5443 
5444   // Then copy the newly loaded TOC anchor to the TOC pointer.
5445   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5446   Chain = TOCVal.getValue(0);
5447   Glue = TOCVal.getValue(1);
5448 
5449   // If the function call has an explicit 'nest' parameter, it takes the
5450   // place of the environment pointer.
5451   assert((!hasNest || !Subtarget.isAIXABI()) &&
5452          "Nest parameter is not supported on AIX.");
5453   if (!hasNest) {
5454     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5455     Chain = EnvVal.getValue(0);
5456     Glue = EnvVal.getValue(1);
5457   }
5458 
5459   // The rest of the indirect call sequence is the same as the non-descriptor
5460   // DAG.
5461   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5462 }
5463 
5464 static void
5465 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5466                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5467                   SelectionDAG &DAG,
5468                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5469                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5470                   const PPCSubtarget &Subtarget) {
5471   const bool IsPPC64 = Subtarget.isPPC64();
5472   // MVT for a general purpose register.
5473   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5474 
5475   // First operand is always the chain.
5476   Ops.push_back(Chain);
5477 
5478   // If it's a direct call pass the callee as the second operand.
5479   if (!CFlags.IsIndirect)
5480     Ops.push_back(Callee);
5481   else {
5482     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5483 
5484     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5485     // on the stack (this would have been done in `LowerCall_64SVR4` or
5486     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5487     // represents both the indirect branch and a load that restores the TOC
5488     // pointer from the linkage area. The operand for the TOC restore is an add
5489     // of the TOC save offset to the stack pointer. This must be the second
5490     // operand: after the chain input but before any other variadic arguments.
5491     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5492     // saved or used.
5493     if (isTOCSaveRestoreRequired(Subtarget)) {
5494       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5495 
5496       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5497       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5498       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5499       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5500       Ops.push_back(AddTOC);
5501     }
5502 
5503     // Add the register used for the environment pointer.
5504     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5505       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5506                                     RegVT));
5507 
5508 
5509     // Add CTR register as callee so a bctr can be emitted later.
5510     if (CFlags.IsTailCall)
5511       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5512   }
5513 
5514   // If this is a tail call add stack pointer delta.
5515   if (CFlags.IsTailCall)
5516     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5517 
5518   // Add argument registers to the end of the list so that they are known live
5519   // into the call.
5520   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5521     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5522                                   RegsToPass[i].second.getValueType()));
5523 
5524   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5525   // no way to mark dependencies as implicit here.
5526   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5527   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5528        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5529     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5530 
5531   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5532   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5533     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5534 
5535   // Add a register mask operand representing the call-preserved registers.
5536   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5537   const uint32_t *Mask =
5538       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5539   assert(Mask && "Missing call preserved mask for calling convention");
5540   Ops.push_back(DAG.getRegisterMask(Mask));
5541 
5542   // If the glue is valid, it is the last operand.
5543   if (Glue.getNode())
5544     Ops.push_back(Glue);
5545 }
5546 
5547 SDValue PPCTargetLowering::FinishCall(
5548     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5549     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5550     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5551     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5552     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5553 
5554   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5555       Subtarget.isAIXABI())
5556     setUsesTOCBasePtr(DAG);
5557 
5558   unsigned CallOpc =
5559       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5560                     Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5561 
5562   if (!CFlags.IsIndirect)
5563     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5564   else if (Subtarget.usesFunctionDescriptors())
5565     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5566                                   dl, CFlags.HasNest, Subtarget);
5567   else
5568     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5569 
5570   // Build the operand list for the call instruction.
5571   SmallVector<SDValue, 8> Ops;
5572   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5573                     SPDiff, Subtarget);
5574 
5575   // Emit tail call.
5576   if (CFlags.IsTailCall) {
5577     // Indirect tail call when using PC Relative calls do not have the same
5578     // constraints.
5579     assert(((Callee.getOpcode() == ISD::Register &&
5580              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5581             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5582             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5583             isa<ConstantSDNode>(Callee) ||
5584             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5585            "Expecting a global address, external symbol, absolute value, "
5586            "register or an indirect tail call when PC Relative calls are "
5587            "used.");
5588     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5589     assert(CallOpc == PPCISD::TC_RETURN &&
5590            "Unexpected call opcode for a tail call.");
5591     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5592     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5593   }
5594 
5595   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5596   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5597   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5598   Glue = Chain.getValue(1);
5599 
5600   // When performing tail call optimization the callee pops its arguments off
5601   // the stack. Account for this here so these bytes can be pushed back on in
5602   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5603   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5604                          getTargetMachine().Options.GuaranteedTailCallOpt)
5605                             ? NumBytes
5606                             : 0;
5607 
5608   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5609                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5610                              Glue, dl);
5611   Glue = Chain.getValue(1);
5612 
5613   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5614                          DAG, InVals);
5615 }
5616 
5617 SDValue
5618 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5619                              SmallVectorImpl<SDValue> &InVals) const {
5620   SelectionDAG &DAG                     = CLI.DAG;
5621   SDLoc &dl                             = CLI.DL;
5622   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5623   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5624   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5625   SDValue Chain                         = CLI.Chain;
5626   SDValue Callee                        = CLI.Callee;
5627   bool &isTailCall                      = CLI.IsTailCall;
5628   CallingConv::ID CallConv              = CLI.CallConv;
5629   bool isVarArg                         = CLI.IsVarArg;
5630   bool isPatchPoint                     = CLI.IsPatchPoint;
5631   const CallBase *CB                    = CLI.CB;
5632 
5633   if (isTailCall) {
5634     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5635       isTailCall = false;
5636     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5637       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5638           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5639     else
5640       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5641                                                      Ins, DAG);
5642     if (isTailCall) {
5643       ++NumTailCalls;
5644       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5645         ++NumSiblingCalls;
5646 
5647       // PC Relative calls no longer guarantee that the callee is a Global
5648       // Address Node. The callee could be an indirect tail call in which
5649       // case the SDValue for the callee could be a load (to load the address
5650       // of a function pointer) or it may be a register copy (to move the
5651       // address of the callee from a function parameter into a virtual
5652       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5653       assert((Subtarget.isUsingPCRelativeCalls() ||
5654               isa<GlobalAddressSDNode>(Callee)) &&
5655              "Callee should be an llvm::Function object.");
5656 
5657       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5658                         << "\nTCO callee: ");
5659       LLVM_DEBUG(Callee.dump());
5660     }
5661   }
5662 
5663   if (!isTailCall && CB && CB->isMustTailCall())
5664     report_fatal_error("failed to perform tail call elimination on a call "
5665                        "site marked musttail");
5666 
5667   // When long calls (i.e. indirect calls) are always used, calls are always
5668   // made via function pointer. If we have a function name, first translate it
5669   // into a pointer.
5670   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5671       !isTailCall)
5672     Callee = LowerGlobalAddress(Callee, DAG);
5673 
5674   CallFlags CFlags(
5675       CallConv, isTailCall, isVarArg, isPatchPoint,
5676       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5677       // hasNest
5678       Subtarget.is64BitELFABI() &&
5679           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5680       CLI.NoMerge);
5681 
5682   if (Subtarget.isAIXABI())
5683     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5684                          InVals, CB);
5685 
5686   assert(Subtarget.isSVR4ABI());
5687   if (Subtarget.isPPC64())
5688     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5689                             InVals, CB);
5690   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5691                           InVals, CB);
5692 }
5693 
5694 SDValue PPCTargetLowering::LowerCall_32SVR4(
5695     SDValue Chain, SDValue Callee, CallFlags CFlags,
5696     const SmallVectorImpl<ISD::OutputArg> &Outs,
5697     const SmallVectorImpl<SDValue> &OutVals,
5698     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5699     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5700     const CallBase *CB) const {
5701   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5702   // of the 32-bit SVR4 ABI stack frame layout.
5703 
5704   const CallingConv::ID CallConv = CFlags.CallConv;
5705   const bool IsVarArg = CFlags.IsVarArg;
5706   const bool IsTailCall = CFlags.IsTailCall;
5707 
5708   assert((CallConv == CallingConv::C ||
5709           CallConv == CallingConv::Cold ||
5710           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5711 
5712   const Align PtrAlign(4);
5713 
5714   MachineFunction &MF = DAG.getMachineFunction();
5715 
5716   // Mark this function as potentially containing a function that contains a
5717   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5718   // and restoring the callers stack pointer in this functions epilog. This is
5719   // done because by tail calling the called function might overwrite the value
5720   // in this function's (MF) stack pointer stack slot 0(SP).
5721   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5722       CallConv == CallingConv::Fast)
5723     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5724 
5725   // Count how many bytes are to be pushed on the stack, including the linkage
5726   // area, parameter list area and the part of the local variable space which
5727   // contains copies of aggregates which are passed by value.
5728 
5729   // Assign locations to all of the outgoing arguments.
5730   SmallVector<CCValAssign, 16> ArgLocs;
5731   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5732 
5733   // Reserve space for the linkage area on the stack.
5734   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5735                        PtrAlign);
5736   if (useSoftFloat())
5737     CCInfo.PreAnalyzeCallOperands(Outs);
5738 
5739   if (IsVarArg) {
5740     // Handle fixed and variable vector arguments differently.
5741     // Fixed vector arguments go into registers as long as registers are
5742     // available. Variable vector arguments always go into memory.
5743     unsigned NumArgs = Outs.size();
5744 
5745     for (unsigned i = 0; i != NumArgs; ++i) {
5746       MVT ArgVT = Outs[i].VT;
5747       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5748       bool Result;
5749 
5750       if (Outs[i].IsFixed) {
5751         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5752                                CCInfo);
5753       } else {
5754         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5755                                       ArgFlags, CCInfo);
5756       }
5757 
5758       if (Result) {
5759 #ifndef NDEBUG
5760         errs() << "Call operand #" << i << " has unhandled type "
5761              << EVT(ArgVT).getEVTString() << "\n";
5762 #endif
5763         llvm_unreachable(nullptr);
5764       }
5765     }
5766   } else {
5767     // All arguments are treated the same.
5768     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5769   }
5770   CCInfo.clearWasPPCF128();
5771 
5772   // Assign locations to all of the outgoing aggregate by value arguments.
5773   SmallVector<CCValAssign, 16> ByValArgLocs;
5774   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5775 
5776   // Reserve stack space for the allocations in CCInfo.
5777   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5778 
5779   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5780 
5781   // Size of the linkage area, parameter list area and the part of the local
5782   // space variable where copies of aggregates which are passed by value are
5783   // stored.
5784   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5785 
5786   // Calculate by how many bytes the stack has to be adjusted in case of tail
5787   // call optimization.
5788   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5789 
5790   // Adjust the stack pointer for the new arguments...
5791   // These operations are automatically eliminated by the prolog/epilog pass
5792   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5793   SDValue CallSeqStart = Chain;
5794 
5795   // Load the return address and frame pointer so it can be moved somewhere else
5796   // later.
5797   SDValue LROp, FPOp;
5798   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5799 
5800   // Set up a copy of the stack pointer for use loading and storing any
5801   // arguments that may not fit in the registers available for argument
5802   // passing.
5803   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5804 
5805   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5806   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5807   SmallVector<SDValue, 8> MemOpChains;
5808 
5809   bool seenFloatArg = false;
5810   // Walk the register/memloc assignments, inserting copies/loads.
5811   // i - Tracks the index into the list of registers allocated for the call
5812   // RealArgIdx - Tracks the index into the list of actual function arguments
5813   // j - Tracks the index into the list of byval arguments
5814   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5815        i != e;
5816        ++i, ++RealArgIdx) {
5817     CCValAssign &VA = ArgLocs[i];
5818     SDValue Arg = OutVals[RealArgIdx];
5819     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5820 
5821     if (Flags.isByVal()) {
5822       // Argument is an aggregate which is passed by value, thus we need to
5823       // create a copy of it in the local variable space of the current stack
5824       // frame (which is the stack frame of the caller) and pass the address of
5825       // this copy to the callee.
5826       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5827       CCValAssign &ByValVA = ByValArgLocs[j++];
5828       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5829 
5830       // Memory reserved in the local variable space of the callers stack frame.
5831       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5832 
5833       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5834       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5835                            StackPtr, PtrOff);
5836 
5837       // Create a copy of the argument in the local area of the current
5838       // stack frame.
5839       SDValue MemcpyCall =
5840         CreateCopyOfByValArgument(Arg, PtrOff,
5841                                   CallSeqStart.getNode()->getOperand(0),
5842                                   Flags, DAG, dl);
5843 
5844       // This must go outside the CALLSEQ_START..END.
5845       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5846                                                      SDLoc(MemcpyCall));
5847       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5848                              NewCallSeqStart.getNode());
5849       Chain = CallSeqStart = NewCallSeqStart;
5850 
5851       // Pass the address of the aggregate copy on the stack either in a
5852       // physical register or in the parameter list area of the current stack
5853       // frame to the callee.
5854       Arg = PtrOff;
5855     }
5856 
5857     // When useCRBits() is true, there can be i1 arguments.
5858     // It is because getRegisterType(MVT::i1) => MVT::i1,
5859     // and for other integer types getRegisterType() => MVT::i32.
5860     // Extend i1 and ensure callee will get i32.
5861     if (Arg.getValueType() == MVT::i1)
5862       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5863                         dl, MVT::i32, Arg);
5864 
5865     if (VA.isRegLoc()) {
5866       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5867       // Put argument in a physical register.
5868       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5869         bool IsLE = Subtarget.isLittleEndian();
5870         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5871                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5872         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5873         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5874                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5875         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5876                              SVal.getValue(0)));
5877       } else
5878         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5879     } else {
5880       // Put argument in the parameter list area of the current stack frame.
5881       assert(VA.isMemLoc());
5882       unsigned LocMemOffset = VA.getLocMemOffset();
5883 
5884       if (!IsTailCall) {
5885         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5886         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5887                              StackPtr, PtrOff);
5888 
5889         MemOpChains.push_back(
5890             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5891       } else {
5892         // Calculate and remember argument location.
5893         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5894                                  TailCallArguments);
5895       }
5896     }
5897   }
5898 
5899   if (!MemOpChains.empty())
5900     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5901 
5902   // Build a sequence of copy-to-reg nodes chained together with token chain
5903   // and flag operands which copy the outgoing args into the appropriate regs.
5904   SDValue InFlag;
5905   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5906     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5907                              RegsToPass[i].second, InFlag);
5908     InFlag = Chain.getValue(1);
5909   }
5910 
5911   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5912   // registers.
5913   if (IsVarArg) {
5914     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5915     SDValue Ops[] = { Chain, InFlag };
5916 
5917     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5918                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5919 
5920     InFlag = Chain.getValue(1);
5921   }
5922 
5923   if (IsTailCall)
5924     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5925                     TailCallArguments);
5926 
5927   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5928                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5929 }
5930 
5931 // Copy an argument into memory, being careful to do this outside the
5932 // call sequence for the call to which the argument belongs.
5933 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5934     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5935     SelectionDAG &DAG, const SDLoc &dl) const {
5936   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5937                         CallSeqStart.getNode()->getOperand(0),
5938                         Flags, DAG, dl);
5939   // The MEMCPY must go outside the CALLSEQ_START..END.
5940   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5941   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5942                                                  SDLoc(MemcpyCall));
5943   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5944                          NewCallSeqStart.getNode());
5945   return NewCallSeqStart;
5946 }
5947 
5948 SDValue PPCTargetLowering::LowerCall_64SVR4(
5949     SDValue Chain, SDValue Callee, CallFlags CFlags,
5950     const SmallVectorImpl<ISD::OutputArg> &Outs,
5951     const SmallVectorImpl<SDValue> &OutVals,
5952     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5953     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5954     const CallBase *CB) const {
5955   bool isELFv2ABI = Subtarget.isELFv2ABI();
5956   bool isLittleEndian = Subtarget.isLittleEndian();
5957   unsigned NumOps = Outs.size();
5958   bool IsSibCall = false;
5959   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5960 
5961   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5962   unsigned PtrByteSize = 8;
5963 
5964   MachineFunction &MF = DAG.getMachineFunction();
5965 
5966   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5967     IsSibCall = true;
5968 
5969   // Mark this function as potentially containing a function that contains a
5970   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5971   // and restoring the callers stack pointer in this functions epilog. This is
5972   // done because by tail calling the called function might overwrite the value
5973   // in this function's (MF) stack pointer stack slot 0(SP).
5974   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5975     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5976 
5977   assert(!(IsFastCall && CFlags.IsVarArg) &&
5978          "fastcc not supported on varargs functions");
5979 
5980   // Count how many bytes are to be pushed on the stack, including the linkage
5981   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5982   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5983   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5984   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5985   unsigned NumBytes = LinkageSize;
5986   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5987 
5988   static const MCPhysReg GPR[] = {
5989     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5990     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5991   };
5992   static const MCPhysReg VR[] = {
5993     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5994     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5995   };
5996 
5997   const unsigned NumGPRs = array_lengthof(GPR);
5998   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5999   const unsigned NumVRs  = array_lengthof(VR);
6000 
6001   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6002   // can be passed to the callee in registers.
6003   // For the fast calling convention, there is another check below.
6004   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6005   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6006   if (!HasParameterArea) {
6007     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6008     unsigned AvailableFPRs = NumFPRs;
6009     unsigned AvailableVRs = NumVRs;
6010     unsigned NumBytesTmp = NumBytes;
6011     for (unsigned i = 0; i != NumOps; ++i) {
6012       if (Outs[i].Flags.isNest()) continue;
6013       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6014                                  PtrByteSize, LinkageSize, ParamAreaSize,
6015                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6016         HasParameterArea = true;
6017     }
6018   }
6019 
6020   // When using the fast calling convention, we don't provide backing for
6021   // arguments that will be in registers.
6022   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6023 
6024   // Avoid allocating parameter area for fastcc functions if all the arguments
6025   // can be passed in the registers.
6026   if (IsFastCall)
6027     HasParameterArea = false;
6028 
6029   // Add up all the space actually used.
6030   for (unsigned i = 0; i != NumOps; ++i) {
6031     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6032     EVT ArgVT = Outs[i].VT;
6033     EVT OrigVT = Outs[i].ArgVT;
6034 
6035     if (Flags.isNest())
6036       continue;
6037 
6038     if (IsFastCall) {
6039       if (Flags.isByVal()) {
6040         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6041         if (NumGPRsUsed > NumGPRs)
6042           HasParameterArea = true;
6043       } else {
6044         switch (ArgVT.getSimpleVT().SimpleTy) {
6045         default: llvm_unreachable("Unexpected ValueType for argument!");
6046         case MVT::i1:
6047         case MVT::i32:
6048         case MVT::i64:
6049           if (++NumGPRsUsed <= NumGPRs)
6050             continue;
6051           break;
6052         case MVT::v4i32:
6053         case MVT::v8i16:
6054         case MVT::v16i8:
6055         case MVT::v2f64:
6056         case MVT::v2i64:
6057         case MVT::v1i128:
6058         case MVT::f128:
6059           if (++NumVRsUsed <= NumVRs)
6060             continue;
6061           break;
6062         case MVT::v4f32:
6063           if (++NumVRsUsed <= NumVRs)
6064             continue;
6065           break;
6066         case MVT::f32:
6067         case MVT::f64:
6068           if (++NumFPRsUsed <= NumFPRs)
6069             continue;
6070           break;
6071         }
6072         HasParameterArea = true;
6073       }
6074     }
6075 
6076     /* Respect alignment of argument on the stack.  */
6077     auto Alignement =
6078         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6079     NumBytes = alignTo(NumBytes, Alignement);
6080 
6081     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6082     if (Flags.isInConsecutiveRegsLast())
6083       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6084   }
6085 
6086   unsigned NumBytesActuallyUsed = NumBytes;
6087 
6088   // In the old ELFv1 ABI,
6089   // the prolog code of the callee may store up to 8 GPR argument registers to
6090   // the stack, allowing va_start to index over them in memory if its varargs.
6091   // Because we cannot tell if this is needed on the caller side, we have to
6092   // conservatively assume that it is needed.  As such, make sure we have at
6093   // least enough stack space for the caller to store the 8 GPRs.
6094   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6095   // really requires memory operands, e.g. a vararg function.
6096   if (HasParameterArea)
6097     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6098   else
6099     NumBytes = LinkageSize;
6100 
6101   // Tail call needs the stack to be aligned.
6102   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6103     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6104 
6105   int SPDiff = 0;
6106 
6107   // Calculate by how many bytes the stack has to be adjusted in case of tail
6108   // call optimization.
6109   if (!IsSibCall)
6110     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6111 
6112   // To protect arguments on the stack from being clobbered in a tail call,
6113   // force all the loads to happen before doing any other lowering.
6114   if (CFlags.IsTailCall)
6115     Chain = DAG.getStackArgumentTokenFactor(Chain);
6116 
6117   // Adjust the stack pointer for the new arguments...
6118   // These operations are automatically eliminated by the prolog/epilog pass
6119   if (!IsSibCall)
6120     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6121   SDValue CallSeqStart = Chain;
6122 
6123   // Load the return address and frame pointer so it can be move somewhere else
6124   // later.
6125   SDValue LROp, FPOp;
6126   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6127 
6128   // Set up a copy of the stack pointer for use loading and storing any
6129   // arguments that may not fit in the registers available for argument
6130   // passing.
6131   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6132 
6133   // Figure out which arguments are going to go in registers, and which in
6134   // memory.  Also, if this is a vararg function, floating point operations
6135   // must be stored to our stack, and loaded into integer regs as well, if
6136   // any integer regs are available for argument passing.
6137   unsigned ArgOffset = LinkageSize;
6138 
6139   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6140   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6141 
6142   SmallVector<SDValue, 8> MemOpChains;
6143   for (unsigned i = 0; i != NumOps; ++i) {
6144     SDValue Arg = OutVals[i];
6145     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6146     EVT ArgVT = Outs[i].VT;
6147     EVT OrigVT = Outs[i].ArgVT;
6148 
6149     // PtrOff will be used to store the current argument to the stack if a
6150     // register cannot be found for it.
6151     SDValue PtrOff;
6152 
6153     // We re-align the argument offset for each argument, except when using the
6154     // fast calling convention, when we need to make sure we do that only when
6155     // we'll actually use a stack slot.
6156     auto ComputePtrOff = [&]() {
6157       /* Respect alignment of argument on the stack.  */
6158       auto Alignment =
6159           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6160       ArgOffset = alignTo(ArgOffset, Alignment);
6161 
6162       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6163 
6164       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6165     };
6166 
6167     if (!IsFastCall) {
6168       ComputePtrOff();
6169 
6170       /* Compute GPR index associated with argument offset.  */
6171       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6172       GPR_idx = std::min(GPR_idx, NumGPRs);
6173     }
6174 
6175     // Promote integers to 64-bit values.
6176     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6177       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6178       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6179       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6180     }
6181 
6182     // FIXME memcpy is used way more than necessary.  Correctness first.
6183     // Note: "by value" is code for passing a structure by value, not
6184     // basic types.
6185     if (Flags.isByVal()) {
6186       // Note: Size includes alignment padding, so
6187       //   struct x { short a; char b; }
6188       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6189       // These are the proper values we need for right-justifying the
6190       // aggregate in a parameter register.
6191       unsigned Size = Flags.getByValSize();
6192 
6193       // An empty aggregate parameter takes up no storage and no
6194       // registers.
6195       if (Size == 0)
6196         continue;
6197 
6198       if (IsFastCall)
6199         ComputePtrOff();
6200 
6201       // All aggregates smaller than 8 bytes must be passed right-justified.
6202       if (Size==1 || Size==2 || Size==4) {
6203         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6204         if (GPR_idx != NumGPRs) {
6205           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6206                                         MachinePointerInfo(), VT);
6207           MemOpChains.push_back(Load.getValue(1));
6208           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6209 
6210           ArgOffset += PtrByteSize;
6211           continue;
6212         }
6213       }
6214 
6215       if (GPR_idx == NumGPRs && Size < 8) {
6216         SDValue AddPtr = PtrOff;
6217         if (!isLittleEndian) {
6218           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6219                                           PtrOff.getValueType());
6220           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6221         }
6222         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6223                                                           CallSeqStart,
6224                                                           Flags, DAG, dl);
6225         ArgOffset += PtrByteSize;
6226         continue;
6227       }
6228       // Copy the object to parameter save area if it can not be entirely passed
6229       // by registers.
6230       // FIXME: we only need to copy the parts which need to be passed in
6231       // parameter save area. For the parts passed by registers, we don't need
6232       // to copy them to the stack although we need to allocate space for them
6233       // in parameter save area.
6234       if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6235         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6236                                                           CallSeqStart,
6237                                                           Flags, DAG, dl);
6238 
6239       // When a register is available, pass a small aggregate right-justified.
6240       if (Size < 8 && GPR_idx != NumGPRs) {
6241         // The easiest way to get this right-justified in a register
6242         // is to copy the structure into the rightmost portion of a
6243         // local variable slot, then load the whole slot into the
6244         // register.
6245         // FIXME: The memcpy seems to produce pretty awful code for
6246         // small aggregates, particularly for packed ones.
6247         // FIXME: It would be preferable to use the slot in the
6248         // parameter save area instead of a new local variable.
6249         SDValue AddPtr = PtrOff;
6250         if (!isLittleEndian) {
6251           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6252           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6253         }
6254         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6255                                                           CallSeqStart,
6256                                                           Flags, DAG, dl);
6257 
6258         // Load the slot into the register.
6259         SDValue Load =
6260             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6261         MemOpChains.push_back(Load.getValue(1));
6262         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6263 
6264         // Done with this argument.
6265         ArgOffset += PtrByteSize;
6266         continue;
6267       }
6268 
6269       // For aggregates larger than PtrByteSize, copy the pieces of the
6270       // object that fit into registers from the parameter save area.
6271       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6272         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6273         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6274         if (GPR_idx != NumGPRs) {
6275           unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6276           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6277           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6278                                         MachinePointerInfo(), ObjType);
6279 
6280           MemOpChains.push_back(Load.getValue(1));
6281           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6282           ArgOffset += PtrByteSize;
6283         } else {
6284           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6285           break;
6286         }
6287       }
6288       continue;
6289     }
6290 
6291     switch (Arg.getSimpleValueType().SimpleTy) {
6292     default: llvm_unreachable("Unexpected ValueType for argument!");
6293     case MVT::i1:
6294     case MVT::i32:
6295     case MVT::i64:
6296       if (Flags.isNest()) {
6297         // The 'nest' parameter, if any, is passed in R11.
6298         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6299         break;
6300       }
6301 
6302       // These can be scalar arguments or elements of an integer array type
6303       // passed directly.  Clang may use those instead of "byval" aggregate
6304       // types to avoid forcing arguments to memory unnecessarily.
6305       if (GPR_idx != NumGPRs) {
6306         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6307       } else {
6308         if (IsFastCall)
6309           ComputePtrOff();
6310 
6311         assert(HasParameterArea &&
6312                "Parameter area must exist to pass an argument in memory.");
6313         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6314                          true, CFlags.IsTailCall, false, MemOpChains,
6315                          TailCallArguments, dl);
6316         if (IsFastCall)
6317           ArgOffset += PtrByteSize;
6318       }
6319       if (!IsFastCall)
6320         ArgOffset += PtrByteSize;
6321       break;
6322     case MVT::f32:
6323     case MVT::f64: {
6324       // These can be scalar arguments or elements of a float array type
6325       // passed directly.  The latter are used to implement ELFv2 homogenous
6326       // float aggregates.
6327 
6328       // Named arguments go into FPRs first, and once they overflow, the
6329       // remaining arguments go into GPRs and then the parameter save area.
6330       // Unnamed arguments for vararg functions always go to GPRs and
6331       // then the parameter save area.  For now, put all arguments to vararg
6332       // routines always in both locations (FPR *and* GPR or stack slot).
6333       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6334       bool NeededLoad = false;
6335 
6336       // First load the argument into the next available FPR.
6337       if (FPR_idx != NumFPRs)
6338         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6339 
6340       // Next, load the argument into GPR or stack slot if needed.
6341       if (!NeedGPROrStack)
6342         ;
6343       else if (GPR_idx != NumGPRs && !IsFastCall) {
6344         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6345         // once we support fp <-> gpr moves.
6346 
6347         // In the non-vararg case, this can only ever happen in the
6348         // presence of f32 array types, since otherwise we never run
6349         // out of FPRs before running out of GPRs.
6350         SDValue ArgVal;
6351 
6352         // Double values are always passed in a single GPR.
6353         if (Arg.getValueType() != MVT::f32) {
6354           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6355 
6356         // Non-array float values are extended and passed in a GPR.
6357         } else if (!Flags.isInConsecutiveRegs()) {
6358           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6359           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6360 
6361         // If we have an array of floats, we collect every odd element
6362         // together with its predecessor into one GPR.
6363         } else if (ArgOffset % PtrByteSize != 0) {
6364           SDValue Lo, Hi;
6365           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6366           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6367           if (!isLittleEndian)
6368             std::swap(Lo, Hi);
6369           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6370 
6371         // The final element, if even, goes into the first half of a GPR.
6372         } else if (Flags.isInConsecutiveRegsLast()) {
6373           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6374           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6375           if (!isLittleEndian)
6376             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6377                                  DAG.getConstant(32, dl, MVT::i32));
6378 
6379         // Non-final even elements are skipped; they will be handled
6380         // together the with subsequent argument on the next go-around.
6381         } else
6382           ArgVal = SDValue();
6383 
6384         if (ArgVal.getNode())
6385           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6386       } else {
6387         if (IsFastCall)
6388           ComputePtrOff();
6389 
6390         // Single-precision floating-point values are mapped to the
6391         // second (rightmost) word of the stack doubleword.
6392         if (Arg.getValueType() == MVT::f32 &&
6393             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6394           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6395           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6396         }
6397 
6398         assert(HasParameterArea &&
6399                "Parameter area must exist to pass an argument in memory.");
6400         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6401                          true, CFlags.IsTailCall, false, MemOpChains,
6402                          TailCallArguments, dl);
6403 
6404         NeededLoad = true;
6405       }
6406       // When passing an array of floats, the array occupies consecutive
6407       // space in the argument area; only round up to the next doubleword
6408       // at the end of the array.  Otherwise, each float takes 8 bytes.
6409       if (!IsFastCall || NeededLoad) {
6410         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6411                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6412         if (Flags.isInConsecutiveRegsLast())
6413           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6414       }
6415       break;
6416     }
6417     case MVT::v4f32:
6418     case MVT::v4i32:
6419     case MVT::v8i16:
6420     case MVT::v16i8:
6421     case MVT::v2f64:
6422     case MVT::v2i64:
6423     case MVT::v1i128:
6424     case MVT::f128:
6425       // These can be scalar arguments or elements of a vector array type
6426       // passed directly.  The latter are used to implement ELFv2 homogenous
6427       // vector aggregates.
6428 
6429       // For a varargs call, named arguments go into VRs or on the stack as
6430       // usual; unnamed arguments always go to the stack or the corresponding
6431       // GPRs when within range.  For now, we always put the value in both
6432       // locations (or even all three).
6433       if (CFlags.IsVarArg) {
6434         assert(HasParameterArea &&
6435                "Parameter area must exist if we have a varargs call.");
6436         // We could elide this store in the case where the object fits
6437         // entirely in R registers.  Maybe later.
6438         SDValue Store =
6439             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6440         MemOpChains.push_back(Store);
6441         if (VR_idx != NumVRs) {
6442           SDValue Load =
6443               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6444           MemOpChains.push_back(Load.getValue(1));
6445           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6446         }
6447         ArgOffset += 16;
6448         for (unsigned i=0; i<16; i+=PtrByteSize) {
6449           if (GPR_idx == NumGPRs)
6450             break;
6451           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6452                                    DAG.getConstant(i, dl, PtrVT));
6453           SDValue Load =
6454               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6455           MemOpChains.push_back(Load.getValue(1));
6456           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6457         }
6458         break;
6459       }
6460 
6461       // Non-varargs Altivec params go into VRs or on the stack.
6462       if (VR_idx != NumVRs) {
6463         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6464       } else {
6465         if (IsFastCall)
6466           ComputePtrOff();
6467 
6468         assert(HasParameterArea &&
6469                "Parameter area must exist to pass an argument in memory.");
6470         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6471                          true, CFlags.IsTailCall, true, MemOpChains,
6472                          TailCallArguments, dl);
6473         if (IsFastCall)
6474           ArgOffset += 16;
6475       }
6476 
6477       if (!IsFastCall)
6478         ArgOffset += 16;
6479       break;
6480     }
6481   }
6482 
6483   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6484          "mismatch in size of parameter area");
6485   (void)NumBytesActuallyUsed;
6486 
6487   if (!MemOpChains.empty())
6488     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6489 
6490   // Check if this is an indirect call (MTCTR/BCTRL).
6491   // See prepareDescriptorIndirectCall and buildCallOperands for more
6492   // information about calls through function pointers in the 64-bit SVR4 ABI.
6493   if (CFlags.IsIndirect) {
6494     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6495     // caller in the TOC save area.
6496     if (isTOCSaveRestoreRequired(Subtarget)) {
6497       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6498       // Load r2 into a virtual register and store it to the TOC save area.
6499       setUsesTOCBasePtr(DAG);
6500       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6501       // TOC save area offset.
6502       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6503       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6504       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6505       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6506                            MachinePointerInfo::getStack(
6507                                DAG.getMachineFunction(), TOCSaveOffset));
6508     }
6509     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6510     // This does not mean the MTCTR instruction must use R12; it's easier
6511     // to model this as an extra parameter, so do that.
6512     if (isELFv2ABI && !CFlags.IsPatchPoint)
6513       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6514   }
6515 
6516   // Build a sequence of copy-to-reg nodes chained together with token chain
6517   // and flag operands which copy the outgoing args into the appropriate regs.
6518   SDValue InFlag;
6519   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6520     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6521                              RegsToPass[i].second, InFlag);
6522     InFlag = Chain.getValue(1);
6523   }
6524 
6525   if (CFlags.IsTailCall && !IsSibCall)
6526     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6527                     TailCallArguments);
6528 
6529   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6530                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6531 }
6532 
6533 // Returns true when the shadow of a general purpose argument register
6534 // in the parameter save area is aligned to at least 'RequiredAlign'.
6535 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6536   assert(RequiredAlign.value() <= 16 &&
6537          "Required alignment greater than stack alignment.");
6538   switch (Reg) {
6539   default:
6540     report_fatal_error("called on invalid register.");
6541   case PPC::R5:
6542   case PPC::R9:
6543   case PPC::X3:
6544   case PPC::X5:
6545   case PPC::X7:
6546   case PPC::X9:
6547     // These registers are 16 byte aligned which is the most strict aligment
6548     // we can support.
6549     return true;
6550   case PPC::R3:
6551   case PPC::R7:
6552   case PPC::X4:
6553   case PPC::X6:
6554   case PPC::X8:
6555   case PPC::X10:
6556     // The shadow of these registers in the PSA is 8 byte aligned.
6557     return RequiredAlign <= 8;
6558   case PPC::R4:
6559   case PPC::R6:
6560   case PPC::R8:
6561   case PPC::R10:
6562     return RequiredAlign <= 4;
6563   }
6564 }
6565 
6566 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6567                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6568                    CCState &S) {
6569   AIXCCState &State = static_cast<AIXCCState &>(S);
6570   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6571       State.getMachineFunction().getSubtarget());
6572   const bool IsPPC64 = Subtarget.isPPC64();
6573   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6574   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6575 
6576   if (ValVT == MVT::f128)
6577     report_fatal_error("f128 is unimplemented on AIX.");
6578 
6579   if (ArgFlags.isNest())
6580     report_fatal_error("Nest arguments are unimplemented.");
6581 
6582   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6583                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6584                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6585   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6586                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6587                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6588 
6589   static const MCPhysReg VR[] = {// Vector registers.
6590                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6591                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6592                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6593 
6594   if (ArgFlags.isByVal()) {
6595     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6596       report_fatal_error("Pass-by-value arguments with alignment greater than "
6597                          "register width are not supported.");
6598 
6599     const unsigned ByValSize = ArgFlags.getByValSize();
6600 
6601     // An empty aggregate parameter takes up no storage and no registers,
6602     // but needs a MemLoc for a stack slot for the formal arguments side.
6603     if (ByValSize == 0) {
6604       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6605                                        State.getNextStackOffset(), RegVT,
6606                                        LocInfo));
6607       return false;
6608     }
6609 
6610     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6611     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6612     for (const unsigned E = Offset + StackSize; Offset < E;
6613          Offset += PtrAlign.value()) {
6614       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6615         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6616       else {
6617         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6618                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6619                                          LocInfo));
6620         break;
6621       }
6622     }
6623     return false;
6624   }
6625 
6626   // Arguments always reserve parameter save area.
6627   switch (ValVT.SimpleTy) {
6628   default:
6629     report_fatal_error("Unhandled value type for argument.");
6630   case MVT::i64:
6631     // i64 arguments should have been split to i32 for PPC32.
6632     assert(IsPPC64 && "PPC32 should have split i64 values.");
6633     LLVM_FALLTHROUGH;
6634   case MVT::i1:
6635   case MVT::i32: {
6636     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6637     // AIX integer arguments are always passed in register width.
6638     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6639       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6640                                   : CCValAssign::LocInfo::ZExt;
6641     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6642       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6643     else
6644       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6645 
6646     return false;
6647   }
6648   case MVT::f32:
6649   case MVT::f64: {
6650     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6651     const unsigned StoreSize = LocVT.getStoreSize();
6652     // Floats are always 4-byte aligned in the PSA on AIX.
6653     // This includes f64 in 64-bit mode for ABI compatibility.
6654     const unsigned Offset =
6655         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6656     unsigned FReg = State.AllocateReg(FPR);
6657     if (FReg)
6658       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6659 
6660     // Reserve and initialize GPRs or initialize the PSA as required.
6661     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6662       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6663         assert(FReg && "An FPR should be available when a GPR is reserved.");
6664         if (State.isVarArg()) {
6665           // Successfully reserved GPRs are only initialized for vararg calls.
6666           // Custom handling is required for:
6667           //   f64 in PPC32 needs to be split into 2 GPRs.
6668           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6669           State.addLoc(
6670               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6671         }
6672       } else {
6673         // If there are insufficient GPRs, the PSA needs to be initialized.
6674         // Initialization occurs even if an FPR was initialized for
6675         // compatibility with the AIX XL compiler. The full memory for the
6676         // argument will be initialized even if a prior word is saved in GPR.
6677         // A custom memLoc is used when the argument also passes in FPR so
6678         // that the callee handling can skip over it easily.
6679         State.addLoc(
6680             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6681                                              LocInfo)
6682                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6683         break;
6684       }
6685     }
6686 
6687     return false;
6688   }
6689   case MVT::v4f32:
6690   case MVT::v4i32:
6691   case MVT::v8i16:
6692   case MVT::v16i8:
6693   case MVT::v2i64:
6694   case MVT::v2f64:
6695   case MVT::v1i128: {
6696     const unsigned VecSize = 16;
6697     const Align VecAlign(VecSize);
6698 
6699     if (!State.isVarArg()) {
6700       // If there are vector registers remaining we don't consume any stack
6701       // space.
6702       if (unsigned VReg = State.AllocateReg(VR)) {
6703         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6704         return false;
6705       }
6706       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6707       // might be allocated in the portion of the PSA that is shadowed by the
6708       // GPRs.
6709       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6710       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6711       return false;
6712     }
6713 
6714     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6715     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6716 
6717     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6718     // Burn any underaligned registers and their shadowed stack space until
6719     // we reach the required alignment.
6720     while (NextRegIndex != GPRs.size() &&
6721            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6722       // Shadow allocate register and its stack shadow.
6723       unsigned Reg = State.AllocateReg(GPRs);
6724       State.AllocateStack(PtrSize, PtrAlign);
6725       assert(Reg && "Allocating register unexpectedly failed.");
6726       (void)Reg;
6727       NextRegIndex = State.getFirstUnallocated(GPRs);
6728     }
6729 
6730     // Vectors that are passed as fixed arguments are handled differently.
6731     // They are passed in VRs if any are available (unlike arguments passed
6732     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6733     // functions)
6734     if (State.isFixed(ValNo)) {
6735       if (unsigned VReg = State.AllocateReg(VR)) {
6736         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6737         // Shadow allocate GPRs and stack space even though we pass in a VR.
6738         for (unsigned I = 0; I != VecSize; I += PtrSize)
6739           State.AllocateReg(GPRs);
6740         State.AllocateStack(VecSize, VecAlign);
6741         return false;
6742       }
6743       // No vector registers remain so pass on the stack.
6744       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6745       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6746       return false;
6747     }
6748 
6749     // If all GPRS are consumed then we pass the argument fully on the stack.
6750     if (NextRegIndex == GPRs.size()) {
6751       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6752       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6753       return false;
6754     }
6755 
6756     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6757     // half of the argument, and then need to pass the remaining half on the
6758     // stack.
6759     if (GPRs[NextRegIndex] == PPC::R9) {
6760       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6761       State.addLoc(
6762           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6763 
6764       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6765       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6766       assert(FirstReg && SecondReg &&
6767              "Allocating R9 or R10 unexpectedly failed.");
6768       State.addLoc(
6769           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6770       State.addLoc(
6771           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6772       return false;
6773     }
6774 
6775     // We have enough GPRs to fully pass the vector argument, and we have
6776     // already consumed any underaligned registers. Start with the custom
6777     // MemLoc and then the custom RegLocs.
6778     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6779     State.addLoc(
6780         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6781     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6782       const unsigned Reg = State.AllocateReg(GPRs);
6783       assert(Reg && "Failed to allocated register for vararg vector argument");
6784       State.addLoc(
6785           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6786     }
6787     return false;
6788   }
6789   }
6790   return true;
6791 }
6792 
6793 // So far, this function is only used by LowerFormalArguments_AIX()
6794 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6795                                                     bool IsPPC64,
6796                                                     bool HasP8Vector,
6797                                                     bool HasVSX) {
6798   assert((IsPPC64 || SVT != MVT::i64) &&
6799          "i64 should have been split for 32-bit codegen.");
6800 
6801   switch (SVT) {
6802   default:
6803     report_fatal_error("Unexpected value type for formal argument");
6804   case MVT::i1:
6805   case MVT::i32:
6806   case MVT::i64:
6807     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6808   case MVT::f32:
6809     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6810   case MVT::f64:
6811     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6812   case MVT::v4f32:
6813   case MVT::v4i32:
6814   case MVT::v8i16:
6815   case MVT::v16i8:
6816   case MVT::v2i64:
6817   case MVT::v2f64:
6818   case MVT::v1i128:
6819     return &PPC::VRRCRegClass;
6820   }
6821 }
6822 
6823 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6824                                         SelectionDAG &DAG, SDValue ArgValue,
6825                                         MVT LocVT, const SDLoc &dl) {
6826   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6827   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6828 
6829   if (Flags.isSExt())
6830     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6831                            DAG.getValueType(ValVT));
6832   else if (Flags.isZExt())
6833     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6834                            DAG.getValueType(ValVT));
6835 
6836   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6837 }
6838 
6839 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6840   const unsigned LASize = FL->getLinkageSize();
6841 
6842   if (PPC::GPRCRegClass.contains(Reg)) {
6843     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6844            "Reg must be a valid argument register!");
6845     return LASize + 4 * (Reg - PPC::R3);
6846   }
6847 
6848   if (PPC::G8RCRegClass.contains(Reg)) {
6849     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6850            "Reg must be a valid argument register!");
6851     return LASize + 8 * (Reg - PPC::X3);
6852   }
6853 
6854   llvm_unreachable("Only general purpose registers expected.");
6855 }
6856 
6857 //   AIX ABI Stack Frame Layout:
6858 //
6859 //   Low Memory +--------------------------------------------+
6860 //   SP   +---> | Back chain                                 | ---+
6861 //        |     +--------------------------------------------+    |
6862 //        |     | Saved Condition Register                   |    |
6863 //        |     +--------------------------------------------+    |
6864 //        |     | Saved Linkage Register                     |    |
6865 //        |     +--------------------------------------------+    | Linkage Area
6866 //        |     | Reserved for compilers                     |    |
6867 //        |     +--------------------------------------------+    |
6868 //        |     | Reserved for binders                       |    |
6869 //        |     +--------------------------------------------+    |
6870 //        |     | Saved TOC pointer                          | ---+
6871 //        |     +--------------------------------------------+
6872 //        |     | Parameter save area                        |
6873 //        |     +--------------------------------------------+
6874 //        |     | Alloca space                               |
6875 //        |     +--------------------------------------------+
6876 //        |     | Local variable space                       |
6877 //        |     +--------------------------------------------+
6878 //        |     | Float/int conversion temporary             |
6879 //        |     +--------------------------------------------+
6880 //        |     | Save area for AltiVec registers            |
6881 //        |     +--------------------------------------------+
6882 //        |     | AltiVec alignment padding                  |
6883 //        |     +--------------------------------------------+
6884 //        |     | Save area for VRSAVE register              |
6885 //        |     +--------------------------------------------+
6886 //        |     | Save area for General Purpose registers    |
6887 //        |     +--------------------------------------------+
6888 //        |     | Save area for Floating Point registers     |
6889 //        |     +--------------------------------------------+
6890 //        +---- | Back chain                                 |
6891 // High Memory  +--------------------------------------------+
6892 //
6893 //  Specifications:
6894 //  AIX 7.2 Assembler Language Reference
6895 //  Subroutine linkage convention
6896 
6897 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6898     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6899     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6900     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6901 
6902   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6903           CallConv == CallingConv::Fast) &&
6904          "Unexpected calling convention!");
6905 
6906   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6907     report_fatal_error("Tail call support is unimplemented on AIX.");
6908 
6909   if (useSoftFloat())
6910     report_fatal_error("Soft float support is unimplemented on AIX.");
6911 
6912   const PPCSubtarget &Subtarget =
6913       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6914 
6915   const bool IsPPC64 = Subtarget.isPPC64();
6916   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6917 
6918   // Assign locations to all of the incoming arguments.
6919   SmallVector<CCValAssign, 16> ArgLocs;
6920   MachineFunction &MF = DAG.getMachineFunction();
6921   MachineFrameInfo &MFI = MF.getFrameInfo();
6922   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6923   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6924 
6925   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6926   // Reserve space for the linkage area on the stack.
6927   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6928   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6929   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6930 
6931   SmallVector<SDValue, 8> MemOps;
6932 
6933   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6934     CCValAssign &VA = ArgLocs[I++];
6935     MVT LocVT = VA.getLocVT();
6936     MVT ValVT = VA.getValVT();
6937     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6938     // For compatibility with the AIX XL compiler, the float args in the
6939     // parameter save area are initialized even if the argument is available
6940     // in register.  The caller is required to initialize both the register
6941     // and memory, however, the callee can choose to expect it in either.
6942     // The memloc is dismissed here because the argument is retrieved from
6943     // the register.
6944     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6945       continue;
6946 
6947     auto HandleMemLoc = [&]() {
6948       const unsigned LocSize = LocVT.getStoreSize();
6949       const unsigned ValSize = ValVT.getStoreSize();
6950       assert((ValSize <= LocSize) &&
6951              "Object size is larger than size of MemLoc");
6952       int CurArgOffset = VA.getLocMemOffset();
6953       // Objects are right-justified because AIX is big-endian.
6954       if (LocSize > ValSize)
6955         CurArgOffset += LocSize - ValSize;
6956       // Potential tail calls could cause overwriting of argument stack slots.
6957       const bool IsImmutable =
6958           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6959             (CallConv == CallingConv::Fast));
6960       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6961       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6962       SDValue ArgValue =
6963           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6964       InVals.push_back(ArgValue);
6965     };
6966 
6967     // Vector arguments to VaArg functions are passed both on the stack, and
6968     // in any available GPRs. Load the value from the stack and add the GPRs
6969     // as live ins.
6970     if (VA.isMemLoc() && VA.needsCustom()) {
6971       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6972       assert(isVarArg && "Only use custom memloc for vararg.");
6973       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6974       // matching custom RegLocs.
6975       const unsigned OriginalValNo = VA.getValNo();
6976       (void)OriginalValNo;
6977 
6978       auto HandleCustomVecRegLoc = [&]() {
6979         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6980                "Missing custom RegLoc.");
6981         VA = ArgLocs[I++];
6982         assert(VA.getValVT().isVector() &&
6983                "Unexpected Val type for custom RegLoc.");
6984         assert(VA.getValNo() == OriginalValNo &&
6985                "ValNo mismatch between custom MemLoc and RegLoc.");
6986         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6987         MF.addLiveIn(VA.getLocReg(),
6988                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6989                                        Subtarget.hasVSX()));
6990       };
6991 
6992       HandleMemLoc();
6993       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6994       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6995       // R10.
6996       HandleCustomVecRegLoc();
6997       HandleCustomVecRegLoc();
6998 
6999       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7000       // we passed the vector in R5, R6, R7 and R8.
7001       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7002         assert(!IsPPC64 &&
7003                "Only 2 custom RegLocs expected for 64-bit codegen.");
7004         HandleCustomVecRegLoc();
7005         HandleCustomVecRegLoc();
7006       }
7007 
7008       continue;
7009     }
7010 
7011     if (VA.isRegLoc()) {
7012       if (VA.getValVT().isScalarInteger())
7013         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7014       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7015         switch (VA.getValVT().SimpleTy) {
7016         default:
7017           report_fatal_error("Unhandled value type for argument.");
7018         case MVT::f32:
7019           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7020           break;
7021         case MVT::f64:
7022           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7023           break;
7024         }
7025       } else if (VA.getValVT().isVector()) {
7026         switch (VA.getValVT().SimpleTy) {
7027         default:
7028           report_fatal_error("Unhandled value type for argument.");
7029         case MVT::v16i8:
7030           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7031           break;
7032         case MVT::v8i16:
7033           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7034           break;
7035         case MVT::v4i32:
7036         case MVT::v2i64:
7037         case MVT::v1i128:
7038           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7039           break;
7040         case MVT::v4f32:
7041         case MVT::v2f64:
7042           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7043           break;
7044         }
7045       }
7046     }
7047 
7048     if (Flags.isByVal() && VA.isMemLoc()) {
7049       const unsigned Size =
7050           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7051                   PtrByteSize);
7052       const int FI = MF.getFrameInfo().CreateFixedObject(
7053           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7054           /* IsAliased */ true);
7055       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7056       InVals.push_back(FIN);
7057 
7058       continue;
7059     }
7060 
7061     if (Flags.isByVal()) {
7062       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7063 
7064       const MCPhysReg ArgReg = VA.getLocReg();
7065       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7066 
7067       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7068         report_fatal_error("Over aligned byvals not supported yet.");
7069 
7070       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7071       const int FI = MF.getFrameInfo().CreateFixedObject(
7072           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7073           /* IsAliased */ true);
7074       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7075       InVals.push_back(FIN);
7076 
7077       // Add live ins for all the RegLocs for the same ByVal.
7078       const TargetRegisterClass *RegClass =
7079           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7080 
7081       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7082                                                unsigned Offset) {
7083         const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7084         // Since the callers side has left justified the aggregate in the
7085         // register, we can simply store the entire register into the stack
7086         // slot.
7087         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7088         // The store to the fixedstack object is needed becuase accessing a
7089         // field of the ByVal will use a gep and load. Ideally we will optimize
7090         // to extracting the value from the register directly, and elide the
7091         // stores when the arguments address is not taken, but that will need to
7092         // be future work.
7093         SDValue Store = DAG.getStore(
7094             CopyFrom.getValue(1), dl, CopyFrom,
7095             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7096             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7097 
7098         MemOps.push_back(Store);
7099       };
7100 
7101       unsigned Offset = 0;
7102       HandleRegLoc(VA.getLocReg(), Offset);
7103       Offset += PtrByteSize;
7104       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7105            Offset += PtrByteSize) {
7106         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7107                "RegLocs should be for ByVal argument.");
7108 
7109         const CCValAssign RL = ArgLocs[I++];
7110         HandleRegLoc(RL.getLocReg(), Offset);
7111         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7112       }
7113 
7114       if (Offset != StackSize) {
7115         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7116                "Expected MemLoc for remaining bytes.");
7117         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7118         // Consume the MemLoc.The InVal has already been emitted, so nothing
7119         // more needs to be done.
7120         ++I;
7121       }
7122 
7123       continue;
7124     }
7125 
7126     if (VA.isRegLoc() && !VA.needsCustom()) {
7127       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7128       Register VReg =
7129           MF.addLiveIn(VA.getLocReg(),
7130                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7131                                          Subtarget.hasVSX()));
7132       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7133       if (ValVT.isScalarInteger() &&
7134           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7135         ArgValue =
7136             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7137       }
7138       InVals.push_back(ArgValue);
7139       continue;
7140     }
7141     if (VA.isMemLoc()) {
7142       HandleMemLoc();
7143       continue;
7144     }
7145   }
7146 
7147   // On AIX a minimum of 8 words is saved to the parameter save area.
7148   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7149   // Area that is at least reserved in the caller of this function.
7150   unsigned CallerReservedArea =
7151       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7152 
7153   // Set the size that is at least reserved in caller of this function. Tail
7154   // call optimized function's reserved stack space needs to be aligned so
7155   // that taking the difference between two stack areas will result in an
7156   // aligned stack.
7157   CallerReservedArea =
7158       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7159   FuncInfo->setMinReservedArea(CallerReservedArea);
7160 
7161   if (isVarArg) {
7162     FuncInfo->setVarArgsFrameIndex(
7163         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7164     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7165 
7166     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7167                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7168 
7169     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7170                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7171     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7172 
7173     // The fixed integer arguments of a variadic function are stored to the
7174     // VarArgsFrameIndex on the stack so that they may be loaded by
7175     // dereferencing the result of va_next.
7176     for (unsigned GPRIndex =
7177              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7178          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7179 
7180       const Register VReg =
7181           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7182                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7183 
7184       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7185       SDValue Store =
7186           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7187       MemOps.push_back(Store);
7188       // Increment the address for the next argument to store.
7189       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7190       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7191     }
7192   }
7193 
7194   if (!MemOps.empty())
7195     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7196 
7197   return Chain;
7198 }
7199 
7200 SDValue PPCTargetLowering::LowerCall_AIX(
7201     SDValue Chain, SDValue Callee, CallFlags CFlags,
7202     const SmallVectorImpl<ISD::OutputArg> &Outs,
7203     const SmallVectorImpl<SDValue> &OutVals,
7204     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7205     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7206     const CallBase *CB) const {
7207   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7208   // AIX ABI stack frame layout.
7209 
7210   assert((CFlags.CallConv == CallingConv::C ||
7211           CFlags.CallConv == CallingConv::Cold ||
7212           CFlags.CallConv == CallingConv::Fast) &&
7213          "Unexpected calling convention!");
7214 
7215   if (CFlags.IsPatchPoint)
7216     report_fatal_error("This call type is unimplemented on AIX.");
7217 
7218   const PPCSubtarget& Subtarget =
7219       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7220 
7221   MachineFunction &MF = DAG.getMachineFunction();
7222   SmallVector<CCValAssign, 16> ArgLocs;
7223   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7224                     *DAG.getContext());
7225 
7226   // Reserve space for the linkage save area (LSA) on the stack.
7227   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7228   //   [SP][CR][LR][2 x reserved][TOC].
7229   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7230   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7231   const bool IsPPC64 = Subtarget.isPPC64();
7232   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7233   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7234   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7235   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7236 
7237   // The prolog code of the callee may store up to 8 GPR argument registers to
7238   // the stack, allowing va_start to index over them in memory if the callee
7239   // is variadic.
7240   // Because we cannot tell if this is needed on the caller side, we have to
7241   // conservatively assume that it is needed.  As such, make sure we have at
7242   // least enough stack space for the caller to store the 8 GPRs.
7243   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7244   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7245                                      CCInfo.getNextStackOffset());
7246 
7247   // Adjust the stack pointer for the new arguments...
7248   // These operations are automatically eliminated by the prolog/epilog pass.
7249   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7250   SDValue CallSeqStart = Chain;
7251 
7252   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7253   SmallVector<SDValue, 8> MemOpChains;
7254 
7255   // Set up a copy of the stack pointer for loading and storing any
7256   // arguments that may not fit in the registers available for argument
7257   // passing.
7258   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7259                                    : DAG.getRegister(PPC::R1, MVT::i32);
7260 
7261   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7262     const unsigned ValNo = ArgLocs[I].getValNo();
7263     SDValue Arg = OutVals[ValNo];
7264     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7265 
7266     if (Flags.isByVal()) {
7267       const unsigned ByValSize = Flags.getByValSize();
7268 
7269       // Nothing to do for zero-sized ByVals on the caller side.
7270       if (!ByValSize) {
7271         ++I;
7272         continue;
7273       }
7274 
7275       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7276         return DAG.getExtLoad(
7277             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7278             (LoadOffset != 0)
7279                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7280                 : Arg,
7281             MachinePointerInfo(), VT);
7282       };
7283 
7284       unsigned LoadOffset = 0;
7285 
7286       // Initialize registers, which are fully occupied by the by-val argument.
7287       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7288         SDValue Load = GetLoad(PtrVT, LoadOffset);
7289         MemOpChains.push_back(Load.getValue(1));
7290         LoadOffset += PtrByteSize;
7291         const CCValAssign &ByValVA = ArgLocs[I++];
7292         assert(ByValVA.getValNo() == ValNo &&
7293                "Unexpected location for pass-by-value argument.");
7294         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7295       }
7296 
7297       if (LoadOffset == ByValSize)
7298         continue;
7299 
7300       // There must be one more loc to handle the remainder.
7301       assert(ArgLocs[I].getValNo() == ValNo &&
7302              "Expected additional location for by-value argument.");
7303 
7304       if (ArgLocs[I].isMemLoc()) {
7305         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7306         const CCValAssign &ByValVA = ArgLocs[I++];
7307         ISD::ArgFlagsTy MemcpyFlags = Flags;
7308         // Only memcpy the bytes that don't pass in register.
7309         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7310         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7311             (LoadOffset != 0)
7312                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7313                 : Arg,
7314             DAG.getObjectPtrOffset(dl, StackPtr,
7315                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7316             CallSeqStart, MemcpyFlags, DAG, dl);
7317         continue;
7318       }
7319 
7320       // Initialize the final register residue.
7321       // Any residue that occupies the final by-val arg register must be
7322       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7323       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7324       // 2 and 1 byte loads.
7325       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7326       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7327              "Unexpected register residue for by-value argument.");
7328       SDValue ResidueVal;
7329       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7330         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7331         const MVT VT =
7332             N == 1 ? MVT::i8
7333                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7334         SDValue Load = GetLoad(VT, LoadOffset);
7335         MemOpChains.push_back(Load.getValue(1));
7336         LoadOffset += N;
7337         Bytes += N;
7338 
7339         // By-val arguments are passed left-justfied in register.
7340         // Every load here needs to be shifted, otherwise a full register load
7341         // should have been used.
7342         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7343                "Unexpected load emitted during handling of pass-by-value "
7344                "argument.");
7345         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7346         EVT ShiftAmountTy =
7347             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7348         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7349         SDValue ShiftedLoad =
7350             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7351         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7352                                               ShiftedLoad)
7353                                 : ShiftedLoad;
7354       }
7355 
7356       const CCValAssign &ByValVA = ArgLocs[I++];
7357       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7358       continue;
7359     }
7360 
7361     CCValAssign &VA = ArgLocs[I++];
7362     const MVT LocVT = VA.getLocVT();
7363     const MVT ValVT = VA.getValVT();
7364 
7365     switch (VA.getLocInfo()) {
7366     default:
7367       report_fatal_error("Unexpected argument extension type.");
7368     case CCValAssign::Full:
7369       break;
7370     case CCValAssign::ZExt:
7371       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7372       break;
7373     case CCValAssign::SExt:
7374       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7375       break;
7376     }
7377 
7378     if (VA.isRegLoc() && !VA.needsCustom()) {
7379       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7380       continue;
7381     }
7382 
7383     // Vector arguments passed to VarArg functions need custom handling when
7384     // they are passed (at least partially) in GPRs.
7385     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7386       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7387       // Store value to its stack slot.
7388       SDValue PtrOff =
7389           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7390       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7391       SDValue Store =
7392           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7393       MemOpChains.push_back(Store);
7394       const unsigned OriginalValNo = VA.getValNo();
7395       // Then load the GPRs from the stack
7396       unsigned LoadOffset = 0;
7397       auto HandleCustomVecRegLoc = [&]() {
7398         assert(I != E && "Unexpected end of CCvalAssigns.");
7399         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7400                "Expected custom RegLoc.");
7401         CCValAssign RegVA = ArgLocs[I++];
7402         assert(RegVA.getValNo() == OriginalValNo &&
7403                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7404         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7405                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7406         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7407         MemOpChains.push_back(Load.getValue(1));
7408         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7409         LoadOffset += PtrByteSize;
7410       };
7411 
7412       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7413       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7414       // R10.
7415       HandleCustomVecRegLoc();
7416       HandleCustomVecRegLoc();
7417 
7418       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7419           ArgLocs[I].getValNo() == OriginalValNo) {
7420         assert(!IsPPC64 &&
7421                "Only 2 custom RegLocs expected for 64-bit codegen.");
7422         HandleCustomVecRegLoc();
7423         HandleCustomVecRegLoc();
7424       }
7425 
7426       continue;
7427     }
7428 
7429     if (VA.isMemLoc()) {
7430       SDValue PtrOff =
7431           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7432       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7433       MemOpChains.push_back(
7434           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7435 
7436       continue;
7437     }
7438 
7439     if (!ValVT.isFloatingPoint())
7440       report_fatal_error(
7441           "Unexpected register handling for calling convention.");
7442 
7443     // Custom handling is used for GPR initializations for vararg float
7444     // arguments.
7445     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7446            LocVT.isInteger() &&
7447            "Custom register handling only expected for VarArg.");
7448 
7449     SDValue ArgAsInt =
7450         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7451 
7452     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7453       // f32 in 32-bit GPR
7454       // f64 in 64-bit GPR
7455       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7456     else if (Arg.getValueType().getFixedSizeInBits() <
7457              LocVT.getFixedSizeInBits())
7458       // f32 in 64-bit GPR.
7459       RegsToPass.push_back(std::make_pair(
7460           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7461     else {
7462       // f64 in two 32-bit GPRs
7463       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7464       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7465              "Unexpected custom register for argument!");
7466       CCValAssign &GPR1 = VA;
7467       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7468                                      DAG.getConstant(32, dl, MVT::i8));
7469       RegsToPass.push_back(std::make_pair(
7470           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7471 
7472       if (I != E) {
7473         // If only 1 GPR was available, there will only be one custom GPR and
7474         // the argument will also pass in memory.
7475         CCValAssign &PeekArg = ArgLocs[I];
7476         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7477           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7478           CCValAssign &GPR2 = ArgLocs[I++];
7479           RegsToPass.push_back(std::make_pair(
7480               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7481         }
7482       }
7483     }
7484   }
7485 
7486   if (!MemOpChains.empty())
7487     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7488 
7489   // For indirect calls, we need to save the TOC base to the stack for
7490   // restoration after the call.
7491   if (CFlags.IsIndirect) {
7492     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7493     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7494     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7495     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7496     const unsigned TOCSaveOffset =
7497         Subtarget.getFrameLowering()->getTOCSaveOffset();
7498 
7499     setUsesTOCBasePtr(DAG);
7500     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7501     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7502     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7503     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7504     Chain = DAG.getStore(
7505         Val.getValue(1), dl, Val, AddPtr,
7506         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7507   }
7508 
7509   // Build a sequence of copy-to-reg nodes chained together with token chain
7510   // and flag operands which copy the outgoing args into the appropriate regs.
7511   SDValue InFlag;
7512   for (auto Reg : RegsToPass) {
7513     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7514     InFlag = Chain.getValue(1);
7515   }
7516 
7517   const int SPDiff = 0;
7518   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7519                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7520 }
7521 
7522 bool
7523 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7524                                   MachineFunction &MF, bool isVarArg,
7525                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7526                                   LLVMContext &Context) const {
7527   SmallVector<CCValAssign, 16> RVLocs;
7528   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7529   return CCInfo.CheckReturn(
7530       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7531                 ? RetCC_PPC_Cold
7532                 : RetCC_PPC);
7533 }
7534 
7535 SDValue
7536 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7537                                bool isVarArg,
7538                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7539                                const SmallVectorImpl<SDValue> &OutVals,
7540                                const SDLoc &dl, SelectionDAG &DAG) const {
7541   SmallVector<CCValAssign, 16> RVLocs;
7542   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7543                  *DAG.getContext());
7544   CCInfo.AnalyzeReturn(Outs,
7545                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7546                            ? RetCC_PPC_Cold
7547                            : RetCC_PPC);
7548 
7549   SDValue Flag;
7550   SmallVector<SDValue, 4> RetOps(1, Chain);
7551 
7552   // Copy the result values into the output registers.
7553   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7554     CCValAssign &VA = RVLocs[i];
7555     assert(VA.isRegLoc() && "Can only return in registers!");
7556 
7557     SDValue Arg = OutVals[RealResIdx];
7558 
7559     switch (VA.getLocInfo()) {
7560     default: llvm_unreachable("Unknown loc info!");
7561     case CCValAssign::Full: break;
7562     case CCValAssign::AExt:
7563       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7564       break;
7565     case CCValAssign::ZExt:
7566       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7567       break;
7568     case CCValAssign::SExt:
7569       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7570       break;
7571     }
7572     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7573       bool isLittleEndian = Subtarget.isLittleEndian();
7574       // Legalize ret f64 -> ret 2 x i32.
7575       SDValue SVal =
7576           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7577                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7578       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7579       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7580       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7581                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7582       Flag = Chain.getValue(1);
7583       VA = RVLocs[++i]; // skip ahead to next loc
7584       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7585     } else
7586       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7587     Flag = Chain.getValue(1);
7588     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7589   }
7590 
7591   RetOps[0] = Chain;  // Update chain.
7592 
7593   // Add the flag if we have it.
7594   if (Flag.getNode())
7595     RetOps.push_back(Flag);
7596 
7597   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7598 }
7599 
7600 SDValue
7601 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7602                                                 SelectionDAG &DAG) const {
7603   SDLoc dl(Op);
7604 
7605   // Get the correct type for integers.
7606   EVT IntVT = Op.getValueType();
7607 
7608   // Get the inputs.
7609   SDValue Chain = Op.getOperand(0);
7610   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7611   // Build a DYNAREAOFFSET node.
7612   SDValue Ops[2] = {Chain, FPSIdx};
7613   SDVTList VTs = DAG.getVTList(IntVT);
7614   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7615 }
7616 
7617 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7618                                              SelectionDAG &DAG) const {
7619   // When we pop the dynamic allocation we need to restore the SP link.
7620   SDLoc dl(Op);
7621 
7622   // Get the correct type for pointers.
7623   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7624 
7625   // Construct the stack pointer operand.
7626   bool isPPC64 = Subtarget.isPPC64();
7627   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7628   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7629 
7630   // Get the operands for the STACKRESTORE.
7631   SDValue Chain = Op.getOperand(0);
7632   SDValue SaveSP = Op.getOperand(1);
7633 
7634   // Load the old link SP.
7635   SDValue LoadLinkSP =
7636       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7637 
7638   // Restore the stack pointer.
7639   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7640 
7641   // Store the old link SP.
7642   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7643 }
7644 
7645 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7646   MachineFunction &MF = DAG.getMachineFunction();
7647   bool isPPC64 = Subtarget.isPPC64();
7648   EVT PtrVT = getPointerTy(MF.getDataLayout());
7649 
7650   // Get current frame pointer save index.  The users of this index will be
7651   // primarily DYNALLOC instructions.
7652   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7653   int RASI = FI->getReturnAddrSaveIndex();
7654 
7655   // If the frame pointer save index hasn't been defined yet.
7656   if (!RASI) {
7657     // Find out what the fix offset of the frame pointer save area.
7658     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7659     // Allocate the frame index for frame pointer save area.
7660     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7661     // Save the result.
7662     FI->setReturnAddrSaveIndex(RASI);
7663   }
7664   return DAG.getFrameIndex(RASI, PtrVT);
7665 }
7666 
7667 SDValue
7668 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7669   MachineFunction &MF = DAG.getMachineFunction();
7670   bool isPPC64 = Subtarget.isPPC64();
7671   EVT PtrVT = getPointerTy(MF.getDataLayout());
7672 
7673   // Get current frame pointer save index.  The users of this index will be
7674   // primarily DYNALLOC instructions.
7675   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7676   int FPSI = FI->getFramePointerSaveIndex();
7677 
7678   // If the frame pointer save index hasn't been defined yet.
7679   if (!FPSI) {
7680     // Find out what the fix offset of the frame pointer save area.
7681     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7682     // Allocate the frame index for frame pointer save area.
7683     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7684     // Save the result.
7685     FI->setFramePointerSaveIndex(FPSI);
7686   }
7687   return DAG.getFrameIndex(FPSI, PtrVT);
7688 }
7689 
7690 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7691                                                    SelectionDAG &DAG) const {
7692   MachineFunction &MF = DAG.getMachineFunction();
7693   // Get the inputs.
7694   SDValue Chain = Op.getOperand(0);
7695   SDValue Size  = Op.getOperand(1);
7696   SDLoc dl(Op);
7697 
7698   // Get the correct type for pointers.
7699   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7700   // Negate the size.
7701   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7702                                 DAG.getConstant(0, dl, PtrVT), Size);
7703   // Construct a node for the frame pointer save index.
7704   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7705   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7706   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7707   if (hasInlineStackProbe(MF))
7708     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7709   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7710 }
7711 
7712 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7713                                                      SelectionDAG &DAG) const {
7714   MachineFunction &MF = DAG.getMachineFunction();
7715 
7716   bool isPPC64 = Subtarget.isPPC64();
7717   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7718 
7719   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7720   return DAG.getFrameIndex(FI, PtrVT);
7721 }
7722 
7723 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7724                                                SelectionDAG &DAG) const {
7725   SDLoc DL(Op);
7726   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7727                      DAG.getVTList(MVT::i32, MVT::Other),
7728                      Op.getOperand(0), Op.getOperand(1));
7729 }
7730 
7731 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7732                                                 SelectionDAG &DAG) const {
7733   SDLoc DL(Op);
7734   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7735                      Op.getOperand(0), Op.getOperand(1));
7736 }
7737 
7738 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7739   if (Op.getValueType().isVector())
7740     return LowerVectorLoad(Op, DAG);
7741 
7742   assert(Op.getValueType() == MVT::i1 &&
7743          "Custom lowering only for i1 loads");
7744 
7745   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7746 
7747   SDLoc dl(Op);
7748   LoadSDNode *LD = cast<LoadSDNode>(Op);
7749 
7750   SDValue Chain = LD->getChain();
7751   SDValue BasePtr = LD->getBasePtr();
7752   MachineMemOperand *MMO = LD->getMemOperand();
7753 
7754   SDValue NewLD =
7755       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7756                      BasePtr, MVT::i8, MMO);
7757   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7758 
7759   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7760   return DAG.getMergeValues(Ops, dl);
7761 }
7762 
7763 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7764   if (Op.getOperand(1).getValueType().isVector())
7765     return LowerVectorStore(Op, DAG);
7766 
7767   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7768          "Custom lowering only for i1 stores");
7769 
7770   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7771 
7772   SDLoc dl(Op);
7773   StoreSDNode *ST = cast<StoreSDNode>(Op);
7774 
7775   SDValue Chain = ST->getChain();
7776   SDValue BasePtr = ST->getBasePtr();
7777   SDValue Value = ST->getValue();
7778   MachineMemOperand *MMO = ST->getMemOperand();
7779 
7780   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7781                       Value);
7782   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7783 }
7784 
7785 // FIXME: Remove this once the ANDI glue bug is fixed:
7786 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7787   assert(Op.getValueType() == MVT::i1 &&
7788          "Custom lowering only for i1 results");
7789 
7790   SDLoc DL(Op);
7791   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7792 }
7793 
7794 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7795                                                SelectionDAG &DAG) const {
7796 
7797   // Implements a vector truncate that fits in a vector register as a shuffle.
7798   // We want to legalize vector truncates down to where the source fits in
7799   // a vector register (and target is therefore smaller than vector register
7800   // size).  At that point legalization will try to custom lower the sub-legal
7801   // result and get here - where we can contain the truncate as a single target
7802   // operation.
7803 
7804   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7805   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7806   //
7807   // We will implement it for big-endian ordering as this (where x denotes
7808   // undefined):
7809   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7810   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7811   //
7812   // The same operation in little-endian ordering will be:
7813   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7814   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7815 
7816   EVT TrgVT = Op.getValueType();
7817   assert(TrgVT.isVector() && "Vector type expected.");
7818   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7819   EVT EltVT = TrgVT.getVectorElementType();
7820   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7821       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7822       !isPowerOf2_32(EltVT.getSizeInBits()))
7823     return SDValue();
7824 
7825   SDValue N1 = Op.getOperand(0);
7826   EVT SrcVT = N1.getValueType();
7827   unsigned SrcSize = SrcVT.getSizeInBits();
7828   if (SrcSize > 256 ||
7829       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7830       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7831     return SDValue();
7832   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7833     return SDValue();
7834 
7835   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7836   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7837 
7838   SDLoc DL(Op);
7839   SDValue Op1, Op2;
7840   if (SrcSize == 256) {
7841     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7842     EVT SplitVT =
7843         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7844     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7845     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7846                       DAG.getConstant(0, DL, VecIdxTy));
7847     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7848                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7849   }
7850   else {
7851     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7852     Op2 = DAG.getUNDEF(WideVT);
7853   }
7854 
7855   // First list the elements we want to keep.
7856   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7857   SmallVector<int, 16> ShuffV;
7858   if (Subtarget.isLittleEndian())
7859     for (unsigned i = 0; i < TrgNumElts; ++i)
7860       ShuffV.push_back(i * SizeMult);
7861   else
7862     for (unsigned i = 1; i <= TrgNumElts; ++i)
7863       ShuffV.push_back(i * SizeMult - 1);
7864 
7865   // Populate the remaining elements with undefs.
7866   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7867     // ShuffV.push_back(i + WideNumElts);
7868     ShuffV.push_back(WideNumElts + 1);
7869 
7870   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7871   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7872   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7873 }
7874 
7875 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7876 /// possible.
7877 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7878   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7879   EVT ResVT = Op.getValueType();
7880   EVT CmpVT = Op.getOperand(0).getValueType();
7881   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7882   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7883   SDLoc dl(Op);
7884 
7885   // Without power9-vector, we don't have native instruction for f128 comparison.
7886   // Following transformation to libcall is needed for setcc:
7887   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7888   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7889     SDValue Z = DAG.getSetCC(
7890         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7891         LHS, RHS, CC);
7892     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7893     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7894   }
7895 
7896   // Not FP, or using SPE? Not a fsel.
7897   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7898       Subtarget.hasSPE())
7899     return Op;
7900 
7901   SDNodeFlags Flags = Op.getNode()->getFlags();
7902 
7903   // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
7904   // presence of infinities.
7905   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7906     switch (CC) {
7907     default:
7908       break;
7909     case ISD::SETOGT:
7910     case ISD::SETGT:
7911       return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
7912     case ISD::SETOLT:
7913     case ISD::SETLT:
7914       return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
7915     }
7916   }
7917 
7918   // We might be able to do better than this under some circumstances, but in
7919   // general, fsel-based lowering of select is a finite-math-only optimization.
7920   // For more information, see section F.3 of the 2.06 ISA specification.
7921   // With ISA 3.0
7922   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7923       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7924     return Op;
7925 
7926   // If the RHS of the comparison is a 0.0, we don't need to do the
7927   // subtraction at all.
7928   SDValue Sel1;
7929   if (isFloatingPointZero(RHS))
7930     switch (CC) {
7931     default: break;       // SETUO etc aren't handled by fsel.
7932     case ISD::SETNE:
7933       std::swap(TV, FV);
7934       LLVM_FALLTHROUGH;
7935     case ISD::SETEQ:
7936       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7937         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7938       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7939       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7940         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7941       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7942                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7943     case ISD::SETULT:
7944     case ISD::SETLT:
7945       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7946       LLVM_FALLTHROUGH;
7947     case ISD::SETOGE:
7948     case ISD::SETGE:
7949       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7950         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7951       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7952     case ISD::SETUGT:
7953     case ISD::SETGT:
7954       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7955       LLVM_FALLTHROUGH;
7956     case ISD::SETOLE:
7957     case ISD::SETLE:
7958       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7959         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7960       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7961                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7962     }
7963 
7964   SDValue Cmp;
7965   switch (CC) {
7966   default: break;       // SETUO etc aren't handled by fsel.
7967   case ISD::SETNE:
7968     std::swap(TV, FV);
7969     LLVM_FALLTHROUGH;
7970   case ISD::SETEQ:
7971     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7972     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7973       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7974     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7975     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7976       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7977     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7978                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7979   case ISD::SETULT:
7980   case ISD::SETLT:
7981     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7982     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7983       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7984     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7985   case ISD::SETOGE:
7986   case ISD::SETGE:
7987     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7988     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7989       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7990     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7991   case ISD::SETUGT:
7992   case ISD::SETGT:
7993     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7994     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7995       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7996     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7997   case ISD::SETOLE:
7998   case ISD::SETLE:
7999     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8000     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8001       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8002     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8003   }
8004   return Op;
8005 }
8006 
8007 static unsigned getPPCStrictOpcode(unsigned Opc) {
8008   switch (Opc) {
8009   default:
8010     llvm_unreachable("No strict version of this opcode!");
8011   case PPCISD::FCTIDZ:
8012     return PPCISD::STRICT_FCTIDZ;
8013   case PPCISD::FCTIWZ:
8014     return PPCISD::STRICT_FCTIWZ;
8015   case PPCISD::FCTIDUZ:
8016     return PPCISD::STRICT_FCTIDUZ;
8017   case PPCISD::FCTIWUZ:
8018     return PPCISD::STRICT_FCTIWUZ;
8019   case PPCISD::FCFID:
8020     return PPCISD::STRICT_FCFID;
8021   case PPCISD::FCFIDU:
8022     return PPCISD::STRICT_FCFIDU;
8023   case PPCISD::FCFIDS:
8024     return PPCISD::STRICT_FCFIDS;
8025   case PPCISD::FCFIDUS:
8026     return PPCISD::STRICT_FCFIDUS;
8027   }
8028 }
8029 
8030 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8031                               const PPCSubtarget &Subtarget) {
8032   SDLoc dl(Op);
8033   bool IsStrict = Op->isStrictFPOpcode();
8034   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8035                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8036 
8037   // TODO: Any other flags to propagate?
8038   SDNodeFlags Flags;
8039   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8040 
8041   // For strict nodes, source is the second operand.
8042   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8043   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8044   assert(Src.getValueType().isFloatingPoint());
8045   if (Src.getValueType() == MVT::f32) {
8046     if (IsStrict) {
8047       Src =
8048           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8049                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8050       Chain = Src.getValue(1);
8051     } else
8052       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8053   }
8054   SDValue Conv;
8055   unsigned Opc = ISD::DELETED_NODE;
8056   switch (Op.getSimpleValueType().SimpleTy) {
8057   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8058   case MVT::i32:
8059     Opc = IsSigned ? PPCISD::FCTIWZ
8060                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8061     break;
8062   case MVT::i64:
8063     assert((IsSigned || Subtarget.hasFPCVT()) &&
8064            "i64 FP_TO_UINT is supported only with FPCVT");
8065     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8066   }
8067   if (IsStrict) {
8068     Opc = getPPCStrictOpcode(Opc);
8069     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8070                        {Chain, Src}, Flags);
8071   } else {
8072     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8073   }
8074   return Conv;
8075 }
8076 
8077 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8078                                                SelectionDAG &DAG,
8079                                                const SDLoc &dl) const {
8080   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8081   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8082                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8083   bool IsStrict = Op->isStrictFPOpcode();
8084 
8085   // Convert the FP value to an int value through memory.
8086   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8087                   (IsSigned || Subtarget.hasFPCVT());
8088   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8089   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8090   MachinePointerInfo MPI =
8091       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8092 
8093   // Emit a store to the stack slot.
8094   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8095   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8096   if (i32Stack) {
8097     MachineFunction &MF = DAG.getMachineFunction();
8098     Alignment = Align(4);
8099     MachineMemOperand *MMO =
8100         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8101     SDValue Ops[] = { Chain, Tmp, FIPtr };
8102     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8103               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8104   } else
8105     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8106 
8107   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8108   // add in a bias on big endian.
8109   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8110     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8111                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8112     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8113   }
8114 
8115   RLI.Chain = Chain;
8116   RLI.Ptr = FIPtr;
8117   RLI.MPI = MPI;
8118   RLI.Alignment = Alignment;
8119 }
8120 
8121 /// Custom lowers floating point to integer conversions to use
8122 /// the direct move instructions available in ISA 2.07 to avoid the
8123 /// need for load/store combinations.
8124 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8125                                                     SelectionDAG &DAG,
8126                                                     const SDLoc &dl) const {
8127   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8128   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8129   if (Op->isStrictFPOpcode())
8130     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8131   else
8132     return Mov;
8133 }
8134 
8135 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8136                                           const SDLoc &dl) const {
8137   bool IsStrict = Op->isStrictFPOpcode();
8138   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8139                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8140   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8141   EVT SrcVT = Src.getValueType();
8142   EVT DstVT = Op.getValueType();
8143 
8144   // FP to INT conversions are legal for f128.
8145   if (SrcVT == MVT::f128)
8146     return Subtarget.hasP9Vector() ? Op : SDValue();
8147 
8148   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8149   // PPC (the libcall is not available).
8150   if (SrcVT == MVT::ppcf128) {
8151     if (DstVT == MVT::i32) {
8152       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8153       // set other fast-math flags to FP operations in both strict and
8154       // non-strict cases. (FP_TO_SINT, FSUB)
8155       SDNodeFlags Flags;
8156       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8157 
8158       if (IsSigned) {
8159         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8160                                  DAG.getIntPtrConstant(0, dl));
8161         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8162                                  DAG.getIntPtrConstant(1, dl));
8163 
8164         // Add the two halves of the long double in round-to-zero mode, and use
8165         // a smaller FP_TO_SINT.
8166         if (IsStrict) {
8167           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8168                                     DAG.getVTList(MVT::f64, MVT::Other),
8169                                     {Op.getOperand(0), Lo, Hi}, Flags);
8170           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8171                              DAG.getVTList(MVT::i32, MVT::Other),
8172                              {Res.getValue(1), Res}, Flags);
8173         } else {
8174           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8175           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8176         }
8177       } else {
8178         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8179         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8180         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8181         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8182         if (IsStrict) {
8183           // Sel = Src < 0x80000000
8184           // FltOfs = select Sel, 0.0, 0x80000000
8185           // IntOfs = select Sel, 0, 0x80000000
8186           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8187           SDValue Chain = Op.getOperand(0);
8188           EVT SetCCVT =
8189               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8190           EVT DstSetCCVT =
8191               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8192           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8193                                      Chain, true);
8194           Chain = Sel.getValue(1);
8195 
8196           SDValue FltOfs = DAG.getSelect(
8197               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8198           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8199 
8200           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8201                                     DAG.getVTList(SrcVT, MVT::Other),
8202                                     {Chain, Src, FltOfs}, Flags);
8203           Chain = Val.getValue(1);
8204           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8205                                      DAG.getVTList(DstVT, MVT::Other),
8206                                      {Chain, Val}, Flags);
8207           Chain = SInt.getValue(1);
8208           SDValue IntOfs = DAG.getSelect(
8209               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8210           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8211           return DAG.getMergeValues({Result, Chain}, dl);
8212         } else {
8213           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8214           // FIXME: generated code sucks.
8215           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8216           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8217           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8218           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8219           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8220         }
8221       }
8222     }
8223 
8224     return SDValue();
8225   }
8226 
8227   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8228     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8229 
8230   ReuseLoadInfo RLI;
8231   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8232 
8233   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8234                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8235 }
8236 
8237 // We're trying to insert a regular store, S, and then a load, L. If the
8238 // incoming value, O, is a load, we might just be able to have our load use the
8239 // address used by O. However, we don't know if anything else will store to
8240 // that address before we can load from it. To prevent this situation, we need
8241 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8242 // the same chain operand as O, we create a token factor from the chain results
8243 // of O and L, and we replace all uses of O's chain result with that token
8244 // factor (see spliceIntoChain below for this last part).
8245 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8246                                             ReuseLoadInfo &RLI,
8247                                             SelectionDAG &DAG,
8248                                             ISD::LoadExtType ET) const {
8249   // Conservatively skip reusing for constrained FP nodes.
8250   if (Op->isStrictFPOpcode())
8251     return false;
8252 
8253   SDLoc dl(Op);
8254   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8255                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8256   if (ET == ISD::NON_EXTLOAD &&
8257       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8258       isOperationLegalOrCustom(Op.getOpcode(),
8259                                Op.getOperand(0).getValueType())) {
8260 
8261     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8262     return true;
8263   }
8264 
8265   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8266   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8267       LD->isNonTemporal())
8268     return false;
8269   if (LD->getMemoryVT() != MemVT)
8270     return false;
8271 
8272   // If the result of the load is an illegal type, then we can't build a
8273   // valid chain for reuse since the legalised loads and token factor node that
8274   // ties the legalised loads together uses a different output chain then the
8275   // illegal load.
8276   if (!isTypeLegal(LD->getValueType(0)))
8277     return false;
8278 
8279   RLI.Ptr = LD->getBasePtr();
8280   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8281     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8282            "Non-pre-inc AM on PPC?");
8283     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8284                           LD->getOffset());
8285   }
8286 
8287   RLI.Chain = LD->getChain();
8288   RLI.MPI = LD->getPointerInfo();
8289   RLI.IsDereferenceable = LD->isDereferenceable();
8290   RLI.IsInvariant = LD->isInvariant();
8291   RLI.Alignment = LD->getAlign();
8292   RLI.AAInfo = LD->getAAInfo();
8293   RLI.Ranges = LD->getRanges();
8294 
8295   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8296   return true;
8297 }
8298 
8299 // Given the head of the old chain, ResChain, insert a token factor containing
8300 // it and NewResChain, and make users of ResChain now be users of that token
8301 // factor.
8302 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8303 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8304                                         SDValue NewResChain,
8305                                         SelectionDAG &DAG) const {
8306   if (!ResChain)
8307     return;
8308 
8309   SDLoc dl(NewResChain);
8310 
8311   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8312                            NewResChain, DAG.getUNDEF(MVT::Other));
8313   assert(TF.getNode() != NewResChain.getNode() &&
8314          "A new TF really is required here");
8315 
8316   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8317   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8318 }
8319 
8320 /// Analyze profitability of direct move
8321 /// prefer float load to int load plus direct move
8322 /// when there is no integer use of int load
8323 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8324   SDNode *Origin = Op.getOperand(0).getNode();
8325   if (Origin->getOpcode() != ISD::LOAD)
8326     return true;
8327 
8328   // If there is no LXSIBZX/LXSIHZX, like Power8,
8329   // prefer direct move if the memory size is 1 or 2 bytes.
8330   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8331   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8332     return true;
8333 
8334   for (SDNode::use_iterator UI = Origin->use_begin(),
8335                             UE = Origin->use_end();
8336        UI != UE; ++UI) {
8337 
8338     // Only look at the users of the loaded value.
8339     if (UI.getUse().get().getResNo() != 0)
8340       continue;
8341 
8342     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8343         UI->getOpcode() != ISD::UINT_TO_FP &&
8344         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8345         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8346       return true;
8347   }
8348 
8349   return false;
8350 }
8351 
8352 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8353                               const PPCSubtarget &Subtarget,
8354                               SDValue Chain = SDValue()) {
8355   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8356                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8357   SDLoc dl(Op);
8358 
8359   // TODO: Any other flags to propagate?
8360   SDNodeFlags Flags;
8361   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8362 
8363   // If we have FCFIDS, then use it when converting to single-precision.
8364   // Otherwise, convert to double-precision and then round.
8365   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8366   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8367                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8368   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8369   if (Op->isStrictFPOpcode()) {
8370     if (!Chain)
8371       Chain = Op.getOperand(0);
8372     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8373                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8374   } else
8375     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8376 }
8377 
8378 /// Custom lowers integer to floating point conversions to use
8379 /// the direct move instructions available in ISA 2.07 to avoid the
8380 /// need for load/store combinations.
8381 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8382                                                     SelectionDAG &DAG,
8383                                                     const SDLoc &dl) const {
8384   assert((Op.getValueType() == MVT::f32 ||
8385           Op.getValueType() == MVT::f64) &&
8386          "Invalid floating point type as target of conversion");
8387   assert(Subtarget.hasFPCVT() &&
8388          "Int to FP conversions with direct moves require FPCVT");
8389   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8390   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8391   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8392                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8393   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8394   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8395   return convertIntToFP(Op, Mov, DAG, Subtarget);
8396 }
8397 
8398 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8399 
8400   EVT VecVT = Vec.getValueType();
8401   assert(VecVT.isVector() && "Expected a vector type.");
8402   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8403 
8404   EVT EltVT = VecVT.getVectorElementType();
8405   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8406   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8407 
8408   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8409   SmallVector<SDValue, 16> Ops(NumConcat);
8410   Ops[0] = Vec;
8411   SDValue UndefVec = DAG.getUNDEF(VecVT);
8412   for (unsigned i = 1; i < NumConcat; ++i)
8413     Ops[i] = UndefVec;
8414 
8415   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8416 }
8417 
8418 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8419                                                 const SDLoc &dl) const {
8420   bool IsStrict = Op->isStrictFPOpcode();
8421   unsigned Opc = Op.getOpcode();
8422   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8423   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8424           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8425          "Unexpected conversion type");
8426   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8427          "Supports conversions to v2f64/v4f32 only.");
8428 
8429   // TODO: Any other flags to propagate?
8430   SDNodeFlags Flags;
8431   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8432 
8433   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8434   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8435 
8436   SDValue Wide = widenVec(DAG, Src, dl);
8437   EVT WideVT = Wide.getValueType();
8438   unsigned WideNumElts = WideVT.getVectorNumElements();
8439   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8440 
8441   SmallVector<int, 16> ShuffV;
8442   for (unsigned i = 0; i < WideNumElts; ++i)
8443     ShuffV.push_back(i + WideNumElts);
8444 
8445   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8446   int SaveElts = FourEltRes ? 4 : 2;
8447   if (Subtarget.isLittleEndian())
8448     for (int i = 0; i < SaveElts; i++)
8449       ShuffV[i * Stride] = i;
8450   else
8451     for (int i = 1; i <= SaveElts; i++)
8452       ShuffV[i * Stride - 1] = i - 1;
8453 
8454   SDValue ShuffleSrc2 =
8455       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8456   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8457 
8458   SDValue Extend;
8459   if (SignedConv) {
8460     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8461     EVT ExtVT = Src.getValueType();
8462     if (Subtarget.hasP9Altivec())
8463       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8464                                IntermediateVT.getVectorNumElements());
8465 
8466     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8467                          DAG.getValueType(ExtVT));
8468   } else
8469     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8470 
8471   if (IsStrict)
8472     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8473                        {Op.getOperand(0), Extend}, Flags);
8474 
8475   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8476 }
8477 
8478 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8479                                           SelectionDAG &DAG) const {
8480   SDLoc dl(Op);
8481   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8482                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8483   bool IsStrict = Op->isStrictFPOpcode();
8484   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8485   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8486 
8487   // TODO: Any other flags to propagate?
8488   SDNodeFlags Flags;
8489   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8490 
8491   EVT InVT = Src.getValueType();
8492   EVT OutVT = Op.getValueType();
8493   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8494       isOperationCustom(Op.getOpcode(), InVT))
8495     return LowerINT_TO_FPVector(Op, DAG, dl);
8496 
8497   // Conversions to f128 are legal.
8498   if (Op.getValueType() == MVT::f128)
8499     return Subtarget.hasP9Vector() ? Op : SDValue();
8500 
8501   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8502   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8503     return SDValue();
8504 
8505   if (Src.getValueType() == MVT::i1) {
8506     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8507                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8508                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8509     if (IsStrict)
8510       return DAG.getMergeValues({Sel, Chain}, dl);
8511     else
8512       return Sel;
8513   }
8514 
8515   // If we have direct moves, we can do all the conversion, skip the store/load
8516   // however, without FPCVT we can't do most conversions.
8517   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8518       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8519     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8520 
8521   assert((IsSigned || Subtarget.hasFPCVT()) &&
8522          "UINT_TO_FP is supported only with FPCVT");
8523 
8524   if (Src.getValueType() == MVT::i64) {
8525     SDValue SINT = Src;
8526     // When converting to single-precision, we actually need to convert
8527     // to double-precision first and then round to single-precision.
8528     // To avoid double-rounding effects during that operation, we have
8529     // to prepare the input operand.  Bits that might be truncated when
8530     // converting to double-precision are replaced by a bit that won't
8531     // be lost at this stage, but is below the single-precision rounding
8532     // position.
8533     //
8534     // However, if -enable-unsafe-fp-math is in effect, accept double
8535     // rounding to avoid the extra overhead.
8536     if (Op.getValueType() == MVT::f32 &&
8537         !Subtarget.hasFPCVT() &&
8538         !DAG.getTarget().Options.UnsafeFPMath) {
8539 
8540       // Twiddle input to make sure the low 11 bits are zero.  (If this
8541       // is the case, we are guaranteed the value will fit into the 53 bit
8542       // mantissa of an IEEE double-precision value without rounding.)
8543       // If any of those low 11 bits were not zero originally, make sure
8544       // bit 12 (value 2048) is set instead, so that the final rounding
8545       // to single-precision gets the correct result.
8546       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8547                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8548       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8549                           Round, DAG.getConstant(2047, dl, MVT::i64));
8550       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8551       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8552                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8553 
8554       // However, we cannot use that value unconditionally: if the magnitude
8555       // of the input value is small, the bit-twiddling we did above might
8556       // end up visibly changing the output.  Fortunately, in that case, we
8557       // don't need to twiddle bits since the original input will convert
8558       // exactly to double-precision floating-point already.  Therefore,
8559       // construct a conditional to use the original value if the top 11
8560       // bits are all sign-bit copies, and use the rounded value computed
8561       // above otherwise.
8562       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8563                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8564       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8565                          Cond, DAG.getConstant(1, dl, MVT::i64));
8566       Cond = DAG.getSetCC(
8567           dl,
8568           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8569           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8570 
8571       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8572     }
8573 
8574     ReuseLoadInfo RLI;
8575     SDValue Bits;
8576 
8577     MachineFunction &MF = DAG.getMachineFunction();
8578     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8579       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8580                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8581       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8582     } else if (Subtarget.hasLFIWAX() &&
8583                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8584       MachineMemOperand *MMO =
8585         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8586                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8587       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8588       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8589                                      DAG.getVTList(MVT::f64, MVT::Other),
8590                                      Ops, MVT::i32, MMO);
8591       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8592     } else if (Subtarget.hasFPCVT() &&
8593                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8594       MachineMemOperand *MMO =
8595         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8596                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8597       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8598       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8599                                      DAG.getVTList(MVT::f64, MVT::Other),
8600                                      Ops, MVT::i32, MMO);
8601       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8602     } else if (((Subtarget.hasLFIWAX() &&
8603                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8604                 (Subtarget.hasFPCVT() &&
8605                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8606                SINT.getOperand(0).getValueType() == MVT::i32) {
8607       MachineFrameInfo &MFI = MF.getFrameInfo();
8608       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8609 
8610       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8611       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8612 
8613       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8614                                    MachinePointerInfo::getFixedStack(
8615                                        DAG.getMachineFunction(), FrameIdx));
8616       Chain = Store;
8617 
8618       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8619              "Expected an i32 store");
8620 
8621       RLI.Ptr = FIdx;
8622       RLI.Chain = Chain;
8623       RLI.MPI =
8624           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8625       RLI.Alignment = Align(4);
8626 
8627       MachineMemOperand *MMO =
8628         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8629                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8630       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8631       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8632                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8633                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8634                                      Ops, MVT::i32, MMO);
8635       Chain = Bits.getValue(1);
8636     } else
8637       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8638 
8639     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8640     if (IsStrict)
8641       Chain = FP.getValue(1);
8642 
8643     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8644       if (IsStrict)
8645         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8646                          DAG.getVTList(MVT::f32, MVT::Other),
8647                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8648       else
8649         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8650                          DAG.getIntPtrConstant(0, dl));
8651     }
8652     return FP;
8653   }
8654 
8655   assert(Src.getValueType() == MVT::i32 &&
8656          "Unhandled INT_TO_FP type in custom expander!");
8657   // Since we only generate this in 64-bit mode, we can take advantage of
8658   // 64-bit registers.  In particular, sign extend the input value into the
8659   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8660   // then lfd it and fcfid it.
8661   MachineFunction &MF = DAG.getMachineFunction();
8662   MachineFrameInfo &MFI = MF.getFrameInfo();
8663   EVT PtrVT = getPointerTy(MF.getDataLayout());
8664 
8665   SDValue Ld;
8666   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8667     ReuseLoadInfo RLI;
8668     bool ReusingLoad;
8669     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8670       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8671       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8672 
8673       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8674                                    MachinePointerInfo::getFixedStack(
8675                                        DAG.getMachineFunction(), FrameIdx));
8676       Chain = Store;
8677 
8678       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8679              "Expected an i32 store");
8680 
8681       RLI.Ptr = FIdx;
8682       RLI.Chain = Chain;
8683       RLI.MPI =
8684           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8685       RLI.Alignment = Align(4);
8686     }
8687 
8688     MachineMemOperand *MMO =
8689       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8690                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8691     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8692     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8693                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8694                                  MVT::i32, MMO);
8695     Chain = Ld.getValue(1);
8696     if (ReusingLoad)
8697       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8698   } else {
8699     assert(Subtarget.isPPC64() &&
8700            "i32->FP without LFIWAX supported only on PPC64");
8701 
8702     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8703     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8704 
8705     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8706 
8707     // STD the extended value into the stack slot.
8708     SDValue Store = DAG.getStore(
8709         Chain, dl, Ext64, FIdx,
8710         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8711     Chain = Store;
8712 
8713     // Load the value as a double.
8714     Ld = DAG.getLoad(
8715         MVT::f64, dl, Chain, FIdx,
8716         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8717     Chain = Ld.getValue(1);
8718   }
8719 
8720   // FCFID it and return it.
8721   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8722   if (IsStrict)
8723     Chain = FP.getValue(1);
8724   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8725     if (IsStrict)
8726       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8727                        DAG.getVTList(MVT::f32, MVT::Other),
8728                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8729     else
8730       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8731                        DAG.getIntPtrConstant(0, dl));
8732   }
8733   return FP;
8734 }
8735 
8736 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8737                                             SelectionDAG &DAG) const {
8738   SDLoc dl(Op);
8739   /*
8740    The rounding mode is in bits 30:31 of FPSR, and has the following
8741    settings:
8742      00 Round to nearest
8743      01 Round to 0
8744      10 Round to +inf
8745      11 Round to -inf
8746 
8747   FLT_ROUNDS, on the other hand, expects the following:
8748     -1 Undefined
8749      0 Round to 0
8750      1 Round to nearest
8751      2 Round to +inf
8752      3 Round to -inf
8753 
8754   To perform the conversion, we do:
8755     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8756   */
8757 
8758   MachineFunction &MF = DAG.getMachineFunction();
8759   EVT VT = Op.getValueType();
8760   EVT PtrVT = getPointerTy(MF.getDataLayout());
8761 
8762   // Save FP Control Word to register
8763   SDValue Chain = Op.getOperand(0);
8764   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8765   Chain = MFFS.getValue(1);
8766 
8767   SDValue CWD;
8768   if (isTypeLegal(MVT::i64)) {
8769     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8770                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8771   } else {
8772     // Save FP register to stack slot
8773     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8774     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8775     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8776 
8777     // Load FP Control Word from low 32 bits of stack slot.
8778     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8779            "Stack slot adjustment is valid only on big endian subtargets!");
8780     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8781     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8782     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8783     Chain = CWD.getValue(1);
8784   }
8785 
8786   // Transform as necessary
8787   SDValue CWD1 =
8788     DAG.getNode(ISD::AND, dl, MVT::i32,
8789                 CWD, DAG.getConstant(3, dl, MVT::i32));
8790   SDValue CWD2 =
8791     DAG.getNode(ISD::SRL, dl, MVT::i32,
8792                 DAG.getNode(ISD::AND, dl, MVT::i32,
8793                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8794                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8795                             DAG.getConstant(3, dl, MVT::i32)),
8796                 DAG.getConstant(1, dl, MVT::i32));
8797 
8798   SDValue RetVal =
8799     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8800 
8801   RetVal =
8802       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8803                   dl, VT, RetVal);
8804 
8805   return DAG.getMergeValues({RetVal, Chain}, dl);
8806 }
8807 
8808 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8809   EVT VT = Op.getValueType();
8810   unsigned BitWidth = VT.getSizeInBits();
8811   SDLoc dl(Op);
8812   assert(Op.getNumOperands() == 3 &&
8813          VT == Op.getOperand(1).getValueType() &&
8814          "Unexpected SHL!");
8815 
8816   // Expand into a bunch of logical ops.  Note that these ops
8817   // depend on the PPC behavior for oversized shift amounts.
8818   SDValue Lo = Op.getOperand(0);
8819   SDValue Hi = Op.getOperand(1);
8820   SDValue Amt = Op.getOperand(2);
8821   EVT AmtVT = Amt.getValueType();
8822 
8823   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8824                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8825   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8826   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8827   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8828   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8829                              DAG.getConstant(-BitWidth, dl, AmtVT));
8830   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8831   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8832   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8833   SDValue OutOps[] = { OutLo, OutHi };
8834   return DAG.getMergeValues(OutOps, dl);
8835 }
8836 
8837 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8838   EVT VT = Op.getValueType();
8839   SDLoc dl(Op);
8840   unsigned BitWidth = VT.getSizeInBits();
8841   assert(Op.getNumOperands() == 3 &&
8842          VT == Op.getOperand(1).getValueType() &&
8843          "Unexpected SRL!");
8844 
8845   // Expand into a bunch of logical ops.  Note that these ops
8846   // depend on the PPC behavior for oversized shift amounts.
8847   SDValue Lo = Op.getOperand(0);
8848   SDValue Hi = Op.getOperand(1);
8849   SDValue Amt = Op.getOperand(2);
8850   EVT AmtVT = Amt.getValueType();
8851 
8852   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8853                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8854   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8855   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8856   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8857   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8858                              DAG.getConstant(-BitWidth, dl, AmtVT));
8859   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8860   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8861   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8862   SDValue OutOps[] = { OutLo, OutHi };
8863   return DAG.getMergeValues(OutOps, dl);
8864 }
8865 
8866 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8867   SDLoc dl(Op);
8868   EVT VT = Op.getValueType();
8869   unsigned BitWidth = VT.getSizeInBits();
8870   assert(Op.getNumOperands() == 3 &&
8871          VT == Op.getOperand(1).getValueType() &&
8872          "Unexpected SRA!");
8873 
8874   // Expand into a bunch of logical ops, followed by a select_cc.
8875   SDValue Lo = Op.getOperand(0);
8876   SDValue Hi = Op.getOperand(1);
8877   SDValue Amt = Op.getOperand(2);
8878   EVT AmtVT = Amt.getValueType();
8879 
8880   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8881                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8882   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8883   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8884   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8885   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8886                              DAG.getConstant(-BitWidth, dl, AmtVT));
8887   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8888   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8889   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8890                                   Tmp4, Tmp6, ISD::SETLE);
8891   SDValue OutOps[] = { OutLo, OutHi };
8892   return DAG.getMergeValues(OutOps, dl);
8893 }
8894 
8895 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8896                                             SelectionDAG &DAG) const {
8897   SDLoc dl(Op);
8898   EVT VT = Op.getValueType();
8899   unsigned BitWidth = VT.getSizeInBits();
8900 
8901   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8902   SDValue X = Op.getOperand(0);
8903   SDValue Y = Op.getOperand(1);
8904   SDValue Z = Op.getOperand(2);
8905   EVT AmtVT = Z.getValueType();
8906 
8907   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8908   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8909   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8910   // on PowerPC shift by BW being well defined.
8911   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8912                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8913   SDValue SubZ =
8914       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8915   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8916   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8917   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8918 }
8919 
8920 //===----------------------------------------------------------------------===//
8921 // Vector related lowering.
8922 //
8923 
8924 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8925 /// element size of SplatSize. Cast the result to VT.
8926 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8927                                       SelectionDAG &DAG, const SDLoc &dl) {
8928   static const MVT VTys[] = { // canonical VT to use for each size.
8929     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8930   };
8931 
8932   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8933 
8934   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8935   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8936     SplatSize = 1;
8937     Val = 0xFF;
8938   }
8939 
8940   EVT CanonicalVT = VTys[SplatSize-1];
8941 
8942   // Build a canonical splat for this value.
8943   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8944 }
8945 
8946 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8947 /// specified intrinsic ID.
8948 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8949                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8950   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8951   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8952                      DAG.getConstant(IID, dl, MVT::i32), Op);
8953 }
8954 
8955 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8956 /// specified intrinsic ID.
8957 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8958                                 SelectionDAG &DAG, const SDLoc &dl,
8959                                 EVT DestVT = MVT::Other) {
8960   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8961   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8962                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8963 }
8964 
8965 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8966 /// specified intrinsic ID.
8967 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8968                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8969                                 EVT DestVT = MVT::Other) {
8970   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8971   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8972                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8973 }
8974 
8975 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8976 /// amount.  The result has the specified value type.
8977 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8978                            SelectionDAG &DAG, const SDLoc &dl) {
8979   // Force LHS/RHS to be the right type.
8980   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8981   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8982 
8983   int Ops[16];
8984   for (unsigned i = 0; i != 16; ++i)
8985     Ops[i] = i + Amt;
8986   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8987   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8988 }
8989 
8990 /// Do we have an efficient pattern in a .td file for this node?
8991 ///
8992 /// \param V - pointer to the BuildVectorSDNode being matched
8993 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8994 ///
8995 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8996 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8997 /// the opposite is true (expansion is beneficial) are:
8998 /// - The node builds a vector out of integers that are not 32 or 64-bits
8999 /// - The node builds a vector out of constants
9000 /// - The node is a "load-and-splat"
9001 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9002 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9003                                             bool HasDirectMove,
9004                                             bool HasP8Vector) {
9005   EVT VecVT = V->getValueType(0);
9006   bool RightType = VecVT == MVT::v2f64 ||
9007     (HasP8Vector && VecVT == MVT::v4f32) ||
9008     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9009   if (!RightType)
9010     return false;
9011 
9012   bool IsSplat = true;
9013   bool IsLoad = false;
9014   SDValue Op0 = V->getOperand(0);
9015 
9016   // This function is called in a block that confirms the node is not a constant
9017   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9018   // different constants.
9019   if (V->isConstant())
9020     return false;
9021   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9022     if (V->getOperand(i).isUndef())
9023       return false;
9024     // We want to expand nodes that represent load-and-splat even if the
9025     // loaded value is a floating point truncation or conversion to int.
9026     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9027         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9028          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9029         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9030          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9031         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9032          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9033       IsLoad = true;
9034     // If the operands are different or the input is not a load and has more
9035     // uses than just this BV node, then it isn't a splat.
9036     if (V->getOperand(i) != Op0 ||
9037         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9038       IsSplat = false;
9039   }
9040   return !(IsSplat && IsLoad);
9041 }
9042 
9043 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9044 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9045 
9046   SDLoc dl(Op);
9047   SDValue Op0 = Op->getOperand(0);
9048 
9049   if ((Op.getValueType() != MVT::f128) ||
9050       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9051       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9052       (Op0.getOperand(1).getValueType() != MVT::i64))
9053     return SDValue();
9054 
9055   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9056                      Op0.getOperand(1));
9057 }
9058 
9059 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9060   const SDValue *InputLoad = &Op;
9061   if (InputLoad->getOpcode() == ISD::BITCAST)
9062     InputLoad = &InputLoad->getOperand(0);
9063   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9064       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9065     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9066     InputLoad = &InputLoad->getOperand(0);
9067   }
9068   if (InputLoad->getOpcode() != ISD::LOAD)
9069     return nullptr;
9070   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9071   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9072 }
9073 
9074 // Convert the argument APFloat to a single precision APFloat if there is no
9075 // loss in information during the conversion to single precision APFloat and the
9076 // resulting number is not a denormal number. Return true if successful.
9077 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9078   APFloat APFloatToConvert = ArgAPFloat;
9079   bool LosesInfo = true;
9080   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9081                            &LosesInfo);
9082   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9083   if (Success)
9084     ArgAPFloat = APFloatToConvert;
9085   return Success;
9086 }
9087 
9088 // Bitcast the argument APInt to a double and convert it to a single precision
9089 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9090 // argument if there is no loss in information during the conversion from
9091 // double to single precision APFloat and the resulting number is not a denormal
9092 // number. Return true if successful.
9093 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9094   double DpValue = ArgAPInt.bitsToDouble();
9095   APFloat APFloatDp(DpValue);
9096   bool Success = convertToNonDenormSingle(APFloatDp);
9097   if (Success)
9098     ArgAPInt = APFloatDp.bitcastToAPInt();
9099   return Success;
9100 }
9101 
9102 // Nondestructive check for convertTonNonDenormSingle.
9103 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9104   // Only convert if it loses info, since XXSPLTIDP should
9105   // handle the other case.
9106   APFloat APFloatToConvert = ArgAPFloat;
9107   bool LosesInfo = true;
9108   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9109                            &LosesInfo);
9110 
9111   return (!LosesInfo && !APFloatToConvert.isDenormal());
9112 }
9113 
9114 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9115                              unsigned &Opcode) {
9116   LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9117   if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9118     return false;
9119 
9120   EVT Ty = Op->getValueType(0);
9121   // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9122   // as we cannot handle extending loads for these types.
9123   if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9124       ISD::isNON_EXTLoad(InputNode))
9125     return true;
9126 
9127   EVT MemVT = InputNode->getMemoryVT();
9128   // For v8i16 and v16i8 types, extending loads can be handled as long as the
9129   // memory VT is the same vector element VT type.
9130   // The loads feeding into the v8i16 and v16i8 types will be extending because
9131   // scalar i8/i16 are not legal types.
9132   if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9133       (MemVT == Ty.getVectorElementType()))
9134     return true;
9135 
9136   if (Ty == MVT::v2i64) {
9137     // Check the extend type, when the input type is i32, and the output vector
9138     // type is v2i64.
9139     if (MemVT == MVT::i32) {
9140       if (ISD::isZEXTLoad(InputNode))
9141         Opcode = PPCISD::ZEXT_LD_SPLAT;
9142       if (ISD::isSEXTLoad(InputNode))
9143         Opcode = PPCISD::SEXT_LD_SPLAT;
9144     }
9145     return true;
9146   }
9147   return false;
9148 }
9149 
9150 // If this is a case we can't handle, return null and let the default
9151 // expansion code take care of it.  If we CAN select this case, and if it
9152 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9153 // this case more efficiently than a constant pool load, lower it to the
9154 // sequence of ops that should be used.
9155 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9156                                              SelectionDAG &DAG) const {
9157   SDLoc dl(Op);
9158   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9159   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9160 
9161   // Check if this is a splat of a constant value.
9162   APInt APSplatBits, APSplatUndef;
9163   unsigned SplatBitSize;
9164   bool HasAnyUndefs;
9165   bool BVNIsConstantSplat =
9166       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9167                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9168 
9169   // If it is a splat of a double, check if we can shrink it to a 32 bit
9170   // non-denormal float which when converted back to double gives us the same
9171   // double. This is to exploit the XXSPLTIDP instruction.
9172   // If we lose precision, we use XXSPLTI32DX.
9173   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9174       Subtarget.hasPrefixInstrs()) {
9175     // Check the type first to short-circuit so we don't modify APSplatBits if
9176     // this block isn't executed.
9177     if ((Op->getValueType(0) == MVT::v2f64) &&
9178         convertToNonDenormSingle(APSplatBits)) {
9179       SDValue SplatNode = DAG.getNode(
9180           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9181           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9182       return DAG.getBitcast(Op.getValueType(), SplatNode);
9183     } else {
9184       // We may lose precision, so we have to use XXSPLTI32DX.
9185 
9186       uint32_t Hi =
9187           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9188       uint32_t Lo =
9189           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9190       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9191 
9192       if (!Hi || !Lo)
9193         // If either load is 0, then we should generate XXLXOR to set to 0.
9194         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9195 
9196       if (Hi)
9197         SplatNode = DAG.getNode(
9198             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9199             DAG.getTargetConstant(0, dl, MVT::i32),
9200             DAG.getTargetConstant(Hi, dl, MVT::i32));
9201 
9202       if (Lo)
9203         SplatNode =
9204             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9205                         DAG.getTargetConstant(1, dl, MVT::i32),
9206                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9207 
9208       return DAG.getBitcast(Op.getValueType(), SplatNode);
9209     }
9210   }
9211 
9212   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9213     unsigned NewOpcode = PPCISD::LD_SPLAT;
9214 
9215     // Handle load-and-splat patterns as we have instructions that will do this
9216     // in one go.
9217     if (DAG.isSplatValue(Op, true) &&
9218         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9219       const SDValue *InputLoad = &Op.getOperand(0);
9220       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9221 
9222       // If the input load is an extending load, it will be an i32 -> i64
9223       // extending load and isValidSplatLoad() will update NewOpcode.
9224       unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9225       unsigned ElementSize =
9226           MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9227 
9228       assert(((ElementSize == 2 * MemorySize)
9229                   ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9230                      NewOpcode == PPCISD::SEXT_LD_SPLAT)
9231                   : (NewOpcode == PPCISD::LD_SPLAT)) &&
9232              "Unmatched element size and opcode!\n");
9233 
9234       // Checking for a single use of this load, we have to check for vector
9235       // width (128 bits) / ElementSize uses (since each operand of the
9236       // BUILD_VECTOR is a separate use of the value.
9237       unsigned NumUsesOfInputLD = 128 / ElementSize;
9238       for (SDValue BVInOp : Op->ops())
9239         if (BVInOp.isUndef())
9240           NumUsesOfInputLD--;
9241 
9242       // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9243       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9244       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9245       // 15", but funciton IsValidSplatLoad() now will only return true when
9246       // the data at index 0 is not nullptr. So we will not get into trouble for
9247       // these cases.
9248       //
9249       // case 1 - lfiwzx/lfiwax
9250       // 1.1: load result is i32 and is sign/zero extend to i64;
9251       // 1.2: build a v2i64 vector type with above loaded value;
9252       // 1.3: the vector has only one value at index 0, others are all undef;
9253       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9254       if (NumUsesOfInputLD == 1 &&
9255           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9256            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9257            Subtarget.hasLFIWAX()))
9258         return SDValue();
9259 
9260       // case 2 - lxvr[hb]x
9261       // 2.1: load result is at most i16;
9262       // 2.2: build a vector with above loaded value;
9263       // 2.3: the vector has only one value at index 0, others are all undef;
9264       // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9265       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9266           Subtarget.isISA3_1() && ElementSize <= 16)
9267         return SDValue();
9268 
9269       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9270       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9271           Subtarget.hasVSX()) {
9272         SDValue Ops[] = {
9273           LD->getChain(),    // Chain
9274           LD->getBasePtr(),  // Ptr
9275           DAG.getValueType(Op.getValueType()) // VT
9276         };
9277         SDValue LdSplt = DAG.getMemIntrinsicNode(
9278             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9279             LD->getMemoryVT(), LD->getMemOperand());
9280         // Replace all uses of the output chain of the original load with the
9281         // output chain of the new load.
9282         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9283                                       LdSplt.getValue(1));
9284         return LdSplt;
9285       }
9286     }
9287 
9288     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9289     // 32-bits can be lowered to VSX instructions under certain conditions.
9290     // Without VSX, there is no pattern more efficient than expanding the node.
9291     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9292         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9293                                         Subtarget.hasP8Vector()))
9294       return Op;
9295     return SDValue();
9296   }
9297 
9298   uint64_t SplatBits = APSplatBits.getZExtValue();
9299   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9300   unsigned SplatSize = SplatBitSize / 8;
9301 
9302   // First, handle single instruction cases.
9303 
9304   // All zeros?
9305   if (SplatBits == 0) {
9306     // Canonicalize all zero vectors to be v4i32.
9307     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9308       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9309       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9310     }
9311     return Op;
9312   }
9313 
9314   // We have XXSPLTIW for constant splats four bytes wide.
9315   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9316   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9317   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9318   // turned into a 4-byte splat of 0xABABABAB.
9319   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9320     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9321                                   Op.getValueType(), DAG, dl);
9322 
9323   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9324     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9325                                   dl);
9326 
9327   // We have XXSPLTIB for constant splats one byte wide.
9328   if (Subtarget.hasP9Vector() && SplatSize == 1)
9329     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9330                                   dl);
9331 
9332   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9333   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9334                     (32-SplatBitSize));
9335   if (SextVal >= -16 && SextVal <= 15)
9336     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9337                                   dl);
9338 
9339   // Two instruction sequences.
9340 
9341   // If this value is in the range [-32,30] and is even, use:
9342   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9343   // If this value is in the range [17,31] and is odd, use:
9344   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9345   // If this value is in the range [-31,-17] and is odd, use:
9346   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9347   // Note the last two are three-instruction sequences.
9348   if (SextVal >= -32 && SextVal <= 31) {
9349     // To avoid having these optimizations undone by constant folding,
9350     // we convert to a pseudo that will be expanded later into one of
9351     // the above forms.
9352     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9353     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9354               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9355     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9356     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9357     if (VT == Op.getValueType())
9358       return RetVal;
9359     else
9360       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9361   }
9362 
9363   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9364   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9365   // for fneg/fabs.
9366   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9367     // Make -1 and vspltisw -1:
9368     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9369 
9370     // Make the VSLW intrinsic, computing 0x8000_0000.
9371     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9372                                    OnesV, DAG, dl);
9373 
9374     // xor by OnesV to invert it.
9375     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9376     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9377   }
9378 
9379   // Check to see if this is a wide variety of vsplti*, binop self cases.
9380   static const signed char SplatCsts[] = {
9381     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9382     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9383   };
9384 
9385   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9386     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9387     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9388     int i = SplatCsts[idx];
9389 
9390     // Figure out what shift amount will be used by altivec if shifted by i in
9391     // this splat size.
9392     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9393 
9394     // vsplti + shl self.
9395     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9396       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9397       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9398         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9399         Intrinsic::ppc_altivec_vslw
9400       };
9401       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9402       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9403     }
9404 
9405     // vsplti + srl self.
9406     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9407       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9408       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9409         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9410         Intrinsic::ppc_altivec_vsrw
9411       };
9412       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9413       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9414     }
9415 
9416     // vsplti + rol self.
9417     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9418                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9419       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9420       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9421         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9422         Intrinsic::ppc_altivec_vrlw
9423       };
9424       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9425       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9426     }
9427 
9428     // t = vsplti c, result = vsldoi t, t, 1
9429     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9430       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9431       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9432       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9433     }
9434     // t = vsplti c, result = vsldoi t, t, 2
9435     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9436       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9437       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9438       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9439     }
9440     // t = vsplti c, result = vsldoi t, t, 3
9441     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9442       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9443       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9444       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9445     }
9446   }
9447 
9448   return SDValue();
9449 }
9450 
9451 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9452 /// the specified operations to build the shuffle.
9453 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9454                                       SDValue RHS, SelectionDAG &DAG,
9455                                       const SDLoc &dl) {
9456   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9457   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9458   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9459 
9460   enum {
9461     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9462     OP_VMRGHW,
9463     OP_VMRGLW,
9464     OP_VSPLTISW0,
9465     OP_VSPLTISW1,
9466     OP_VSPLTISW2,
9467     OP_VSPLTISW3,
9468     OP_VSLDOI4,
9469     OP_VSLDOI8,
9470     OP_VSLDOI12
9471   };
9472 
9473   if (OpNum == OP_COPY) {
9474     if (LHSID == (1*9+2)*9+3) return LHS;
9475     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9476     return RHS;
9477   }
9478 
9479   SDValue OpLHS, OpRHS;
9480   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9481   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9482 
9483   int ShufIdxs[16];
9484   switch (OpNum) {
9485   default: llvm_unreachable("Unknown i32 permute!");
9486   case OP_VMRGHW:
9487     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9488     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9489     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9490     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9491     break;
9492   case OP_VMRGLW:
9493     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9494     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9495     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9496     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9497     break;
9498   case OP_VSPLTISW0:
9499     for (unsigned i = 0; i != 16; ++i)
9500       ShufIdxs[i] = (i&3)+0;
9501     break;
9502   case OP_VSPLTISW1:
9503     for (unsigned i = 0; i != 16; ++i)
9504       ShufIdxs[i] = (i&3)+4;
9505     break;
9506   case OP_VSPLTISW2:
9507     for (unsigned i = 0; i != 16; ++i)
9508       ShufIdxs[i] = (i&3)+8;
9509     break;
9510   case OP_VSPLTISW3:
9511     for (unsigned i = 0; i != 16; ++i)
9512       ShufIdxs[i] = (i&3)+12;
9513     break;
9514   case OP_VSLDOI4:
9515     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9516   case OP_VSLDOI8:
9517     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9518   case OP_VSLDOI12:
9519     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9520   }
9521   EVT VT = OpLHS.getValueType();
9522   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9523   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9524   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9525   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9526 }
9527 
9528 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9529 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9530 /// SDValue.
9531 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9532                                            SelectionDAG &DAG) const {
9533   const unsigned BytesInVector = 16;
9534   bool IsLE = Subtarget.isLittleEndian();
9535   SDLoc dl(N);
9536   SDValue V1 = N->getOperand(0);
9537   SDValue V2 = N->getOperand(1);
9538   unsigned ShiftElts = 0, InsertAtByte = 0;
9539   bool Swap = false;
9540 
9541   // Shifts required to get the byte we want at element 7.
9542   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9543                                    0, 15, 14, 13, 12, 11, 10, 9};
9544   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9545                                 1, 2,  3,  4,  5,  6,  7,  8};
9546 
9547   ArrayRef<int> Mask = N->getMask();
9548   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9549 
9550   // For each mask element, find out if we're just inserting something
9551   // from V2 into V1 or vice versa.
9552   // Possible permutations inserting an element from V2 into V1:
9553   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9554   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9555   //   ...
9556   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9557   // Inserting from V1 into V2 will be similar, except mask range will be
9558   // [16,31].
9559 
9560   bool FoundCandidate = false;
9561   // If both vector operands for the shuffle are the same vector, the mask
9562   // will contain only elements from the first one and the second one will be
9563   // undef.
9564   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9565   // Go through the mask of half-words to find an element that's being moved
9566   // from one vector to the other.
9567   for (unsigned i = 0; i < BytesInVector; ++i) {
9568     unsigned CurrentElement = Mask[i];
9569     // If 2nd operand is undefined, we should only look for element 7 in the
9570     // Mask.
9571     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9572       continue;
9573 
9574     bool OtherElementsInOrder = true;
9575     // Examine the other elements in the Mask to see if they're in original
9576     // order.
9577     for (unsigned j = 0; j < BytesInVector; ++j) {
9578       if (j == i)
9579         continue;
9580       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9581       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9582       // in which we always assume we're always picking from the 1st operand.
9583       int MaskOffset =
9584           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9585       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9586         OtherElementsInOrder = false;
9587         break;
9588       }
9589     }
9590     // If other elements are in original order, we record the number of shifts
9591     // we need to get the element we want into element 7. Also record which byte
9592     // in the vector we should insert into.
9593     if (OtherElementsInOrder) {
9594       // If 2nd operand is undefined, we assume no shifts and no swapping.
9595       if (V2.isUndef()) {
9596         ShiftElts = 0;
9597         Swap = false;
9598       } else {
9599         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9600         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9601                          : BigEndianShifts[CurrentElement & 0xF];
9602         Swap = CurrentElement < BytesInVector;
9603       }
9604       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9605       FoundCandidate = true;
9606       break;
9607     }
9608   }
9609 
9610   if (!FoundCandidate)
9611     return SDValue();
9612 
9613   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9614   // optionally with VECSHL if shift is required.
9615   if (Swap)
9616     std::swap(V1, V2);
9617   if (V2.isUndef())
9618     V2 = V1;
9619   if (ShiftElts) {
9620     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9621                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9622     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9623                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9624   }
9625   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9626                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9627 }
9628 
9629 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9630 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9631 /// SDValue.
9632 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9633                                            SelectionDAG &DAG) const {
9634   const unsigned NumHalfWords = 8;
9635   const unsigned BytesInVector = NumHalfWords * 2;
9636   // Check that the shuffle is on half-words.
9637   if (!isNByteElemShuffleMask(N, 2, 1))
9638     return SDValue();
9639 
9640   bool IsLE = Subtarget.isLittleEndian();
9641   SDLoc dl(N);
9642   SDValue V1 = N->getOperand(0);
9643   SDValue V2 = N->getOperand(1);
9644   unsigned ShiftElts = 0, InsertAtByte = 0;
9645   bool Swap = false;
9646 
9647   // Shifts required to get the half-word we want at element 3.
9648   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9649   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9650 
9651   uint32_t Mask = 0;
9652   uint32_t OriginalOrderLow = 0x1234567;
9653   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9654   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9655   // 32-bit space, only need 4-bit nibbles per element.
9656   for (unsigned i = 0; i < NumHalfWords; ++i) {
9657     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9658     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9659   }
9660 
9661   // For each mask element, find out if we're just inserting something
9662   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9663   // from V2 into V1:
9664   //   X, 1, 2, 3, 4, 5, 6, 7
9665   //   0, X, 2, 3, 4, 5, 6, 7
9666   //   0, 1, X, 3, 4, 5, 6, 7
9667   //   0, 1, 2, X, 4, 5, 6, 7
9668   //   0, 1, 2, 3, X, 5, 6, 7
9669   //   0, 1, 2, 3, 4, X, 6, 7
9670   //   0, 1, 2, 3, 4, 5, X, 7
9671   //   0, 1, 2, 3, 4, 5, 6, X
9672   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9673 
9674   bool FoundCandidate = false;
9675   // Go through the mask of half-words to find an element that's being moved
9676   // from one vector to the other.
9677   for (unsigned i = 0; i < NumHalfWords; ++i) {
9678     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9679     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9680     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9681     uint32_t TargetOrder = 0x0;
9682 
9683     // If both vector operands for the shuffle are the same vector, the mask
9684     // will contain only elements from the first one and the second one will be
9685     // undef.
9686     if (V2.isUndef()) {
9687       ShiftElts = 0;
9688       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9689       TargetOrder = OriginalOrderLow;
9690       Swap = false;
9691       // Skip if not the correct element or mask of other elements don't equal
9692       // to our expected order.
9693       if (MaskOneElt == VINSERTHSrcElem &&
9694           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9695         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9696         FoundCandidate = true;
9697         break;
9698       }
9699     } else { // If both operands are defined.
9700       // Target order is [8,15] if the current mask is between [0,7].
9701       TargetOrder =
9702           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9703       // Skip if mask of other elements don't equal our expected order.
9704       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9705         // We only need the last 3 bits for the number of shifts.
9706         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9707                          : BigEndianShifts[MaskOneElt & 0x7];
9708         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9709         Swap = MaskOneElt < NumHalfWords;
9710         FoundCandidate = true;
9711         break;
9712       }
9713     }
9714   }
9715 
9716   if (!FoundCandidate)
9717     return SDValue();
9718 
9719   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9720   // optionally with VECSHL if shift is required.
9721   if (Swap)
9722     std::swap(V1, V2);
9723   if (V2.isUndef())
9724     V2 = V1;
9725   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9726   if (ShiftElts) {
9727     // Double ShiftElts because we're left shifting on v16i8 type.
9728     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9729                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9730     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9731     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9732                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9733     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9734   }
9735   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9736   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9737                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9738   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9739 }
9740 
9741 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9742 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9743 /// return the default SDValue.
9744 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9745                                               SelectionDAG &DAG) const {
9746   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9747   // to v16i8. Peek through the bitcasts to get the actual operands.
9748   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9749   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9750 
9751   auto ShuffleMask = SVN->getMask();
9752   SDValue VecShuffle(SVN, 0);
9753   SDLoc DL(SVN);
9754 
9755   // Check that we have a four byte shuffle.
9756   if (!isNByteElemShuffleMask(SVN, 4, 1))
9757     return SDValue();
9758 
9759   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9760   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9761     std::swap(LHS, RHS);
9762     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9763     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9764   }
9765 
9766   // Ensure that the RHS is a vector of constants.
9767   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9768   if (!BVN)
9769     return SDValue();
9770 
9771   // Check if RHS is a splat of 4-bytes (or smaller).
9772   APInt APSplatValue, APSplatUndef;
9773   unsigned SplatBitSize;
9774   bool HasAnyUndefs;
9775   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9776                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9777       SplatBitSize > 32)
9778     return SDValue();
9779 
9780   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9781   // The instruction splats a constant C into two words of the source vector
9782   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9783   // Thus we check that the shuffle mask is the equivalent  of
9784   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9785   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9786   // within each word are consecutive, so we only need to check the first byte.
9787   SDValue Index;
9788   bool IsLE = Subtarget.isLittleEndian();
9789   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9790       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9791        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9792     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9793   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9794            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9795             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9796     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9797   else
9798     return SDValue();
9799 
9800   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9801   // for XXSPLTI32DX.
9802   unsigned SplatVal = APSplatValue.getZExtValue();
9803   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9804     SplatVal |= (SplatVal << SplatBitSize);
9805 
9806   SDValue SplatNode = DAG.getNode(
9807       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9808       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9809   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9810 }
9811 
9812 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9813 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9814 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9815 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9816 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9817   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9818   assert(Op.getValueType() == MVT::v1i128 &&
9819          "Only set v1i128 as custom, other type shouldn't reach here!");
9820   SDLoc dl(Op);
9821   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9822   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9823   unsigned SHLAmt = N1.getConstantOperandVal(0);
9824   if (SHLAmt % 8 == 0) {
9825     std::array<int, 16> Mask;
9826     std::iota(Mask.begin(), Mask.end(), 0);
9827     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9828     if (SDValue Shuffle =
9829             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9830                                  DAG.getUNDEF(MVT::v16i8), Mask))
9831       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9832   }
9833   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9834   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9835                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9836   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9837                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9838   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9839   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9840 }
9841 
9842 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9843 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9844 /// return the code it can be lowered into.  Worst case, it can always be
9845 /// lowered into a vperm.
9846 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9847                                                SelectionDAG &DAG) const {
9848   SDLoc dl(Op);
9849   SDValue V1 = Op.getOperand(0);
9850   SDValue V2 = Op.getOperand(1);
9851   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9852 
9853   // Any nodes that were combined in the target-independent combiner prior
9854   // to vector legalization will not be sent to the target combine. Try to
9855   // combine it here.
9856   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9857     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9858       return NewShuffle;
9859     Op = NewShuffle;
9860     SVOp = cast<ShuffleVectorSDNode>(Op);
9861     V1 = Op.getOperand(0);
9862     V2 = Op.getOperand(1);
9863   }
9864   EVT VT = Op.getValueType();
9865   bool isLittleEndian = Subtarget.isLittleEndian();
9866 
9867   unsigned ShiftElts, InsertAtByte;
9868   bool Swap = false;
9869 
9870   // If this is a load-and-splat, we can do that with a single instruction
9871   // in some cases. However if the load has multiple uses, we don't want to
9872   // combine it because that will just produce multiple loads.
9873   bool IsPermutedLoad = false;
9874   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9875   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9876       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9877       InputLoad->hasOneUse()) {
9878     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9879     int SplatIdx =
9880       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9881 
9882     // The splat index for permuted loads will be in the left half of the vector
9883     // which is strictly wider than the loaded value by 8 bytes. So we need to
9884     // adjust the splat index to point to the correct address in memory.
9885     if (IsPermutedLoad) {
9886       assert((isLittleEndian || IsFourByte) &&
9887              "Unexpected size for permuted load on big endian target");
9888       SplatIdx += IsFourByte ? 2 : 1;
9889       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9890              "Splat of a value outside of the loaded memory");
9891     }
9892 
9893     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9894     // For 4-byte load-and-splat, we need Power9.
9895     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9896       uint64_t Offset = 0;
9897       if (IsFourByte)
9898         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9899       else
9900         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9901 
9902       // If the width of the load is the same as the width of the splat,
9903       // loading with an offset would load the wrong memory.
9904       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9905         Offset = 0;
9906 
9907       SDValue BasePtr = LD->getBasePtr();
9908       if (Offset != 0)
9909         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9910                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9911       SDValue Ops[] = {
9912         LD->getChain(),    // Chain
9913         BasePtr,           // BasePtr
9914         DAG.getValueType(Op.getValueType()) // VT
9915       };
9916       SDVTList VTL =
9917         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9918       SDValue LdSplt =
9919         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9920                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9921       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9922       if (LdSplt.getValueType() != SVOp->getValueType(0))
9923         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9924       return LdSplt;
9925     }
9926   }
9927   if (Subtarget.hasP9Vector() &&
9928       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9929                            isLittleEndian)) {
9930     if (Swap)
9931       std::swap(V1, V2);
9932     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9933     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9934     if (ShiftElts) {
9935       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9936                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9937       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9938                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9939       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9940     }
9941     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9942                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9943     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9944   }
9945 
9946   if (Subtarget.hasPrefixInstrs()) {
9947     SDValue SplatInsertNode;
9948     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9949       return SplatInsertNode;
9950   }
9951 
9952   if (Subtarget.hasP9Altivec()) {
9953     SDValue NewISDNode;
9954     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9955       return NewISDNode;
9956 
9957     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9958       return NewISDNode;
9959   }
9960 
9961   if (Subtarget.hasVSX() &&
9962       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9963     if (Swap)
9964       std::swap(V1, V2);
9965     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9966     SDValue Conv2 =
9967         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9968 
9969     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9970                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9971     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9972   }
9973 
9974   if (Subtarget.hasVSX() &&
9975     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9976     if (Swap)
9977       std::swap(V1, V2);
9978     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9979     SDValue Conv2 =
9980         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9981 
9982     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9983                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9984     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9985   }
9986 
9987   if (Subtarget.hasP9Vector()) {
9988      if (PPC::isXXBRHShuffleMask(SVOp)) {
9989       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9990       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9991       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9992     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9993       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9994       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9995       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9996     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9997       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9998       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9999       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10000     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10001       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10002       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10003       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10004     }
10005   }
10006 
10007   if (Subtarget.hasVSX()) {
10008     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10009       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10010 
10011       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10012       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10013                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10014       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10015     }
10016 
10017     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10018     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10019       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10020       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10021       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10022     }
10023   }
10024 
10025   // Cases that are handled by instructions that take permute immediates
10026   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10027   // selected by the instruction selector.
10028   if (V2.isUndef()) {
10029     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10030         PPC::isSplatShuffleMask(SVOp, 2) ||
10031         PPC::isSplatShuffleMask(SVOp, 4) ||
10032         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10033         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10034         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10035         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10036         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10037         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10038         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10039         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10040         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10041         (Subtarget.hasP8Altivec() && (
10042          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10043          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10044          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10045       return Op;
10046     }
10047   }
10048 
10049   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10050   // and produce a fixed permutation.  If any of these match, do not lower to
10051   // VPERM.
10052   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10053   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10054       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10055       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10056       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10057       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10058       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10059       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10060       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10061       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10062       (Subtarget.hasP8Altivec() && (
10063        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10064        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10065        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10066     return Op;
10067 
10068   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10069   // perfect shuffle table to emit an optimal matching sequence.
10070   ArrayRef<int> PermMask = SVOp->getMask();
10071 
10072   if (!DisablePerfectShuffle && !isLittleEndian) {
10073     unsigned PFIndexes[4];
10074     bool isFourElementShuffle = true;
10075     for (unsigned i = 0; i != 4 && isFourElementShuffle;
10076          ++i) {                           // Element number
10077       unsigned EltNo = 8;                 // Start out undef.
10078       for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10079         if (PermMask[i * 4 + j] < 0)
10080           continue; // Undef, ignore it.
10081 
10082         unsigned ByteSource = PermMask[i * 4 + j];
10083         if ((ByteSource & 3) != j) {
10084           isFourElementShuffle = false;
10085           break;
10086         }
10087 
10088         if (EltNo == 8) {
10089           EltNo = ByteSource / 4;
10090         } else if (EltNo != ByteSource / 4) {
10091           isFourElementShuffle = false;
10092           break;
10093         }
10094       }
10095       PFIndexes[i] = EltNo;
10096     }
10097 
10098     // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10099     // perfect shuffle vector to determine if it is cost effective to do this as
10100     // discrete instructions, or whether we should use a vperm.
10101     // For now, we skip this for little endian until such time as we have a
10102     // little-endian perfect shuffle table.
10103     if (isFourElementShuffle) {
10104       // Compute the index in the perfect shuffle table.
10105       unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10106                               PFIndexes[2] * 9 + PFIndexes[3];
10107 
10108       unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10109       unsigned Cost = (PFEntry >> 30);
10110 
10111       // Determining when to avoid vperm is tricky.  Many things affect the cost
10112       // of vperm, particularly how many times the perm mask needs to be
10113       // computed. For example, if the perm mask can be hoisted out of a loop or
10114       // is already used (perhaps because there are multiple permutes with the
10115       // same shuffle mask?) the vperm has a cost of 1.  OTOH, hoisting the
10116       // permute mask out of the loop requires an extra register.
10117       //
10118       // As a compromise, we only emit discrete instructions if the shuffle can
10119       // be generated in 3 or fewer operations.  When we have loop information
10120       // available, if this block is within a loop, we should avoid using vperm
10121       // for 3-operation perms and use a constant pool load instead.
10122       if (Cost < 3)
10123         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10124     }
10125   }
10126 
10127   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10128   // vector that will get spilled to the constant pool.
10129   if (V2.isUndef()) V2 = V1;
10130 
10131   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10132   // that it is in input element units, not in bytes.  Convert now.
10133 
10134   // For little endian, the order of the input vectors is reversed, and
10135   // the permutation mask is complemented with respect to 31.  This is
10136   // necessary to produce proper semantics with the big-endian-biased vperm
10137   // instruction.
10138   EVT EltVT = V1.getValueType().getVectorElementType();
10139   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10140 
10141   SmallVector<SDValue, 16> ResultMask;
10142   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10143     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10144 
10145     for (unsigned j = 0; j != BytesPerElement; ++j)
10146       if (isLittleEndian)
10147         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10148                                              dl, MVT::i32));
10149       else
10150         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10151                                              MVT::i32));
10152   }
10153 
10154   ShufflesHandledWithVPERM++;
10155   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10156   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10157   LLVM_DEBUG(SVOp->dump());
10158   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10159   LLVM_DEBUG(VPermMask.dump());
10160 
10161   if (isLittleEndian)
10162     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10163                        V2, V1, VPermMask);
10164   else
10165     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10166                        V1, V2, VPermMask);
10167 }
10168 
10169 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10170 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10171 /// information about the intrinsic.
10172 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10173                                  bool &isDot, const PPCSubtarget &Subtarget) {
10174   unsigned IntrinsicID =
10175       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10176   CompareOpc = -1;
10177   isDot = false;
10178   switch (IntrinsicID) {
10179   default:
10180     return false;
10181   // Comparison predicates.
10182   case Intrinsic::ppc_altivec_vcmpbfp_p:
10183     CompareOpc = 966;
10184     isDot = true;
10185     break;
10186   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10187     CompareOpc = 198;
10188     isDot = true;
10189     break;
10190   case Intrinsic::ppc_altivec_vcmpequb_p:
10191     CompareOpc = 6;
10192     isDot = true;
10193     break;
10194   case Intrinsic::ppc_altivec_vcmpequh_p:
10195     CompareOpc = 70;
10196     isDot = true;
10197     break;
10198   case Intrinsic::ppc_altivec_vcmpequw_p:
10199     CompareOpc = 134;
10200     isDot = true;
10201     break;
10202   case Intrinsic::ppc_altivec_vcmpequd_p:
10203     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10204       CompareOpc = 199;
10205       isDot = true;
10206     } else
10207       return false;
10208     break;
10209   case Intrinsic::ppc_altivec_vcmpneb_p:
10210   case Intrinsic::ppc_altivec_vcmpneh_p:
10211   case Intrinsic::ppc_altivec_vcmpnew_p:
10212   case Intrinsic::ppc_altivec_vcmpnezb_p:
10213   case Intrinsic::ppc_altivec_vcmpnezh_p:
10214   case Intrinsic::ppc_altivec_vcmpnezw_p:
10215     if (Subtarget.hasP9Altivec()) {
10216       switch (IntrinsicID) {
10217       default:
10218         llvm_unreachable("Unknown comparison intrinsic.");
10219       case Intrinsic::ppc_altivec_vcmpneb_p:
10220         CompareOpc = 7;
10221         break;
10222       case Intrinsic::ppc_altivec_vcmpneh_p:
10223         CompareOpc = 71;
10224         break;
10225       case Intrinsic::ppc_altivec_vcmpnew_p:
10226         CompareOpc = 135;
10227         break;
10228       case Intrinsic::ppc_altivec_vcmpnezb_p:
10229         CompareOpc = 263;
10230         break;
10231       case Intrinsic::ppc_altivec_vcmpnezh_p:
10232         CompareOpc = 327;
10233         break;
10234       case Intrinsic::ppc_altivec_vcmpnezw_p:
10235         CompareOpc = 391;
10236         break;
10237       }
10238       isDot = true;
10239     } else
10240       return false;
10241     break;
10242   case Intrinsic::ppc_altivec_vcmpgefp_p:
10243     CompareOpc = 454;
10244     isDot = true;
10245     break;
10246   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10247     CompareOpc = 710;
10248     isDot = true;
10249     break;
10250   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10251     CompareOpc = 774;
10252     isDot = true;
10253     break;
10254   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10255     CompareOpc = 838;
10256     isDot = true;
10257     break;
10258   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10259     CompareOpc = 902;
10260     isDot = true;
10261     break;
10262   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10263     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10264       CompareOpc = 967;
10265       isDot = true;
10266     } else
10267       return false;
10268     break;
10269   case Intrinsic::ppc_altivec_vcmpgtub_p:
10270     CompareOpc = 518;
10271     isDot = true;
10272     break;
10273   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10274     CompareOpc = 582;
10275     isDot = true;
10276     break;
10277   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10278     CompareOpc = 646;
10279     isDot = true;
10280     break;
10281   case Intrinsic::ppc_altivec_vcmpgtud_p:
10282     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10283       CompareOpc = 711;
10284       isDot = true;
10285     } else
10286       return false;
10287     break;
10288 
10289   case Intrinsic::ppc_altivec_vcmpequq:
10290   case Intrinsic::ppc_altivec_vcmpgtsq:
10291   case Intrinsic::ppc_altivec_vcmpgtuq:
10292     if (!Subtarget.isISA3_1())
10293       return false;
10294     switch (IntrinsicID) {
10295     default:
10296       llvm_unreachable("Unknown comparison intrinsic.");
10297     case Intrinsic::ppc_altivec_vcmpequq:
10298       CompareOpc = 455;
10299       break;
10300     case Intrinsic::ppc_altivec_vcmpgtsq:
10301       CompareOpc = 903;
10302       break;
10303     case Intrinsic::ppc_altivec_vcmpgtuq:
10304       CompareOpc = 647;
10305       break;
10306     }
10307     break;
10308 
10309   // VSX predicate comparisons use the same infrastructure
10310   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10311   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10312   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10313   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10314   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10315   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10316     if (Subtarget.hasVSX()) {
10317       switch (IntrinsicID) {
10318       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10319         CompareOpc = 99;
10320         break;
10321       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10322         CompareOpc = 115;
10323         break;
10324       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10325         CompareOpc = 107;
10326         break;
10327       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10328         CompareOpc = 67;
10329         break;
10330       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10331         CompareOpc = 83;
10332         break;
10333       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10334         CompareOpc = 75;
10335         break;
10336       }
10337       isDot = true;
10338     } else
10339       return false;
10340     break;
10341 
10342   // Normal Comparisons.
10343   case Intrinsic::ppc_altivec_vcmpbfp:
10344     CompareOpc = 966;
10345     break;
10346   case Intrinsic::ppc_altivec_vcmpeqfp:
10347     CompareOpc = 198;
10348     break;
10349   case Intrinsic::ppc_altivec_vcmpequb:
10350     CompareOpc = 6;
10351     break;
10352   case Intrinsic::ppc_altivec_vcmpequh:
10353     CompareOpc = 70;
10354     break;
10355   case Intrinsic::ppc_altivec_vcmpequw:
10356     CompareOpc = 134;
10357     break;
10358   case Intrinsic::ppc_altivec_vcmpequd:
10359     if (Subtarget.hasP8Altivec())
10360       CompareOpc = 199;
10361     else
10362       return false;
10363     break;
10364   case Intrinsic::ppc_altivec_vcmpneb:
10365   case Intrinsic::ppc_altivec_vcmpneh:
10366   case Intrinsic::ppc_altivec_vcmpnew:
10367   case Intrinsic::ppc_altivec_vcmpnezb:
10368   case Intrinsic::ppc_altivec_vcmpnezh:
10369   case Intrinsic::ppc_altivec_vcmpnezw:
10370     if (Subtarget.hasP9Altivec())
10371       switch (IntrinsicID) {
10372       default:
10373         llvm_unreachable("Unknown comparison intrinsic.");
10374       case Intrinsic::ppc_altivec_vcmpneb:
10375         CompareOpc = 7;
10376         break;
10377       case Intrinsic::ppc_altivec_vcmpneh:
10378         CompareOpc = 71;
10379         break;
10380       case Intrinsic::ppc_altivec_vcmpnew:
10381         CompareOpc = 135;
10382         break;
10383       case Intrinsic::ppc_altivec_vcmpnezb:
10384         CompareOpc = 263;
10385         break;
10386       case Intrinsic::ppc_altivec_vcmpnezh:
10387         CompareOpc = 327;
10388         break;
10389       case Intrinsic::ppc_altivec_vcmpnezw:
10390         CompareOpc = 391;
10391         break;
10392       }
10393     else
10394       return false;
10395     break;
10396   case Intrinsic::ppc_altivec_vcmpgefp:
10397     CompareOpc = 454;
10398     break;
10399   case Intrinsic::ppc_altivec_vcmpgtfp:
10400     CompareOpc = 710;
10401     break;
10402   case Intrinsic::ppc_altivec_vcmpgtsb:
10403     CompareOpc = 774;
10404     break;
10405   case Intrinsic::ppc_altivec_vcmpgtsh:
10406     CompareOpc = 838;
10407     break;
10408   case Intrinsic::ppc_altivec_vcmpgtsw:
10409     CompareOpc = 902;
10410     break;
10411   case Intrinsic::ppc_altivec_vcmpgtsd:
10412     if (Subtarget.hasP8Altivec())
10413       CompareOpc = 967;
10414     else
10415       return false;
10416     break;
10417   case Intrinsic::ppc_altivec_vcmpgtub:
10418     CompareOpc = 518;
10419     break;
10420   case Intrinsic::ppc_altivec_vcmpgtuh:
10421     CompareOpc = 582;
10422     break;
10423   case Intrinsic::ppc_altivec_vcmpgtuw:
10424     CompareOpc = 646;
10425     break;
10426   case Intrinsic::ppc_altivec_vcmpgtud:
10427     if (Subtarget.hasP8Altivec())
10428       CompareOpc = 711;
10429     else
10430       return false;
10431     break;
10432   case Intrinsic::ppc_altivec_vcmpequq_p:
10433   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10434   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10435     if (!Subtarget.isISA3_1())
10436       return false;
10437     switch (IntrinsicID) {
10438     default:
10439       llvm_unreachable("Unknown comparison intrinsic.");
10440     case Intrinsic::ppc_altivec_vcmpequq_p:
10441       CompareOpc = 455;
10442       break;
10443     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10444       CompareOpc = 903;
10445       break;
10446     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10447       CompareOpc = 647;
10448       break;
10449     }
10450     isDot = true;
10451     break;
10452   }
10453   return true;
10454 }
10455 
10456 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10457 /// lower, do it, otherwise return null.
10458 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10459                                                    SelectionDAG &DAG) const {
10460   unsigned IntrinsicID =
10461     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10462 
10463   SDLoc dl(Op);
10464 
10465   switch (IntrinsicID) {
10466   case Intrinsic::thread_pointer:
10467     // Reads the thread pointer register, used for __builtin_thread_pointer.
10468     if (Subtarget.isPPC64())
10469       return DAG.getRegister(PPC::X13, MVT::i64);
10470     return DAG.getRegister(PPC::R2, MVT::i32);
10471 
10472   case Intrinsic::ppc_mma_disassemble_acc:
10473   case Intrinsic::ppc_vsx_disassemble_pair: {
10474     int NumVecs = 2;
10475     SDValue WideVec = Op.getOperand(1);
10476     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10477       NumVecs = 4;
10478       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10479     }
10480     SmallVector<SDValue, 4> RetOps;
10481     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10482       SDValue Extract = DAG.getNode(
10483           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10484           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10485                                                      : VecNo,
10486                           dl, getPointerTy(DAG.getDataLayout())));
10487       RetOps.push_back(Extract);
10488     }
10489     return DAG.getMergeValues(RetOps, dl);
10490   }
10491 
10492   case Intrinsic::ppc_unpack_longdouble: {
10493     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10494     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10495            "Argument of long double unpack must be 0 or 1!");
10496     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10497                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10498                                        Idx->getValueType(0)));
10499   }
10500 
10501   case Intrinsic::ppc_compare_exp_lt:
10502   case Intrinsic::ppc_compare_exp_gt:
10503   case Intrinsic::ppc_compare_exp_eq:
10504   case Intrinsic::ppc_compare_exp_uo: {
10505     unsigned Pred;
10506     switch (IntrinsicID) {
10507     case Intrinsic::ppc_compare_exp_lt:
10508       Pred = PPC::PRED_LT;
10509       break;
10510     case Intrinsic::ppc_compare_exp_gt:
10511       Pred = PPC::PRED_GT;
10512       break;
10513     case Intrinsic::ppc_compare_exp_eq:
10514       Pred = PPC::PRED_EQ;
10515       break;
10516     case Intrinsic::ppc_compare_exp_uo:
10517       Pred = PPC::PRED_UN;
10518       break;
10519     }
10520     return SDValue(
10521         DAG.getMachineNode(
10522             PPC::SELECT_CC_I4, dl, MVT::i32,
10523             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10524                                         Op.getOperand(1), Op.getOperand(2)),
10525                      0),
10526              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10527              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10528         0);
10529   }
10530   case Intrinsic::ppc_test_data_class_d:
10531   case Intrinsic::ppc_test_data_class_f: {
10532     unsigned CmprOpc = PPC::XSTSTDCDP;
10533     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10534       CmprOpc = PPC::XSTSTDCSP;
10535     return SDValue(
10536         DAG.getMachineNode(
10537             PPC::SELECT_CC_I4, dl, MVT::i32,
10538             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10539                                         Op.getOperand(1)),
10540                      0),
10541              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10542              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10543         0);
10544   }
10545   case Intrinsic::ppc_fnmsub: {
10546     EVT VT = Op.getOperand(1).getValueType();
10547     if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
10548       return DAG.getNode(
10549           ISD::FNEG, dl, VT,
10550           DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
10551                       DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
10552     return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
10553                        Op.getOperand(2), Op.getOperand(3));
10554   }
10555   case Intrinsic::ppc_convert_f128_to_ppcf128:
10556   case Intrinsic::ppc_convert_ppcf128_to_f128: {
10557     RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10558                             ? RTLIB::CONVERT_PPCF128_F128
10559                             : RTLIB::CONVERT_F128_PPCF128;
10560     MakeLibCallOptions CallOptions;
10561     std::pair<SDValue, SDValue> Result =
10562         makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10563                     dl, SDValue());
10564     return Result.first;
10565   }
10566   case Intrinsic::ppc_maxfe:
10567   case Intrinsic::ppc_maxfl:
10568   case Intrinsic::ppc_maxfs:
10569   case Intrinsic::ppc_minfe:
10570   case Intrinsic::ppc_minfl:
10571   case Intrinsic::ppc_minfs: {
10572     EVT VT = Op.getValueType();
10573     assert(
10574         all_of(Op->ops().drop_front(4),
10575                [VT](const SDUse &Use) { return Use.getValueType() == VT; }) &&
10576         "ppc_[max|min]f[e|l|s] must have uniform type arguments");
10577     ISD::CondCode CC = ISD::SETGT;
10578     if (IntrinsicID == Intrinsic::ppc_minfe ||
10579         IntrinsicID == Intrinsic::ppc_minfl ||
10580         IntrinsicID == Intrinsic::ppc_minfs)
10581       CC = ISD::SETLT;
10582     unsigned I = Op.getNumOperands() - 2, Cnt = I;
10583     SDValue Res = Op.getOperand(I);
10584     for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) {
10585       Res =
10586           DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC);
10587     }
10588     return Res;
10589   }
10590   }
10591 
10592   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10593   // opcode number of the comparison.
10594   int CompareOpc;
10595   bool isDot;
10596   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10597     return SDValue();    // Don't custom lower most intrinsics.
10598 
10599   // If this is a non-dot comparison, make the VCMP node and we are done.
10600   if (!isDot) {
10601     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10602                               Op.getOperand(1), Op.getOperand(2),
10603                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10604     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10605   }
10606 
10607   // Create the PPCISD altivec 'dot' comparison node.
10608   SDValue Ops[] = {
10609     Op.getOperand(2),  // LHS
10610     Op.getOperand(3),  // RHS
10611     DAG.getConstant(CompareOpc, dl, MVT::i32)
10612   };
10613   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10614   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10615 
10616   // Now that we have the comparison, emit a copy from the CR to a GPR.
10617   // This is flagged to the above dot comparison.
10618   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10619                                 DAG.getRegister(PPC::CR6, MVT::i32),
10620                                 CompNode.getValue(1));
10621 
10622   // Unpack the result based on how the target uses it.
10623   unsigned BitNo;   // Bit # of CR6.
10624   bool InvertBit;   // Invert result?
10625   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10626   default:  // Can't happen, don't crash on invalid number though.
10627   case 0:   // Return the value of the EQ bit of CR6.
10628     BitNo = 0; InvertBit = false;
10629     break;
10630   case 1:   // Return the inverted value of the EQ bit of CR6.
10631     BitNo = 0; InvertBit = true;
10632     break;
10633   case 2:   // Return the value of the LT bit of CR6.
10634     BitNo = 2; InvertBit = false;
10635     break;
10636   case 3:   // Return the inverted value of the LT bit of CR6.
10637     BitNo = 2; InvertBit = true;
10638     break;
10639   }
10640 
10641   // Shift the bit into the low position.
10642   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10643                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10644   // Isolate the bit.
10645   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10646                       DAG.getConstant(1, dl, MVT::i32));
10647 
10648   // If we are supposed to, toggle the bit.
10649   if (InvertBit)
10650     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10651                         DAG.getConstant(1, dl, MVT::i32));
10652   return Flags;
10653 }
10654 
10655 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10656                                                SelectionDAG &DAG) const {
10657   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10658   // the beginning of the argument list.
10659   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10660   SDLoc DL(Op);
10661   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10662   case Intrinsic::ppc_cfence: {
10663     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10664     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10665     SDValue Val = Op.getOperand(ArgStart + 1);
10666     EVT Ty = Val.getValueType();
10667     if (Ty == MVT::i128) {
10668       // FIXME: Testing one of two paired registers is sufficient to guarantee
10669       // ordering?
10670       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10671     }
10672     return SDValue(
10673         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10674                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10675                            Op.getOperand(0)),
10676         0);
10677   }
10678   default:
10679     break;
10680   }
10681   return SDValue();
10682 }
10683 
10684 // Lower scalar BSWAP64 to xxbrd.
10685 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10686   SDLoc dl(Op);
10687   if (!Subtarget.isPPC64())
10688     return Op;
10689   // MTVSRDD
10690   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10691                    Op.getOperand(0));
10692   // XXBRD
10693   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10694   // MFVSRD
10695   int VectorIndex = 0;
10696   if (Subtarget.isLittleEndian())
10697     VectorIndex = 1;
10698   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10699                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10700   return Op;
10701 }
10702 
10703 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10704 // compared to a value that is atomically loaded (atomic loads zero-extend).
10705 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10706                                                 SelectionDAG &DAG) const {
10707   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10708          "Expecting an atomic compare-and-swap here.");
10709   SDLoc dl(Op);
10710   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10711   EVT MemVT = AtomicNode->getMemoryVT();
10712   if (MemVT.getSizeInBits() >= 32)
10713     return Op;
10714 
10715   SDValue CmpOp = Op.getOperand(2);
10716   // If this is already correctly zero-extended, leave it alone.
10717   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10718   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10719     return Op;
10720 
10721   // Clear the high bits of the compare operand.
10722   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10723   SDValue NewCmpOp =
10724     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10725                 DAG.getConstant(MaskVal, dl, MVT::i32));
10726 
10727   // Replace the existing compare operand with the properly zero-extended one.
10728   SmallVector<SDValue, 4> Ops;
10729   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10730     Ops.push_back(AtomicNode->getOperand(i));
10731   Ops[2] = NewCmpOp;
10732   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10733   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10734   auto NodeTy =
10735     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10736   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10737 }
10738 
10739 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10740                                                   SelectionDAG &DAG) const {
10741   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10742   EVT MemVT = N->getMemoryVT();
10743   assert(MemVT.getSimpleVT() == MVT::i128 &&
10744          "Expect quadword atomic operations");
10745   SDLoc dl(N);
10746   unsigned Opc = N->getOpcode();
10747   switch (Opc) {
10748   case ISD::ATOMIC_LOAD: {
10749     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10750     // lowered to ppc instructions by pattern matching instruction selector.
10751     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10752     SmallVector<SDValue, 4> Ops{
10753         N->getOperand(0),
10754         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10755     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10756       Ops.push_back(N->getOperand(I));
10757     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10758                                                 Ops, MemVT, N->getMemOperand());
10759     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10760     SDValue ValHi =
10761         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10762     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10763                         DAG.getConstant(64, dl, MVT::i32));
10764     SDValue Val =
10765         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10766     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10767                        {Val, LoadedVal.getValue(2)});
10768   }
10769   case ISD::ATOMIC_STORE: {
10770     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10771     // lowered to ppc instructions by pattern matching instruction selector.
10772     SDVTList Tys = DAG.getVTList(MVT::Other);
10773     SmallVector<SDValue, 4> Ops{
10774         N->getOperand(0),
10775         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10776     SDValue Val = N->getOperand(2);
10777     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10778     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10779                                 DAG.getConstant(64, dl, MVT::i32));
10780     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10781     Ops.push_back(ValLo);
10782     Ops.push_back(ValHi);
10783     Ops.push_back(N->getOperand(1));
10784     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10785                                    N->getMemOperand());
10786   }
10787   default:
10788     llvm_unreachable("Unexpected atomic opcode");
10789   }
10790 }
10791 
10792 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10793                                                  SelectionDAG &DAG) const {
10794   SDLoc dl(Op);
10795   // Create a stack slot that is 16-byte aligned.
10796   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10797   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10798   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10799   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10800 
10801   // Store the input value into Value#0 of the stack slot.
10802   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10803                                MachinePointerInfo());
10804   // Load it out.
10805   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10806 }
10807 
10808 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10809                                                   SelectionDAG &DAG) const {
10810   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10811          "Should only be called for ISD::INSERT_VECTOR_ELT");
10812 
10813   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10814 
10815   EVT VT = Op.getValueType();
10816   SDLoc dl(Op);
10817   SDValue V1 = Op.getOperand(0);
10818   SDValue V2 = Op.getOperand(1);
10819 
10820   if (VT == MVT::v2f64 && C)
10821     return Op;
10822 
10823   if (Subtarget.hasP9Vector()) {
10824     // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
10825     // because on P10, it allows this specific insert_vector_elt load pattern to
10826     // utilize the refactored load and store infrastructure in order to exploit
10827     // prefixed loads.
10828     // On targets with inexpensive direct moves (Power9 and up), a
10829     // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
10830     // load since a single precision load will involve conversion to double
10831     // precision on the load followed by another conversion to single precision.
10832     if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
10833         (isa<LoadSDNode>(V2))) {
10834       SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
10835       SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
10836       SDValue InsVecElt =
10837           DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
10838                       BitcastLoad, Op.getOperand(2));
10839       return DAG.getBitcast(MVT::v4f32, InsVecElt);
10840     }
10841   }
10842 
10843   if (Subtarget.isISA3_1()) {
10844     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10845       return SDValue();
10846     // On P10, we have legal lowering for constant and variable indices for
10847     // all vectors.
10848     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10849         VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
10850       return Op;
10851   }
10852 
10853   // Before P10, we have legal lowering for constant indices but not for
10854   // variable ones.
10855   if (!C)
10856     return SDValue();
10857 
10858   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10859   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10860     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10861     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10862     unsigned InsertAtElement = C->getZExtValue();
10863     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10864     if (Subtarget.isLittleEndian()) {
10865       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10866     }
10867     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10868                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10869   }
10870   return Op;
10871 }
10872 
10873 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10874                                            SelectionDAG &DAG) const {
10875   SDLoc dl(Op);
10876   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10877   SDValue LoadChain = LN->getChain();
10878   SDValue BasePtr = LN->getBasePtr();
10879   EVT VT = Op.getValueType();
10880 
10881   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10882     return Op;
10883 
10884   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10885   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10886   // 2 or 4 vsx registers.
10887   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10888          "Type unsupported without MMA");
10889   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10890          "Type unsupported without paired vector support");
10891   Align Alignment = LN->getAlign();
10892   SmallVector<SDValue, 4> Loads;
10893   SmallVector<SDValue, 4> LoadChains;
10894   unsigned NumVecs = VT.getSizeInBits() / 128;
10895   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10896     SDValue Load =
10897         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10898                     LN->getPointerInfo().getWithOffset(Idx * 16),
10899                     commonAlignment(Alignment, Idx * 16),
10900                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10901     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10902                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10903     Loads.push_back(Load);
10904     LoadChains.push_back(Load.getValue(1));
10905   }
10906   if (Subtarget.isLittleEndian()) {
10907     std::reverse(Loads.begin(), Loads.end());
10908     std::reverse(LoadChains.begin(), LoadChains.end());
10909   }
10910   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10911   SDValue Value =
10912       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10913                   dl, VT, Loads);
10914   SDValue RetOps[] = {Value, TF};
10915   return DAG.getMergeValues(RetOps, dl);
10916 }
10917 
10918 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10919                                             SelectionDAG &DAG) const {
10920   SDLoc dl(Op);
10921   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10922   SDValue StoreChain = SN->getChain();
10923   SDValue BasePtr = SN->getBasePtr();
10924   SDValue Value = SN->getValue();
10925   EVT StoreVT = Value.getValueType();
10926 
10927   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10928     return Op;
10929 
10930   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10931   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10932   // underlying registers individually.
10933   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10934          "Type unsupported without MMA");
10935   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10936          "Type unsupported without paired vector support");
10937   Align Alignment = SN->getAlign();
10938   SmallVector<SDValue, 4> Stores;
10939   unsigned NumVecs = 2;
10940   if (StoreVT == MVT::v512i1) {
10941     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10942     NumVecs = 4;
10943   }
10944   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10945     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10946     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10947                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10948     SDValue Store =
10949         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10950                      SN->getPointerInfo().getWithOffset(Idx * 16),
10951                      commonAlignment(Alignment, Idx * 16),
10952                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10953     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10954                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10955     Stores.push_back(Store);
10956   }
10957   SDValue TF = DAG.getTokenFactor(dl, Stores);
10958   return TF;
10959 }
10960 
10961 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10962   SDLoc dl(Op);
10963   if (Op.getValueType() == MVT::v4i32) {
10964     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10965 
10966     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10967     // +16 as shift amt.
10968     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10969     SDValue RHSSwap =   // = vrlw RHS, 16
10970       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10971 
10972     // Shrinkify inputs to v8i16.
10973     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10974     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10975     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10976 
10977     // Low parts multiplied together, generating 32-bit results (we ignore the
10978     // top parts).
10979     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10980                                         LHS, RHS, DAG, dl, MVT::v4i32);
10981 
10982     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10983                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10984     // Shift the high parts up 16 bits.
10985     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10986                               Neg16, DAG, dl);
10987     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10988   } else if (Op.getValueType() == MVT::v16i8) {
10989     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10990     bool isLittleEndian = Subtarget.isLittleEndian();
10991 
10992     // Multiply the even 8-bit parts, producing 16-bit sums.
10993     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10994                                            LHS, RHS, DAG, dl, MVT::v8i16);
10995     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10996 
10997     // Multiply the odd 8-bit parts, producing 16-bit sums.
10998     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10999                                           LHS, RHS, DAG, dl, MVT::v8i16);
11000     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
11001 
11002     // Merge the results together.  Because vmuleub and vmuloub are
11003     // instructions with a big-endian bias, we must reverse the
11004     // element numbering and reverse the meaning of "odd" and "even"
11005     // when generating little endian code.
11006     int Ops[16];
11007     for (unsigned i = 0; i != 8; ++i) {
11008       if (isLittleEndian) {
11009         Ops[i*2  ] = 2*i;
11010         Ops[i*2+1] = 2*i+16;
11011       } else {
11012         Ops[i*2  ] = 2*i+1;
11013         Ops[i*2+1] = 2*i+1+16;
11014       }
11015     }
11016     if (isLittleEndian)
11017       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
11018     else
11019       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
11020   } else {
11021     llvm_unreachable("Unknown mul to lower!");
11022   }
11023 }
11024 
11025 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11026   bool IsStrict = Op->isStrictFPOpcode();
11027   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
11028       !Subtarget.hasP9Vector())
11029     return SDValue();
11030 
11031   return Op;
11032 }
11033 
11034 // Custom lowering for fpext vf32 to v2f64
11035 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11036 
11037   assert(Op.getOpcode() == ISD::FP_EXTEND &&
11038          "Should only be called for ISD::FP_EXTEND");
11039 
11040   // FIXME: handle extends from half precision float vectors on P9.
11041   // We only want to custom lower an extend from v2f32 to v2f64.
11042   if (Op.getValueType() != MVT::v2f64 ||
11043       Op.getOperand(0).getValueType() != MVT::v2f32)
11044     return SDValue();
11045 
11046   SDLoc dl(Op);
11047   SDValue Op0 = Op.getOperand(0);
11048 
11049   switch (Op0.getOpcode()) {
11050   default:
11051     return SDValue();
11052   case ISD::EXTRACT_SUBVECTOR: {
11053     assert(Op0.getNumOperands() == 2 &&
11054            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11055            "Node should have 2 operands with second one being a constant!");
11056 
11057     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11058       return SDValue();
11059 
11060     // Custom lower is only done for high or low doubleword.
11061     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11062     if (Idx % 2 != 0)
11063       return SDValue();
11064 
11065     // Since input is v4f32, at this point Idx is either 0 or 2.
11066     // Shift to get the doubleword position we want.
11067     int DWord = Idx >> 1;
11068 
11069     // High and low word positions are different on little endian.
11070     if (Subtarget.isLittleEndian())
11071       DWord ^= 0x1;
11072 
11073     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11074                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11075   }
11076   case ISD::FADD:
11077   case ISD::FMUL:
11078   case ISD::FSUB: {
11079     SDValue NewLoad[2];
11080     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11081       // Ensure both input are loads.
11082       SDValue LdOp = Op0.getOperand(i);
11083       if (LdOp.getOpcode() != ISD::LOAD)
11084         return SDValue();
11085       // Generate new load node.
11086       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11087       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11088       NewLoad[i] = DAG.getMemIntrinsicNode(
11089           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11090           LD->getMemoryVT(), LD->getMemOperand());
11091     }
11092     SDValue NewOp =
11093         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11094                     NewLoad[1], Op0.getNode()->getFlags());
11095     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11096                        DAG.getConstant(0, dl, MVT::i32));
11097   }
11098   case ISD::LOAD: {
11099     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11100     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11101     SDValue NewLd = DAG.getMemIntrinsicNode(
11102         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11103         LD->getMemoryVT(), LD->getMemOperand());
11104     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11105                        DAG.getConstant(0, dl, MVT::i32));
11106   }
11107   }
11108   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11109 }
11110 
11111 /// LowerOperation - Provide custom lowering hooks for some operations.
11112 ///
11113 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11114   switch (Op.getOpcode()) {
11115   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11116   case ISD::FPOW:               return lowerPow(Op, DAG);
11117   case ISD::FSIN:               return lowerSin(Op, DAG);
11118   case ISD::FCOS:               return lowerCos(Op, DAG);
11119   case ISD::FLOG:               return lowerLog(Op, DAG);
11120   case ISD::FLOG10:             return lowerLog10(Op, DAG);
11121   case ISD::FEXP:               return lowerExp(Op, DAG);
11122   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11123   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11124   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11125   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11126   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11127   case ISD::STRICT_FSETCC:
11128   case ISD::STRICT_FSETCCS:
11129   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11130   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11131   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11132 
11133   case ISD::INLINEASM:
11134   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11135   // Variable argument lowering.
11136   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11137   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11138   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11139 
11140   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11141   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11142   case ISD::GET_DYNAMIC_AREA_OFFSET:
11143     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11144 
11145   // Exception handling lowering.
11146   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11147   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11148   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11149 
11150   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11151   case ISD::STORE:              return LowerSTORE(Op, DAG);
11152   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11153   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11154   case ISD::STRICT_FP_TO_UINT:
11155   case ISD::STRICT_FP_TO_SINT:
11156   case ISD::FP_TO_UINT:
11157   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11158   case ISD::STRICT_UINT_TO_FP:
11159   case ISD::STRICT_SINT_TO_FP:
11160   case ISD::UINT_TO_FP:
11161   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11162   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11163 
11164   // Lower 64-bit shifts.
11165   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11166   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11167   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11168 
11169   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11170   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11171 
11172   // Vector-related lowering.
11173   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11174   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11175   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11176   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11177   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11178   case ISD::MUL:                return LowerMUL(Op, DAG);
11179   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11180   case ISD::STRICT_FP_ROUND:
11181   case ISD::FP_ROUND:
11182     return LowerFP_ROUND(Op, DAG);
11183   case ISD::ROTL:               return LowerROTL(Op, DAG);
11184 
11185   // For counter-based loop handling.
11186   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11187 
11188   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11189 
11190   // Frame & Return address.
11191   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11192   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11193 
11194   case ISD::INTRINSIC_VOID:
11195     return LowerINTRINSIC_VOID(Op, DAG);
11196   case ISD::BSWAP:
11197     return LowerBSWAP(Op, DAG);
11198   case ISD::ATOMIC_CMP_SWAP:
11199     return LowerATOMIC_CMP_SWAP(Op, DAG);
11200   case ISD::ATOMIC_STORE:
11201     return LowerATOMIC_LOAD_STORE(Op, DAG);
11202   }
11203 }
11204 
11205 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11206                                            SmallVectorImpl<SDValue>&Results,
11207                                            SelectionDAG &DAG) const {
11208   SDLoc dl(N);
11209   switch (N->getOpcode()) {
11210   default:
11211     llvm_unreachable("Do not know how to custom type legalize this operation!");
11212   case ISD::ATOMIC_LOAD: {
11213     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11214     Results.push_back(Res);
11215     Results.push_back(Res.getValue(1));
11216     break;
11217   }
11218   case ISD::READCYCLECOUNTER: {
11219     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11220     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11221 
11222     Results.push_back(
11223         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11224     Results.push_back(RTB.getValue(2));
11225     break;
11226   }
11227   case ISD::INTRINSIC_W_CHAIN: {
11228     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11229         Intrinsic::loop_decrement)
11230       break;
11231 
11232     assert(N->getValueType(0) == MVT::i1 &&
11233            "Unexpected result type for CTR decrement intrinsic");
11234     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11235                                  N->getValueType(0));
11236     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11237     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11238                                  N->getOperand(1));
11239 
11240     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11241     Results.push_back(NewInt.getValue(1));
11242     break;
11243   }
11244   case ISD::INTRINSIC_WO_CHAIN: {
11245     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11246     case Intrinsic::ppc_pack_longdouble:
11247       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11248                                     N->getOperand(2), N->getOperand(1)));
11249       break;
11250     case Intrinsic::ppc_maxfe:
11251     case Intrinsic::ppc_minfe:
11252     case Intrinsic::ppc_fnmsub:
11253     case Intrinsic::ppc_convert_f128_to_ppcf128:
11254       Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11255       break;
11256     }
11257     break;
11258   }
11259   case ISD::VAARG: {
11260     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11261       return;
11262 
11263     EVT VT = N->getValueType(0);
11264 
11265     if (VT == MVT::i64) {
11266       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11267 
11268       Results.push_back(NewNode);
11269       Results.push_back(NewNode.getValue(1));
11270     }
11271     return;
11272   }
11273   case ISD::STRICT_FP_TO_SINT:
11274   case ISD::STRICT_FP_TO_UINT:
11275   case ISD::FP_TO_SINT:
11276   case ISD::FP_TO_UINT: {
11277     // LowerFP_TO_INT() can only handle f32 and f64.
11278     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11279         MVT::ppcf128)
11280       return;
11281     SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11282     Results.push_back(LoweredValue);
11283     if (N->isStrictFPOpcode())
11284       Results.push_back(LoweredValue.getValue(1));
11285     return;
11286   }
11287   case ISD::TRUNCATE: {
11288     if (!N->getValueType(0).isVector())
11289       return;
11290     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11291     if (Lowered)
11292       Results.push_back(Lowered);
11293     return;
11294   }
11295   case ISD::FSHL:
11296   case ISD::FSHR:
11297     // Don't handle funnel shifts here.
11298     return;
11299   case ISD::BITCAST:
11300     // Don't handle bitcast here.
11301     return;
11302   case ISD::FP_EXTEND:
11303     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11304     if (Lowered)
11305       Results.push_back(Lowered);
11306     return;
11307   }
11308 }
11309 
11310 //===----------------------------------------------------------------------===//
11311 //  Other Lowering Code
11312 //===----------------------------------------------------------------------===//
11313 
11314 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11315   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11316   Function *Func = Intrinsic::getDeclaration(M, Id);
11317   return Builder.CreateCall(Func, {});
11318 }
11319 
11320 // The mappings for emitLeading/TrailingFence is taken from
11321 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11322 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11323                                                  Instruction *Inst,
11324                                                  AtomicOrdering Ord) const {
11325   if (Ord == AtomicOrdering::SequentiallyConsistent)
11326     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11327   if (isReleaseOrStronger(Ord))
11328     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11329   return nullptr;
11330 }
11331 
11332 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11333                                                   Instruction *Inst,
11334                                                   AtomicOrdering Ord) const {
11335   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11336     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11337     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11338     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11339     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11340       return Builder.CreateCall(
11341           Intrinsic::getDeclaration(
11342               Builder.GetInsertBlock()->getParent()->getParent(),
11343               Intrinsic::ppc_cfence, {Inst->getType()}),
11344           {Inst});
11345     // FIXME: Can use isync for rmw operation.
11346     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11347   }
11348   return nullptr;
11349 }
11350 
11351 MachineBasicBlock *
11352 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11353                                     unsigned AtomicSize,
11354                                     unsigned BinOpcode,
11355                                     unsigned CmpOpcode,
11356                                     unsigned CmpPred) const {
11357   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11358   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11359 
11360   auto LoadMnemonic = PPC::LDARX;
11361   auto StoreMnemonic = PPC::STDCX;
11362   switch (AtomicSize) {
11363   default:
11364     llvm_unreachable("Unexpected size of atomic entity");
11365   case 1:
11366     LoadMnemonic = PPC::LBARX;
11367     StoreMnemonic = PPC::STBCX;
11368     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11369     break;
11370   case 2:
11371     LoadMnemonic = PPC::LHARX;
11372     StoreMnemonic = PPC::STHCX;
11373     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11374     break;
11375   case 4:
11376     LoadMnemonic = PPC::LWARX;
11377     StoreMnemonic = PPC::STWCX;
11378     break;
11379   case 8:
11380     LoadMnemonic = PPC::LDARX;
11381     StoreMnemonic = PPC::STDCX;
11382     break;
11383   }
11384 
11385   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11386   MachineFunction *F = BB->getParent();
11387   MachineFunction::iterator It = ++BB->getIterator();
11388 
11389   Register dest = MI.getOperand(0).getReg();
11390   Register ptrA = MI.getOperand(1).getReg();
11391   Register ptrB = MI.getOperand(2).getReg();
11392   Register incr = MI.getOperand(3).getReg();
11393   DebugLoc dl = MI.getDebugLoc();
11394 
11395   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11396   MachineBasicBlock *loop2MBB =
11397     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11398   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11399   F->insert(It, loopMBB);
11400   if (CmpOpcode)
11401     F->insert(It, loop2MBB);
11402   F->insert(It, exitMBB);
11403   exitMBB->splice(exitMBB->begin(), BB,
11404                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11405   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11406 
11407   MachineRegisterInfo &RegInfo = F->getRegInfo();
11408   Register TmpReg = (!BinOpcode) ? incr :
11409     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11410                                            : &PPC::GPRCRegClass);
11411 
11412   //  thisMBB:
11413   //   ...
11414   //   fallthrough --> loopMBB
11415   BB->addSuccessor(loopMBB);
11416 
11417   //  loopMBB:
11418   //   l[wd]arx dest, ptr
11419   //   add r0, dest, incr
11420   //   st[wd]cx. r0, ptr
11421   //   bne- loopMBB
11422   //   fallthrough --> exitMBB
11423 
11424   // For max/min...
11425   //  loopMBB:
11426   //   l[wd]arx dest, ptr
11427   //   cmpl?[wd] incr, dest
11428   //   bgt exitMBB
11429   //  loop2MBB:
11430   //   st[wd]cx. dest, ptr
11431   //   bne- loopMBB
11432   //   fallthrough --> exitMBB
11433 
11434   BB = loopMBB;
11435   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11436     .addReg(ptrA).addReg(ptrB);
11437   if (BinOpcode)
11438     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11439   if (CmpOpcode) {
11440     // Signed comparisons of byte or halfword values must be sign-extended.
11441     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11442       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11443       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11444               ExtReg).addReg(dest);
11445       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11446         .addReg(incr).addReg(ExtReg);
11447     } else
11448       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11449         .addReg(incr).addReg(dest);
11450 
11451     BuildMI(BB, dl, TII->get(PPC::BCC))
11452       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11453     BB->addSuccessor(loop2MBB);
11454     BB->addSuccessor(exitMBB);
11455     BB = loop2MBB;
11456   }
11457   BuildMI(BB, dl, TII->get(StoreMnemonic))
11458     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11459   BuildMI(BB, dl, TII->get(PPC::BCC))
11460     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11461   BB->addSuccessor(loopMBB);
11462   BB->addSuccessor(exitMBB);
11463 
11464   //  exitMBB:
11465   //   ...
11466   BB = exitMBB;
11467   return BB;
11468 }
11469 
11470 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11471   switch(MI.getOpcode()) {
11472   default:
11473     return false;
11474   case PPC::COPY:
11475     return TII->isSignExtended(MI);
11476   case PPC::LHA:
11477   case PPC::LHA8:
11478   case PPC::LHAU:
11479   case PPC::LHAU8:
11480   case PPC::LHAUX:
11481   case PPC::LHAUX8:
11482   case PPC::LHAX:
11483   case PPC::LHAX8:
11484   case PPC::LWA:
11485   case PPC::LWAUX:
11486   case PPC::LWAX:
11487   case PPC::LWAX_32:
11488   case PPC::LWA_32:
11489   case PPC::PLHA:
11490   case PPC::PLHA8:
11491   case PPC::PLHA8pc:
11492   case PPC::PLHApc:
11493   case PPC::PLWA:
11494   case PPC::PLWA8:
11495   case PPC::PLWA8pc:
11496   case PPC::PLWApc:
11497   case PPC::EXTSB:
11498   case PPC::EXTSB8:
11499   case PPC::EXTSB8_32_64:
11500   case PPC::EXTSB8_rec:
11501   case PPC::EXTSB_rec:
11502   case PPC::EXTSH:
11503   case PPC::EXTSH8:
11504   case PPC::EXTSH8_32_64:
11505   case PPC::EXTSH8_rec:
11506   case PPC::EXTSH_rec:
11507   case PPC::EXTSW:
11508   case PPC::EXTSWSLI:
11509   case PPC::EXTSWSLI_32_64:
11510   case PPC::EXTSWSLI_32_64_rec:
11511   case PPC::EXTSWSLI_rec:
11512   case PPC::EXTSW_32:
11513   case PPC::EXTSW_32_64:
11514   case PPC::EXTSW_32_64_rec:
11515   case PPC::EXTSW_rec:
11516   case PPC::SRAW:
11517   case PPC::SRAWI:
11518   case PPC::SRAWI_rec:
11519   case PPC::SRAW_rec:
11520     return true;
11521   }
11522   return false;
11523 }
11524 
11525 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11526     MachineInstr &MI, MachineBasicBlock *BB,
11527     bool is8bit, // operation
11528     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11529   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11530   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11531 
11532   // If this is a signed comparison and the value being compared is not known
11533   // to be sign extended, sign extend it here.
11534   DebugLoc dl = MI.getDebugLoc();
11535   MachineFunction *F = BB->getParent();
11536   MachineRegisterInfo &RegInfo = F->getRegInfo();
11537   Register incr = MI.getOperand(3).getReg();
11538   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11539     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11540 
11541   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11542     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11543     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11544         .addReg(MI.getOperand(3).getReg());
11545     MI.getOperand(3).setReg(ValueReg);
11546   }
11547   // If we support part-word atomic mnemonics, just use them
11548   if (Subtarget.hasPartwordAtomics())
11549     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11550                             CmpPred);
11551 
11552   // In 64 bit mode we have to use 64 bits for addresses, even though the
11553   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11554   // registers without caring whether they're 32 or 64, but here we're
11555   // doing actual arithmetic on the addresses.
11556   bool is64bit = Subtarget.isPPC64();
11557   bool isLittleEndian = Subtarget.isLittleEndian();
11558   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11559 
11560   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11561   MachineFunction::iterator It = ++BB->getIterator();
11562 
11563   Register dest = MI.getOperand(0).getReg();
11564   Register ptrA = MI.getOperand(1).getReg();
11565   Register ptrB = MI.getOperand(2).getReg();
11566 
11567   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11568   MachineBasicBlock *loop2MBB =
11569       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11570   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11571   F->insert(It, loopMBB);
11572   if (CmpOpcode)
11573     F->insert(It, loop2MBB);
11574   F->insert(It, exitMBB);
11575   exitMBB->splice(exitMBB->begin(), BB,
11576                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11577   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11578 
11579   const TargetRegisterClass *RC =
11580       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11581   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11582 
11583   Register PtrReg = RegInfo.createVirtualRegister(RC);
11584   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11585   Register ShiftReg =
11586       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11587   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11588   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11589   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11590   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11591   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11592   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11593   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11594   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11595   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11596   Register Ptr1Reg;
11597   Register TmpReg =
11598       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11599 
11600   //  thisMBB:
11601   //   ...
11602   //   fallthrough --> loopMBB
11603   BB->addSuccessor(loopMBB);
11604 
11605   // The 4-byte load must be aligned, while a char or short may be
11606   // anywhere in the word.  Hence all this nasty bookkeeping code.
11607   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11608   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11609   //   xori shift, shift1, 24 [16]
11610   //   rlwinm ptr, ptr1, 0, 0, 29
11611   //   slw incr2, incr, shift
11612   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11613   //   slw mask, mask2, shift
11614   //  loopMBB:
11615   //   lwarx tmpDest, ptr
11616   //   add tmp, tmpDest, incr2
11617   //   andc tmp2, tmpDest, mask
11618   //   and tmp3, tmp, mask
11619   //   or tmp4, tmp3, tmp2
11620   //   stwcx. tmp4, ptr
11621   //   bne- loopMBB
11622   //   fallthrough --> exitMBB
11623   //   srw SrwDest, tmpDest, shift
11624   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11625   if (ptrA != ZeroReg) {
11626     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11627     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11628         .addReg(ptrA)
11629         .addReg(ptrB);
11630   } else {
11631     Ptr1Reg = ptrB;
11632   }
11633   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11634   // mode.
11635   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11636       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11637       .addImm(3)
11638       .addImm(27)
11639       .addImm(is8bit ? 28 : 27);
11640   if (!isLittleEndian)
11641     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11642         .addReg(Shift1Reg)
11643         .addImm(is8bit ? 24 : 16);
11644   if (is64bit)
11645     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11646         .addReg(Ptr1Reg)
11647         .addImm(0)
11648         .addImm(61);
11649   else
11650     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11651         .addReg(Ptr1Reg)
11652         .addImm(0)
11653         .addImm(0)
11654         .addImm(29);
11655   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11656   if (is8bit)
11657     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11658   else {
11659     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11660     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11661         .addReg(Mask3Reg)
11662         .addImm(65535);
11663   }
11664   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11665       .addReg(Mask2Reg)
11666       .addReg(ShiftReg);
11667 
11668   BB = loopMBB;
11669   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11670       .addReg(ZeroReg)
11671       .addReg(PtrReg);
11672   if (BinOpcode)
11673     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11674         .addReg(Incr2Reg)
11675         .addReg(TmpDestReg);
11676   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11677       .addReg(TmpDestReg)
11678       .addReg(MaskReg);
11679   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11680   if (CmpOpcode) {
11681     // For unsigned comparisons, we can directly compare the shifted values.
11682     // For signed comparisons we shift and sign extend.
11683     Register SReg = RegInfo.createVirtualRegister(GPRC);
11684     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11685         .addReg(TmpDestReg)
11686         .addReg(MaskReg);
11687     unsigned ValueReg = SReg;
11688     unsigned CmpReg = Incr2Reg;
11689     if (CmpOpcode == PPC::CMPW) {
11690       ValueReg = RegInfo.createVirtualRegister(GPRC);
11691       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11692           .addReg(SReg)
11693           .addReg(ShiftReg);
11694       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11695       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11696           .addReg(ValueReg);
11697       ValueReg = ValueSReg;
11698       CmpReg = incr;
11699     }
11700     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11701         .addReg(CmpReg)
11702         .addReg(ValueReg);
11703     BuildMI(BB, dl, TII->get(PPC::BCC))
11704         .addImm(CmpPred)
11705         .addReg(PPC::CR0)
11706         .addMBB(exitMBB);
11707     BB->addSuccessor(loop2MBB);
11708     BB->addSuccessor(exitMBB);
11709     BB = loop2MBB;
11710   }
11711   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11712   BuildMI(BB, dl, TII->get(PPC::STWCX))
11713       .addReg(Tmp4Reg)
11714       .addReg(ZeroReg)
11715       .addReg(PtrReg);
11716   BuildMI(BB, dl, TII->get(PPC::BCC))
11717       .addImm(PPC::PRED_NE)
11718       .addReg(PPC::CR0)
11719       .addMBB(loopMBB);
11720   BB->addSuccessor(loopMBB);
11721   BB->addSuccessor(exitMBB);
11722 
11723   //  exitMBB:
11724   //   ...
11725   BB = exitMBB;
11726   // Since the shift amount is not a constant, we need to clear
11727   // the upper bits with a separate RLWINM.
11728   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11729       .addReg(SrwDestReg)
11730       .addImm(0)
11731       .addImm(is8bit ? 24 : 16)
11732       .addImm(31);
11733   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11734       .addReg(TmpDestReg)
11735       .addReg(ShiftReg);
11736   return BB;
11737 }
11738 
11739 llvm::MachineBasicBlock *
11740 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11741                                     MachineBasicBlock *MBB) const {
11742   DebugLoc DL = MI.getDebugLoc();
11743   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11744   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11745 
11746   MachineFunction *MF = MBB->getParent();
11747   MachineRegisterInfo &MRI = MF->getRegInfo();
11748 
11749   const BasicBlock *BB = MBB->getBasicBlock();
11750   MachineFunction::iterator I = ++MBB->getIterator();
11751 
11752   Register DstReg = MI.getOperand(0).getReg();
11753   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11754   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11755   Register mainDstReg = MRI.createVirtualRegister(RC);
11756   Register restoreDstReg = MRI.createVirtualRegister(RC);
11757 
11758   MVT PVT = getPointerTy(MF->getDataLayout());
11759   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11760          "Invalid Pointer Size!");
11761   // For v = setjmp(buf), we generate
11762   //
11763   // thisMBB:
11764   //  SjLjSetup mainMBB
11765   //  bl mainMBB
11766   //  v_restore = 1
11767   //  b sinkMBB
11768   //
11769   // mainMBB:
11770   //  buf[LabelOffset] = LR
11771   //  v_main = 0
11772   //
11773   // sinkMBB:
11774   //  v = phi(main, restore)
11775   //
11776 
11777   MachineBasicBlock *thisMBB = MBB;
11778   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11779   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11780   MF->insert(I, mainMBB);
11781   MF->insert(I, sinkMBB);
11782 
11783   MachineInstrBuilder MIB;
11784 
11785   // Transfer the remainder of BB and its successor edges to sinkMBB.
11786   sinkMBB->splice(sinkMBB->begin(), MBB,
11787                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11788   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11789 
11790   // Note that the structure of the jmp_buf used here is not compatible
11791   // with that used by libc, and is not designed to be. Specifically, it
11792   // stores only those 'reserved' registers that LLVM does not otherwise
11793   // understand how to spill. Also, by convention, by the time this
11794   // intrinsic is called, Clang has already stored the frame address in the
11795   // first slot of the buffer and stack address in the third. Following the
11796   // X86 target code, we'll store the jump address in the second slot. We also
11797   // need to save the TOC pointer (R2) to handle jumps between shared
11798   // libraries, and that will be stored in the fourth slot. The thread
11799   // identifier (R13) is not affected.
11800 
11801   // thisMBB:
11802   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11803   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11804   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11805 
11806   // Prepare IP either in reg.
11807   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11808   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11809   Register BufReg = MI.getOperand(1).getReg();
11810 
11811   if (Subtarget.is64BitELFABI()) {
11812     setUsesTOCBasePtr(*MBB->getParent());
11813     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11814               .addReg(PPC::X2)
11815               .addImm(TOCOffset)
11816               .addReg(BufReg)
11817               .cloneMemRefs(MI);
11818   }
11819 
11820   // Naked functions never have a base pointer, and so we use r1. For all
11821   // other functions, this decision must be delayed until during PEI.
11822   unsigned BaseReg;
11823   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11824     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11825   else
11826     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11827 
11828   MIB = BuildMI(*thisMBB, MI, DL,
11829                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11830             .addReg(BaseReg)
11831             .addImm(BPOffset)
11832             .addReg(BufReg)
11833             .cloneMemRefs(MI);
11834 
11835   // Setup
11836   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11837   MIB.addRegMask(TRI->getNoPreservedMask());
11838 
11839   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11840 
11841   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11842           .addMBB(mainMBB);
11843   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11844 
11845   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11846   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11847 
11848   // mainMBB:
11849   //  mainDstReg = 0
11850   MIB =
11851       BuildMI(mainMBB, DL,
11852               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11853 
11854   // Store IP
11855   if (Subtarget.isPPC64()) {
11856     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11857             .addReg(LabelReg)
11858             .addImm(LabelOffset)
11859             .addReg(BufReg);
11860   } else {
11861     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11862             .addReg(LabelReg)
11863             .addImm(LabelOffset)
11864             .addReg(BufReg);
11865   }
11866   MIB.cloneMemRefs(MI);
11867 
11868   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11869   mainMBB->addSuccessor(sinkMBB);
11870 
11871   // sinkMBB:
11872   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11873           TII->get(PPC::PHI), DstReg)
11874     .addReg(mainDstReg).addMBB(mainMBB)
11875     .addReg(restoreDstReg).addMBB(thisMBB);
11876 
11877   MI.eraseFromParent();
11878   return sinkMBB;
11879 }
11880 
11881 MachineBasicBlock *
11882 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11883                                      MachineBasicBlock *MBB) const {
11884   DebugLoc DL = MI.getDebugLoc();
11885   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11886 
11887   MachineFunction *MF = MBB->getParent();
11888   MachineRegisterInfo &MRI = MF->getRegInfo();
11889 
11890   MVT PVT = getPointerTy(MF->getDataLayout());
11891   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11892          "Invalid Pointer Size!");
11893 
11894   const TargetRegisterClass *RC =
11895     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11896   Register Tmp = MRI.createVirtualRegister(RC);
11897   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11898   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11899   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11900   unsigned BP =
11901       (PVT == MVT::i64)
11902           ? PPC::X30
11903           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11904                                                               : PPC::R30);
11905 
11906   MachineInstrBuilder MIB;
11907 
11908   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11909   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11910   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11911   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11912 
11913   Register BufReg = MI.getOperand(0).getReg();
11914 
11915   // Reload FP (the jumped-to function may not have had a
11916   // frame pointer, and if so, then its r31 will be restored
11917   // as necessary).
11918   if (PVT == MVT::i64) {
11919     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11920             .addImm(0)
11921             .addReg(BufReg);
11922   } else {
11923     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11924             .addImm(0)
11925             .addReg(BufReg);
11926   }
11927   MIB.cloneMemRefs(MI);
11928 
11929   // Reload IP
11930   if (PVT == MVT::i64) {
11931     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11932             .addImm(LabelOffset)
11933             .addReg(BufReg);
11934   } else {
11935     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11936             .addImm(LabelOffset)
11937             .addReg(BufReg);
11938   }
11939   MIB.cloneMemRefs(MI);
11940 
11941   // Reload SP
11942   if (PVT == MVT::i64) {
11943     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11944             .addImm(SPOffset)
11945             .addReg(BufReg);
11946   } else {
11947     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11948             .addImm(SPOffset)
11949             .addReg(BufReg);
11950   }
11951   MIB.cloneMemRefs(MI);
11952 
11953   // Reload BP
11954   if (PVT == MVT::i64) {
11955     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11956             .addImm(BPOffset)
11957             .addReg(BufReg);
11958   } else {
11959     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11960             .addImm(BPOffset)
11961             .addReg(BufReg);
11962   }
11963   MIB.cloneMemRefs(MI);
11964 
11965   // Reload TOC
11966   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11967     setUsesTOCBasePtr(*MBB->getParent());
11968     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11969               .addImm(TOCOffset)
11970               .addReg(BufReg)
11971               .cloneMemRefs(MI);
11972   }
11973 
11974   // Jump
11975   BuildMI(*MBB, MI, DL,
11976           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11977   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11978 
11979   MI.eraseFromParent();
11980   return MBB;
11981 }
11982 
11983 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11984   // If the function specifically requests inline stack probes, emit them.
11985   if (MF.getFunction().hasFnAttribute("probe-stack"))
11986     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11987            "inline-asm";
11988   return false;
11989 }
11990 
11991 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11992   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11993   unsigned StackAlign = TFI->getStackAlignment();
11994   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11995          "Unexpected stack alignment");
11996   // The default stack probe size is 4096 if the function has no
11997   // stack-probe-size attribute.
11998   unsigned StackProbeSize = 4096;
11999   const Function &Fn = MF.getFunction();
12000   if (Fn.hasFnAttribute("stack-probe-size"))
12001     Fn.getFnAttribute("stack-probe-size")
12002         .getValueAsString()
12003         .getAsInteger(0, StackProbeSize);
12004   // Round down to the stack alignment.
12005   StackProbeSize &= ~(StackAlign - 1);
12006   return StackProbeSize ? StackProbeSize : StackAlign;
12007 }
12008 
12009 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
12010 // into three phases. In the first phase, it uses pseudo instruction
12011 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
12012 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
12013 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
12014 // MaxCallFrameSize so that it can calculate correct data area pointer.
12015 MachineBasicBlock *
12016 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
12017                                     MachineBasicBlock *MBB) const {
12018   const bool isPPC64 = Subtarget.isPPC64();
12019   MachineFunction *MF = MBB->getParent();
12020   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12021   DebugLoc DL = MI.getDebugLoc();
12022   const unsigned ProbeSize = getStackProbeSize(*MF);
12023   const BasicBlock *ProbedBB = MBB->getBasicBlock();
12024   MachineRegisterInfo &MRI = MF->getRegInfo();
12025   // The CFG of probing stack looks as
12026   //         +-----+
12027   //         | MBB |
12028   //         +--+--+
12029   //            |
12030   //       +----v----+
12031   //  +--->+ TestMBB +---+
12032   //  |    +----+----+   |
12033   //  |         |        |
12034   //  |   +-----v----+   |
12035   //  +---+ BlockMBB |   |
12036   //      +----------+   |
12037   //                     |
12038   //       +---------+   |
12039   //       | TailMBB +<--+
12040   //       +---------+
12041   // In MBB, calculate previous frame pointer and final stack pointer.
12042   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
12043   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
12044   // TailMBB is spliced via \p MI.
12045   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
12046   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
12047   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
12048 
12049   MachineFunction::iterator MBBIter = ++MBB->getIterator();
12050   MF->insert(MBBIter, TestMBB);
12051   MF->insert(MBBIter, BlockMBB);
12052   MF->insert(MBBIter, TailMBB);
12053 
12054   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
12055   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12056 
12057   Register DstReg = MI.getOperand(0).getReg();
12058   Register NegSizeReg = MI.getOperand(1).getReg();
12059   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12060   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12061   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12062   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12063 
12064   // Since value of NegSizeReg might be realigned in prologepilog, insert a
12065   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
12066   // NegSize.
12067   unsigned ProbeOpc;
12068   if (!MRI.hasOneNonDBGUse(NegSizeReg))
12069     ProbeOpc =
12070         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
12071   else
12072     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
12073     // and NegSizeReg will be allocated in the same phyreg to avoid
12074     // redundant copy when NegSizeReg has only one use which is current MI and
12075     // will be replaced by PREPARE_PROBED_ALLOCA then.
12076     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
12077                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
12078   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
12079       .addDef(ActualNegSizeReg)
12080       .addReg(NegSizeReg)
12081       .add(MI.getOperand(2))
12082       .add(MI.getOperand(3));
12083 
12084   // Calculate final stack pointer, which equals to SP + ActualNegSize.
12085   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12086           FinalStackPtr)
12087       .addReg(SPReg)
12088       .addReg(ActualNegSizeReg);
12089 
12090   // Materialize a scratch register for update.
12091   int64_t NegProbeSize = -(int64_t)ProbeSize;
12092   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
12093   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12094   if (!isInt<16>(NegProbeSize)) {
12095     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12096     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12097         .addImm(NegProbeSize >> 16);
12098     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12099             ScratchReg)
12100         .addReg(TempReg)
12101         .addImm(NegProbeSize & 0xFFFF);
12102   } else
12103     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12104         .addImm(NegProbeSize);
12105 
12106   {
12107     // Probing leading residual part.
12108     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12109     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12110         .addReg(ActualNegSizeReg)
12111         .addReg(ScratchReg);
12112     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12113     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12114         .addReg(Div)
12115         .addReg(ScratchReg);
12116     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12117     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12118         .addReg(Mul)
12119         .addReg(ActualNegSizeReg);
12120     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12121         .addReg(FramePointer)
12122         .addReg(SPReg)
12123         .addReg(NegMod);
12124   }
12125 
12126   {
12127     // Remaining part should be multiple of ProbeSize.
12128     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12129     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12130         .addReg(SPReg)
12131         .addReg(FinalStackPtr);
12132     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12133         .addImm(PPC::PRED_EQ)
12134         .addReg(CmpResult)
12135         .addMBB(TailMBB);
12136     TestMBB->addSuccessor(BlockMBB);
12137     TestMBB->addSuccessor(TailMBB);
12138   }
12139 
12140   {
12141     // Touch the block.
12142     // |P...|P...|P...
12143     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12144         .addReg(FramePointer)
12145         .addReg(SPReg)
12146         .addReg(ScratchReg);
12147     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12148     BlockMBB->addSuccessor(TestMBB);
12149   }
12150 
12151   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12152   // DYNAREAOFFSET pseudo instruction to get the future result.
12153   Register MaxCallFrameSizeReg =
12154       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12155   BuildMI(TailMBB, DL,
12156           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12157           MaxCallFrameSizeReg)
12158       .add(MI.getOperand(2))
12159       .add(MI.getOperand(3));
12160   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12161       .addReg(SPReg)
12162       .addReg(MaxCallFrameSizeReg);
12163 
12164   // Splice instructions after MI to TailMBB.
12165   TailMBB->splice(TailMBB->end(), MBB,
12166                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12167   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12168   MBB->addSuccessor(TestMBB);
12169 
12170   // Delete the pseudo instruction.
12171   MI.eraseFromParent();
12172 
12173   ++NumDynamicAllocaProbed;
12174   return TailMBB;
12175 }
12176 
12177 MachineBasicBlock *
12178 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12179                                                MachineBasicBlock *BB) const {
12180   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12181       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12182     if (Subtarget.is64BitELFABI() &&
12183         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12184         !Subtarget.isUsingPCRelativeCalls()) {
12185       // Call lowering should have added an r2 operand to indicate a dependence
12186       // on the TOC base pointer value. It can't however, because there is no
12187       // way to mark the dependence as implicit there, and so the stackmap code
12188       // will confuse it with a regular operand. Instead, add the dependence
12189       // here.
12190       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12191     }
12192 
12193     return emitPatchPoint(MI, BB);
12194   }
12195 
12196   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12197       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12198     return emitEHSjLjSetJmp(MI, BB);
12199   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12200              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12201     return emitEHSjLjLongJmp(MI, BB);
12202   }
12203 
12204   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12205 
12206   // To "insert" these instructions we actually have to insert their
12207   // control-flow patterns.
12208   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12209   MachineFunction::iterator It = ++BB->getIterator();
12210 
12211   MachineFunction *F = BB->getParent();
12212   MachineRegisterInfo &MRI = F->getRegInfo();
12213 
12214   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12215       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12216       MI.getOpcode() == PPC::SELECT_I8) {
12217     SmallVector<MachineOperand, 2> Cond;
12218     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12219         MI.getOpcode() == PPC::SELECT_CC_I8)
12220       Cond.push_back(MI.getOperand(4));
12221     else
12222       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12223     Cond.push_back(MI.getOperand(1));
12224 
12225     DebugLoc dl = MI.getDebugLoc();
12226     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12227                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12228   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12229              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12230              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12231              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12232              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12233              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12234              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12235              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12236              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12237              MI.getOpcode() == PPC::SELECT_F4 ||
12238              MI.getOpcode() == PPC::SELECT_F8 ||
12239              MI.getOpcode() == PPC::SELECT_F16 ||
12240              MI.getOpcode() == PPC::SELECT_SPE ||
12241              MI.getOpcode() == PPC::SELECT_SPE4 ||
12242              MI.getOpcode() == PPC::SELECT_VRRC ||
12243              MI.getOpcode() == PPC::SELECT_VSFRC ||
12244              MI.getOpcode() == PPC::SELECT_VSSRC ||
12245              MI.getOpcode() == PPC::SELECT_VSRC) {
12246     // The incoming instruction knows the destination vreg to set, the
12247     // condition code register to branch on, the true/false values to
12248     // select between, and a branch opcode to use.
12249 
12250     //  thisMBB:
12251     //  ...
12252     //   TrueVal = ...
12253     //   cmpTY ccX, r1, r2
12254     //   bCC copy1MBB
12255     //   fallthrough --> copy0MBB
12256     MachineBasicBlock *thisMBB = BB;
12257     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12258     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12259     DebugLoc dl = MI.getDebugLoc();
12260     F->insert(It, copy0MBB);
12261     F->insert(It, sinkMBB);
12262 
12263     // Transfer the remainder of BB and its successor edges to sinkMBB.
12264     sinkMBB->splice(sinkMBB->begin(), BB,
12265                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12266     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12267 
12268     // Next, add the true and fallthrough blocks as its successors.
12269     BB->addSuccessor(copy0MBB);
12270     BB->addSuccessor(sinkMBB);
12271 
12272     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12273         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12274         MI.getOpcode() == PPC::SELECT_F16 ||
12275         MI.getOpcode() == PPC::SELECT_SPE4 ||
12276         MI.getOpcode() == PPC::SELECT_SPE ||
12277         MI.getOpcode() == PPC::SELECT_VRRC ||
12278         MI.getOpcode() == PPC::SELECT_VSFRC ||
12279         MI.getOpcode() == PPC::SELECT_VSSRC ||
12280         MI.getOpcode() == PPC::SELECT_VSRC) {
12281       BuildMI(BB, dl, TII->get(PPC::BC))
12282           .addReg(MI.getOperand(1).getReg())
12283           .addMBB(sinkMBB);
12284     } else {
12285       unsigned SelectPred = MI.getOperand(4).getImm();
12286       BuildMI(BB, dl, TII->get(PPC::BCC))
12287           .addImm(SelectPred)
12288           .addReg(MI.getOperand(1).getReg())
12289           .addMBB(sinkMBB);
12290     }
12291 
12292     //  copy0MBB:
12293     //   %FalseValue = ...
12294     //   # fallthrough to sinkMBB
12295     BB = copy0MBB;
12296 
12297     // Update machine-CFG edges
12298     BB->addSuccessor(sinkMBB);
12299 
12300     //  sinkMBB:
12301     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12302     //  ...
12303     BB = sinkMBB;
12304     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12305         .addReg(MI.getOperand(3).getReg())
12306         .addMBB(copy0MBB)
12307         .addReg(MI.getOperand(2).getReg())
12308         .addMBB(thisMBB);
12309   } else if (MI.getOpcode() == PPC::ReadTB) {
12310     // To read the 64-bit time-base register on a 32-bit target, we read the
12311     // two halves. Should the counter have wrapped while it was being read, we
12312     // need to try again.
12313     // ...
12314     // readLoop:
12315     // mfspr Rx,TBU # load from TBU
12316     // mfspr Ry,TB  # load from TB
12317     // mfspr Rz,TBU # load from TBU
12318     // cmpw crX,Rx,Rz # check if 'old'='new'
12319     // bne readLoop   # branch if they're not equal
12320     // ...
12321 
12322     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12323     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12324     DebugLoc dl = MI.getDebugLoc();
12325     F->insert(It, readMBB);
12326     F->insert(It, sinkMBB);
12327 
12328     // Transfer the remainder of BB and its successor edges to sinkMBB.
12329     sinkMBB->splice(sinkMBB->begin(), BB,
12330                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12331     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12332 
12333     BB->addSuccessor(readMBB);
12334     BB = readMBB;
12335 
12336     MachineRegisterInfo &RegInfo = F->getRegInfo();
12337     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12338     Register LoReg = MI.getOperand(0).getReg();
12339     Register HiReg = MI.getOperand(1).getReg();
12340 
12341     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12342     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12343     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12344 
12345     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12346 
12347     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12348         .addReg(HiReg)
12349         .addReg(ReadAgainReg);
12350     BuildMI(BB, dl, TII->get(PPC::BCC))
12351         .addImm(PPC::PRED_NE)
12352         .addReg(CmpReg)
12353         .addMBB(readMBB);
12354 
12355     BB->addSuccessor(readMBB);
12356     BB->addSuccessor(sinkMBB);
12357   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12358     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12359   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12360     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12361   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12362     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12363   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12364     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12365 
12366   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12367     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12368   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12369     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12370   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12371     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12372   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12373     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12374 
12375   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12376     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12377   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12378     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12379   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12380     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12381   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12382     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12383 
12384   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12385     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12386   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12387     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12388   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12389     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12390   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12391     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12392 
12393   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12394     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12395   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12396     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12397   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12398     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12399   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12400     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12401 
12402   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12403     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12404   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12405     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12406   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12407     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12408   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12409     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12410 
12411   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12412     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12413   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12414     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12415   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12416     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12417   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12418     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12419 
12420   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12421     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12422   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12423     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12424   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12425     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12426   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12427     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12428 
12429   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12430     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12431   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12432     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12433   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12434     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12435   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12436     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12437 
12438   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12439     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12440   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12441     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12442   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12443     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12444   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12445     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12446 
12447   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12448     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12449   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12450     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12451   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12452     BB = EmitAtomicBinary(MI, BB, 4, 0);
12453   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12454     BB = EmitAtomicBinary(MI, BB, 8, 0);
12455   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12456            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12457            (Subtarget.hasPartwordAtomics() &&
12458             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12459            (Subtarget.hasPartwordAtomics() &&
12460             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12461     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12462 
12463     auto LoadMnemonic = PPC::LDARX;
12464     auto StoreMnemonic = PPC::STDCX;
12465     switch (MI.getOpcode()) {
12466     default:
12467       llvm_unreachable("Compare and swap of unknown size");
12468     case PPC::ATOMIC_CMP_SWAP_I8:
12469       LoadMnemonic = PPC::LBARX;
12470       StoreMnemonic = PPC::STBCX;
12471       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12472       break;
12473     case PPC::ATOMIC_CMP_SWAP_I16:
12474       LoadMnemonic = PPC::LHARX;
12475       StoreMnemonic = PPC::STHCX;
12476       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12477       break;
12478     case PPC::ATOMIC_CMP_SWAP_I32:
12479       LoadMnemonic = PPC::LWARX;
12480       StoreMnemonic = PPC::STWCX;
12481       break;
12482     case PPC::ATOMIC_CMP_SWAP_I64:
12483       LoadMnemonic = PPC::LDARX;
12484       StoreMnemonic = PPC::STDCX;
12485       break;
12486     }
12487     Register dest = MI.getOperand(0).getReg();
12488     Register ptrA = MI.getOperand(1).getReg();
12489     Register ptrB = MI.getOperand(2).getReg();
12490     Register oldval = MI.getOperand(3).getReg();
12491     Register newval = MI.getOperand(4).getReg();
12492     DebugLoc dl = MI.getDebugLoc();
12493 
12494     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12495     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12496     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12497     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12498     F->insert(It, loop1MBB);
12499     F->insert(It, loop2MBB);
12500     F->insert(It, midMBB);
12501     F->insert(It, exitMBB);
12502     exitMBB->splice(exitMBB->begin(), BB,
12503                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12504     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12505 
12506     //  thisMBB:
12507     //   ...
12508     //   fallthrough --> loopMBB
12509     BB->addSuccessor(loop1MBB);
12510 
12511     // loop1MBB:
12512     //   l[bhwd]arx dest, ptr
12513     //   cmp[wd] dest, oldval
12514     //   bne- midMBB
12515     // loop2MBB:
12516     //   st[bhwd]cx. newval, ptr
12517     //   bne- loopMBB
12518     //   b exitBB
12519     // midMBB:
12520     //   st[bhwd]cx. dest, ptr
12521     // exitBB:
12522     BB = loop1MBB;
12523     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12524     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12525         .addReg(oldval)
12526         .addReg(dest);
12527     BuildMI(BB, dl, TII->get(PPC::BCC))
12528         .addImm(PPC::PRED_NE)
12529         .addReg(PPC::CR0)
12530         .addMBB(midMBB);
12531     BB->addSuccessor(loop2MBB);
12532     BB->addSuccessor(midMBB);
12533 
12534     BB = loop2MBB;
12535     BuildMI(BB, dl, TII->get(StoreMnemonic))
12536         .addReg(newval)
12537         .addReg(ptrA)
12538         .addReg(ptrB);
12539     BuildMI(BB, dl, TII->get(PPC::BCC))
12540         .addImm(PPC::PRED_NE)
12541         .addReg(PPC::CR0)
12542         .addMBB(loop1MBB);
12543     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12544     BB->addSuccessor(loop1MBB);
12545     BB->addSuccessor(exitMBB);
12546 
12547     BB = midMBB;
12548     BuildMI(BB, dl, TII->get(StoreMnemonic))
12549         .addReg(dest)
12550         .addReg(ptrA)
12551         .addReg(ptrB);
12552     BB->addSuccessor(exitMBB);
12553 
12554     //  exitMBB:
12555     //   ...
12556     BB = exitMBB;
12557   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12558              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12559     // We must use 64-bit registers for addresses when targeting 64-bit,
12560     // since we're actually doing arithmetic on them.  Other registers
12561     // can be 32-bit.
12562     bool is64bit = Subtarget.isPPC64();
12563     bool isLittleEndian = Subtarget.isLittleEndian();
12564     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12565 
12566     Register dest = MI.getOperand(0).getReg();
12567     Register ptrA = MI.getOperand(1).getReg();
12568     Register ptrB = MI.getOperand(2).getReg();
12569     Register oldval = MI.getOperand(3).getReg();
12570     Register newval = MI.getOperand(4).getReg();
12571     DebugLoc dl = MI.getDebugLoc();
12572 
12573     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12574     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12575     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12576     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12577     F->insert(It, loop1MBB);
12578     F->insert(It, loop2MBB);
12579     F->insert(It, midMBB);
12580     F->insert(It, exitMBB);
12581     exitMBB->splice(exitMBB->begin(), BB,
12582                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12583     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12584 
12585     MachineRegisterInfo &RegInfo = F->getRegInfo();
12586     const TargetRegisterClass *RC =
12587         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12588     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12589 
12590     Register PtrReg = RegInfo.createVirtualRegister(RC);
12591     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12592     Register ShiftReg =
12593         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12594     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12595     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12596     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12597     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12598     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12599     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12600     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12601     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12602     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12603     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12604     Register Ptr1Reg;
12605     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12606     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12607     //  thisMBB:
12608     //   ...
12609     //   fallthrough --> loopMBB
12610     BB->addSuccessor(loop1MBB);
12611 
12612     // The 4-byte load must be aligned, while a char or short may be
12613     // anywhere in the word.  Hence all this nasty bookkeeping code.
12614     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12615     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12616     //   xori shift, shift1, 24 [16]
12617     //   rlwinm ptr, ptr1, 0, 0, 29
12618     //   slw newval2, newval, shift
12619     //   slw oldval2, oldval,shift
12620     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12621     //   slw mask, mask2, shift
12622     //   and newval3, newval2, mask
12623     //   and oldval3, oldval2, mask
12624     // loop1MBB:
12625     //   lwarx tmpDest, ptr
12626     //   and tmp, tmpDest, mask
12627     //   cmpw tmp, oldval3
12628     //   bne- midMBB
12629     // loop2MBB:
12630     //   andc tmp2, tmpDest, mask
12631     //   or tmp4, tmp2, newval3
12632     //   stwcx. tmp4, ptr
12633     //   bne- loop1MBB
12634     //   b exitBB
12635     // midMBB:
12636     //   stwcx. tmpDest, ptr
12637     // exitBB:
12638     //   srw dest, tmpDest, shift
12639     if (ptrA != ZeroReg) {
12640       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12641       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12642           .addReg(ptrA)
12643           .addReg(ptrB);
12644     } else {
12645       Ptr1Reg = ptrB;
12646     }
12647 
12648     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12649     // mode.
12650     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12651         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12652         .addImm(3)
12653         .addImm(27)
12654         .addImm(is8bit ? 28 : 27);
12655     if (!isLittleEndian)
12656       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12657           .addReg(Shift1Reg)
12658           .addImm(is8bit ? 24 : 16);
12659     if (is64bit)
12660       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12661           .addReg(Ptr1Reg)
12662           .addImm(0)
12663           .addImm(61);
12664     else
12665       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12666           .addReg(Ptr1Reg)
12667           .addImm(0)
12668           .addImm(0)
12669           .addImm(29);
12670     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12671         .addReg(newval)
12672         .addReg(ShiftReg);
12673     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12674         .addReg(oldval)
12675         .addReg(ShiftReg);
12676     if (is8bit)
12677       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12678     else {
12679       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12680       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12681           .addReg(Mask3Reg)
12682           .addImm(65535);
12683     }
12684     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12685         .addReg(Mask2Reg)
12686         .addReg(ShiftReg);
12687     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12688         .addReg(NewVal2Reg)
12689         .addReg(MaskReg);
12690     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12691         .addReg(OldVal2Reg)
12692         .addReg(MaskReg);
12693 
12694     BB = loop1MBB;
12695     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12696         .addReg(ZeroReg)
12697         .addReg(PtrReg);
12698     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12699         .addReg(TmpDestReg)
12700         .addReg(MaskReg);
12701     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12702         .addReg(TmpReg)
12703         .addReg(OldVal3Reg);
12704     BuildMI(BB, dl, TII->get(PPC::BCC))
12705         .addImm(PPC::PRED_NE)
12706         .addReg(PPC::CR0)
12707         .addMBB(midMBB);
12708     BB->addSuccessor(loop2MBB);
12709     BB->addSuccessor(midMBB);
12710 
12711     BB = loop2MBB;
12712     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12713         .addReg(TmpDestReg)
12714         .addReg(MaskReg);
12715     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12716         .addReg(Tmp2Reg)
12717         .addReg(NewVal3Reg);
12718     BuildMI(BB, dl, TII->get(PPC::STWCX))
12719         .addReg(Tmp4Reg)
12720         .addReg(ZeroReg)
12721         .addReg(PtrReg);
12722     BuildMI(BB, dl, TII->get(PPC::BCC))
12723         .addImm(PPC::PRED_NE)
12724         .addReg(PPC::CR0)
12725         .addMBB(loop1MBB);
12726     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12727     BB->addSuccessor(loop1MBB);
12728     BB->addSuccessor(exitMBB);
12729 
12730     BB = midMBB;
12731     BuildMI(BB, dl, TII->get(PPC::STWCX))
12732         .addReg(TmpDestReg)
12733         .addReg(ZeroReg)
12734         .addReg(PtrReg);
12735     BB->addSuccessor(exitMBB);
12736 
12737     //  exitMBB:
12738     //   ...
12739     BB = exitMBB;
12740     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12741         .addReg(TmpReg)
12742         .addReg(ShiftReg);
12743   } else if (MI.getOpcode() == PPC::FADDrtz) {
12744     // This pseudo performs an FADD with rounding mode temporarily forced
12745     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12746     // is not modeled at the SelectionDAG level.
12747     Register Dest = MI.getOperand(0).getReg();
12748     Register Src1 = MI.getOperand(1).getReg();
12749     Register Src2 = MI.getOperand(2).getReg();
12750     DebugLoc dl = MI.getDebugLoc();
12751 
12752     MachineRegisterInfo &RegInfo = F->getRegInfo();
12753     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12754 
12755     // Save FPSCR value.
12756     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12757 
12758     // Set rounding mode to round-to-zero.
12759     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12760         .addImm(31)
12761         .addReg(PPC::RM, RegState::ImplicitDefine);
12762 
12763     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12764         .addImm(30)
12765         .addReg(PPC::RM, RegState::ImplicitDefine);
12766 
12767     // Perform addition.
12768     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12769                    .addReg(Src1)
12770                    .addReg(Src2);
12771     if (MI.getFlag(MachineInstr::NoFPExcept))
12772       MIB.setMIFlag(MachineInstr::NoFPExcept);
12773 
12774     // Restore FPSCR value.
12775     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12776   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12777              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12778              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12779              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12780     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12781                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12782                           ? PPC::ANDI8_rec
12783                           : PPC::ANDI_rec;
12784     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12785                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12786 
12787     MachineRegisterInfo &RegInfo = F->getRegInfo();
12788     Register Dest = RegInfo.createVirtualRegister(
12789         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12790 
12791     DebugLoc Dl = MI.getDebugLoc();
12792     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12793         .addReg(MI.getOperand(1).getReg())
12794         .addImm(1);
12795     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12796             MI.getOperand(0).getReg())
12797         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12798   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12799     DebugLoc Dl = MI.getDebugLoc();
12800     MachineRegisterInfo &RegInfo = F->getRegInfo();
12801     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12802     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12803     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12804             MI.getOperand(0).getReg())
12805         .addReg(CRReg);
12806   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12807     DebugLoc Dl = MI.getDebugLoc();
12808     unsigned Imm = MI.getOperand(1).getImm();
12809     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12810     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12811             MI.getOperand(0).getReg())
12812         .addReg(PPC::CR0EQ);
12813   } else if (MI.getOpcode() == PPC::SETRNDi) {
12814     DebugLoc dl = MI.getDebugLoc();
12815     Register OldFPSCRReg = MI.getOperand(0).getReg();
12816 
12817     // Save FPSCR value.
12818     if (MRI.use_empty(OldFPSCRReg))
12819       BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12820     else
12821       BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12822 
12823     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12824     // the following settings:
12825     //   00 Round to nearest
12826     //   01 Round to 0
12827     //   10 Round to +inf
12828     //   11 Round to -inf
12829 
12830     // When the operand is immediate, using the two least significant bits of
12831     // the immediate to set the bits 62:63 of FPSCR.
12832     unsigned Mode = MI.getOperand(1).getImm();
12833     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12834         .addImm(31)
12835         .addReg(PPC::RM, RegState::ImplicitDefine);
12836 
12837     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12838         .addImm(30)
12839         .addReg(PPC::RM, RegState::ImplicitDefine);
12840   } else if (MI.getOpcode() == PPC::SETRND) {
12841     DebugLoc dl = MI.getDebugLoc();
12842 
12843     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12844     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12845     // If the target doesn't have DirectMove, we should use stack to do the
12846     // conversion, because the target doesn't have the instructions like mtvsrd
12847     // or mfvsrd to do this conversion directly.
12848     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12849       if (Subtarget.hasDirectMove()) {
12850         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12851           .addReg(SrcReg);
12852       } else {
12853         // Use stack to do the register copy.
12854         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12855         MachineRegisterInfo &RegInfo = F->getRegInfo();
12856         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12857         if (RC == &PPC::F8RCRegClass) {
12858           // Copy register from F8RCRegClass to G8RCRegclass.
12859           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12860                  "Unsupported RegClass.");
12861 
12862           StoreOp = PPC::STFD;
12863           LoadOp = PPC::LD;
12864         } else {
12865           // Copy register from G8RCRegClass to F8RCRegclass.
12866           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12867                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12868                  "Unsupported RegClass.");
12869         }
12870 
12871         MachineFrameInfo &MFI = F->getFrameInfo();
12872         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12873 
12874         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12875             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12876             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12877             MFI.getObjectAlign(FrameIdx));
12878 
12879         // Store the SrcReg into the stack.
12880         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12881           .addReg(SrcReg)
12882           .addImm(0)
12883           .addFrameIndex(FrameIdx)
12884           .addMemOperand(MMOStore);
12885 
12886         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12887             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12888             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12889             MFI.getObjectAlign(FrameIdx));
12890 
12891         // Load from the stack where SrcReg is stored, and save to DestReg,
12892         // so we have done the RegClass conversion from RegClass::SrcReg to
12893         // RegClass::DestReg.
12894         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12895           .addImm(0)
12896           .addFrameIndex(FrameIdx)
12897           .addMemOperand(MMOLoad);
12898       }
12899     };
12900 
12901     Register OldFPSCRReg = MI.getOperand(0).getReg();
12902 
12903     // Save FPSCR value.
12904     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12905 
12906     // When the operand is gprc register, use two least significant bits of the
12907     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12908     //
12909     // copy OldFPSCRTmpReg, OldFPSCRReg
12910     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12911     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12912     // copy NewFPSCRReg, NewFPSCRTmpReg
12913     // mtfsf 255, NewFPSCRReg
12914     MachineOperand SrcOp = MI.getOperand(1);
12915     MachineRegisterInfo &RegInfo = F->getRegInfo();
12916     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12917 
12918     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12919 
12920     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12921     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12922 
12923     // The first operand of INSERT_SUBREG should be a register which has
12924     // subregisters, we only care about its RegClass, so we should use an
12925     // IMPLICIT_DEF register.
12926     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12927     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12928       .addReg(ImDefReg)
12929       .add(SrcOp)
12930       .addImm(1);
12931 
12932     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12933     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12934       .addReg(OldFPSCRTmpReg)
12935       .addReg(ExtSrcReg)
12936       .addImm(0)
12937       .addImm(62);
12938 
12939     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12940     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12941 
12942     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12943     // bits of FPSCR.
12944     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12945       .addImm(255)
12946       .addReg(NewFPSCRReg)
12947       .addImm(0)
12948       .addImm(0);
12949   } else if (MI.getOpcode() == PPC::SETFLM) {
12950     DebugLoc Dl = MI.getDebugLoc();
12951 
12952     // Result of setflm is previous FPSCR content, so we need to save it first.
12953     Register OldFPSCRReg = MI.getOperand(0).getReg();
12954     if (MRI.use_empty(OldFPSCRReg))
12955       BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12956     else
12957       BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12958 
12959     // Put bits in 32:63 to FPSCR.
12960     Register NewFPSCRReg = MI.getOperand(1).getReg();
12961     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12962         .addImm(255)
12963         .addReg(NewFPSCRReg)
12964         .addImm(0)
12965         .addImm(0);
12966   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12967              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12968     return emitProbedAlloca(MI, BB);
12969   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12970     DebugLoc DL = MI.getDebugLoc();
12971     Register Src = MI.getOperand(2).getReg();
12972     Register Lo = MI.getOperand(0).getReg();
12973     Register Hi = MI.getOperand(1).getReg();
12974     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12975         .addDef(Lo)
12976         .addUse(Src, 0, PPC::sub_gp8_x1);
12977     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12978         .addDef(Hi)
12979         .addUse(Src, 0, PPC::sub_gp8_x0);
12980   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12981              MI.getOpcode() == PPC::STQX_PSEUDO) {
12982     DebugLoc DL = MI.getDebugLoc();
12983     // Ptr is used as the ptr_rc_no_r0 part
12984     // of LQ/STQ's memory operand and adding result of RA and RB,
12985     // so it has to be g8rc_and_g8rc_nox0.
12986     Register Ptr =
12987         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12988     Register Val = MI.getOperand(0).getReg();
12989     Register RA = MI.getOperand(1).getReg();
12990     Register RB = MI.getOperand(2).getReg();
12991     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12992     BuildMI(*BB, MI, DL,
12993             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12994                                               : TII->get(PPC::STQ))
12995         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12996         .addImm(0)
12997         .addReg(Ptr);
12998   } else {
12999     llvm_unreachable("Unexpected instr type to insert");
13000   }
13001 
13002   MI.eraseFromParent(); // The pseudo instruction is gone now.
13003   return BB;
13004 }
13005 
13006 //===----------------------------------------------------------------------===//
13007 // Target Optimization Hooks
13008 //===----------------------------------------------------------------------===//
13009 
13010 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
13011   // For the estimates, convergence is quadratic, so we essentially double the
13012   // number of digits correct after every iteration. For both FRE and FRSQRTE,
13013   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
13014   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
13015   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
13016   if (VT.getScalarType() == MVT::f64)
13017     RefinementSteps++;
13018   return RefinementSteps;
13019 }
13020 
13021 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
13022                                             const DenormalMode &Mode) const {
13023   // We only have VSX Vector Test for software Square Root.
13024   EVT VT = Op.getValueType();
13025   if (!isTypeLegal(MVT::i1) ||
13026       (VT != MVT::f64 &&
13027        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
13028     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
13029 
13030   SDLoc DL(Op);
13031   // The output register of FTSQRT is CR field.
13032   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
13033   // ftsqrt BF,FRB
13034   // Let e_b be the unbiased exponent of the double-precision
13035   // floating-point operand in register FRB.
13036   // fe_flag is set to 1 if either of the following conditions occurs.
13037   //   - The double-precision floating-point operand in register FRB is a zero,
13038   //     a NaN, or an infinity, or a negative value.
13039   //   - e_b is less than or equal to -970.
13040   // Otherwise fe_flag is set to 0.
13041   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
13042   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
13043   // exponent is less than -970)
13044   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
13045   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
13046                                     FTSQRT, SRIdxVal),
13047                  0);
13048 }
13049 
13050 SDValue
13051 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
13052                                                SelectionDAG &DAG) const {
13053   // We only have VSX Vector Square Root.
13054   EVT VT = Op.getValueType();
13055   if (VT != MVT::f64 &&
13056       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
13057     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
13058 
13059   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
13060 }
13061 
13062 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
13063                                            int Enabled, int &RefinementSteps,
13064                                            bool &UseOneConstNR,
13065                                            bool Reciprocal) const {
13066   EVT VT = Operand.getValueType();
13067   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
13068       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
13069       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13070       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13071     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13072       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13073 
13074     // The Newton-Raphson computation with a single constant does not provide
13075     // enough accuracy on some CPUs.
13076     UseOneConstNR = !Subtarget.needsTwoConstNR();
13077     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
13078   }
13079   return SDValue();
13080 }
13081 
13082 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
13083                                             int Enabled,
13084                                             int &RefinementSteps) const {
13085   EVT VT = Operand.getValueType();
13086   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13087       (VT == MVT::f64 && Subtarget.hasFRE()) ||
13088       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13089       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13090     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13091       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13092     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13093   }
13094   return SDValue();
13095 }
13096 
13097 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13098   // Note: This functionality is used only when unsafe-fp-math is enabled, and
13099   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13100   // enabled for division), this functionality is redundant with the default
13101   // combiner logic (once the division -> reciprocal/multiply transformation
13102   // has taken place). As a result, this matters more for older cores than for
13103   // newer ones.
13104 
13105   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13106   // reciprocal if there are two or more FDIVs (for embedded cores with only
13107   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13108   switch (Subtarget.getCPUDirective()) {
13109   default:
13110     return 3;
13111   case PPC::DIR_440:
13112   case PPC::DIR_A2:
13113   case PPC::DIR_E500:
13114   case PPC::DIR_E500mc:
13115   case PPC::DIR_E5500:
13116     return 2;
13117   }
13118 }
13119 
13120 // isConsecutiveLSLoc needs to work even if all adds have not yet been
13121 // collapsed, and so we need to look through chains of them.
13122 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13123                                      int64_t& Offset, SelectionDAG &DAG) {
13124   if (DAG.isBaseWithConstantOffset(Loc)) {
13125     Base = Loc.getOperand(0);
13126     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13127 
13128     // The base might itself be a base plus an offset, and if so, accumulate
13129     // that as well.
13130     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13131   }
13132 }
13133 
13134 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13135                             unsigned Bytes, int Dist,
13136                             SelectionDAG &DAG) {
13137   if (VT.getSizeInBits() / 8 != Bytes)
13138     return false;
13139 
13140   SDValue BaseLoc = Base->getBasePtr();
13141   if (Loc.getOpcode() == ISD::FrameIndex) {
13142     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13143       return false;
13144     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13145     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13146     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13147     int FS  = MFI.getObjectSize(FI);
13148     int BFS = MFI.getObjectSize(BFI);
13149     if (FS != BFS || FS != (int)Bytes) return false;
13150     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13151   }
13152 
13153   SDValue Base1 = Loc, Base2 = BaseLoc;
13154   int64_t Offset1 = 0, Offset2 = 0;
13155   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13156   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13157   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13158     return true;
13159 
13160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13161   const GlobalValue *GV1 = nullptr;
13162   const GlobalValue *GV2 = nullptr;
13163   Offset1 = 0;
13164   Offset2 = 0;
13165   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13166   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13167   if (isGA1 && isGA2 && GV1 == GV2)
13168     return Offset1 == (Offset2 + Dist*Bytes);
13169   return false;
13170 }
13171 
13172 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13173 // not enforce equality of the chain operands.
13174 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13175                             unsigned Bytes, int Dist,
13176                             SelectionDAG &DAG) {
13177   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13178     EVT VT = LS->getMemoryVT();
13179     SDValue Loc = LS->getBasePtr();
13180     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13181   }
13182 
13183   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13184     EVT VT;
13185     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13186     default: return false;
13187     case Intrinsic::ppc_altivec_lvx:
13188     case Intrinsic::ppc_altivec_lvxl:
13189     case Intrinsic::ppc_vsx_lxvw4x:
13190     case Intrinsic::ppc_vsx_lxvw4x_be:
13191       VT = MVT::v4i32;
13192       break;
13193     case Intrinsic::ppc_vsx_lxvd2x:
13194     case Intrinsic::ppc_vsx_lxvd2x_be:
13195       VT = MVT::v2f64;
13196       break;
13197     case Intrinsic::ppc_altivec_lvebx:
13198       VT = MVT::i8;
13199       break;
13200     case Intrinsic::ppc_altivec_lvehx:
13201       VT = MVT::i16;
13202       break;
13203     case Intrinsic::ppc_altivec_lvewx:
13204       VT = MVT::i32;
13205       break;
13206     }
13207 
13208     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13209   }
13210 
13211   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13212     EVT VT;
13213     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13214     default: return false;
13215     case Intrinsic::ppc_altivec_stvx:
13216     case Intrinsic::ppc_altivec_stvxl:
13217     case Intrinsic::ppc_vsx_stxvw4x:
13218       VT = MVT::v4i32;
13219       break;
13220     case Intrinsic::ppc_vsx_stxvd2x:
13221       VT = MVT::v2f64;
13222       break;
13223     case Intrinsic::ppc_vsx_stxvw4x_be:
13224       VT = MVT::v4i32;
13225       break;
13226     case Intrinsic::ppc_vsx_stxvd2x_be:
13227       VT = MVT::v2f64;
13228       break;
13229     case Intrinsic::ppc_altivec_stvebx:
13230       VT = MVT::i8;
13231       break;
13232     case Intrinsic::ppc_altivec_stvehx:
13233       VT = MVT::i16;
13234       break;
13235     case Intrinsic::ppc_altivec_stvewx:
13236       VT = MVT::i32;
13237       break;
13238     }
13239 
13240     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13241   }
13242 
13243   return false;
13244 }
13245 
13246 // Return true is there is a nearyby consecutive load to the one provided
13247 // (regardless of alignment). We search up and down the chain, looking though
13248 // token factors and other loads (but nothing else). As a result, a true result
13249 // indicates that it is safe to create a new consecutive load adjacent to the
13250 // load provided.
13251 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13252   SDValue Chain = LD->getChain();
13253   EVT VT = LD->getMemoryVT();
13254 
13255   SmallSet<SDNode *, 16> LoadRoots;
13256   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13257   SmallSet<SDNode *, 16> Visited;
13258 
13259   // First, search up the chain, branching to follow all token-factor operands.
13260   // If we find a consecutive load, then we're done, otherwise, record all
13261   // nodes just above the top-level loads and token factors.
13262   while (!Queue.empty()) {
13263     SDNode *ChainNext = Queue.pop_back_val();
13264     if (!Visited.insert(ChainNext).second)
13265       continue;
13266 
13267     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13268       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13269         return true;
13270 
13271       if (!Visited.count(ChainLD->getChain().getNode()))
13272         Queue.push_back(ChainLD->getChain().getNode());
13273     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13274       for (const SDUse &O : ChainNext->ops())
13275         if (!Visited.count(O.getNode()))
13276           Queue.push_back(O.getNode());
13277     } else
13278       LoadRoots.insert(ChainNext);
13279   }
13280 
13281   // Second, search down the chain, starting from the top-level nodes recorded
13282   // in the first phase. These top-level nodes are the nodes just above all
13283   // loads and token factors. Starting with their uses, recursively look though
13284   // all loads (just the chain uses) and token factors to find a consecutive
13285   // load.
13286   Visited.clear();
13287   Queue.clear();
13288 
13289   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13290        IE = LoadRoots.end(); I != IE; ++I) {
13291     Queue.push_back(*I);
13292 
13293     while (!Queue.empty()) {
13294       SDNode *LoadRoot = Queue.pop_back_val();
13295       if (!Visited.insert(LoadRoot).second)
13296         continue;
13297 
13298       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13299         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13300           return true;
13301 
13302       for (SDNode *U : LoadRoot->uses())
13303         if (((isa<MemSDNode>(U) &&
13304               cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13305              U->getOpcode() == ISD::TokenFactor) &&
13306             !Visited.count(U))
13307           Queue.push_back(U);
13308     }
13309   }
13310 
13311   return false;
13312 }
13313 
13314 /// This function is called when we have proved that a SETCC node can be replaced
13315 /// by subtraction (and other supporting instructions) so that the result of
13316 /// comparison is kept in a GPR instead of CR. This function is purely for
13317 /// codegen purposes and has some flags to guide the codegen process.
13318 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13319                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13320   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13321 
13322   // Zero extend the operands to the largest legal integer. Originally, they
13323   // must be of a strictly smaller size.
13324   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13325                          DAG.getConstant(Size, DL, MVT::i32));
13326   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13327                          DAG.getConstant(Size, DL, MVT::i32));
13328 
13329   // Swap if needed. Depends on the condition code.
13330   if (Swap)
13331     std::swap(Op0, Op1);
13332 
13333   // Subtract extended integers.
13334   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13335 
13336   // Move the sign bit to the least significant position and zero out the rest.
13337   // Now the least significant bit carries the result of original comparison.
13338   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13339                              DAG.getConstant(Size - 1, DL, MVT::i32));
13340   auto Final = Shifted;
13341 
13342   // Complement the result if needed. Based on the condition code.
13343   if (Complement)
13344     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13345                         DAG.getConstant(1, DL, MVT::i64));
13346 
13347   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13348 }
13349 
13350 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13351                                                   DAGCombinerInfo &DCI) const {
13352   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13353 
13354   SelectionDAG &DAG = DCI.DAG;
13355   SDLoc DL(N);
13356 
13357   // Size of integers being compared has a critical role in the following
13358   // analysis, so we prefer to do this when all types are legal.
13359   if (!DCI.isAfterLegalizeDAG())
13360     return SDValue();
13361 
13362   // If all users of SETCC extend its value to a legal integer type
13363   // then we replace SETCC with a subtraction
13364   for (const SDNode *U : N->uses())
13365     if (U->getOpcode() != ISD::ZERO_EXTEND)
13366       return SDValue();
13367 
13368   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13369   auto OpSize = N->getOperand(0).getValueSizeInBits();
13370 
13371   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13372 
13373   if (OpSize < Size) {
13374     switch (CC) {
13375     default: break;
13376     case ISD::SETULT:
13377       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13378     case ISD::SETULE:
13379       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13380     case ISD::SETUGT:
13381       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13382     case ISD::SETUGE:
13383       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13384     }
13385   }
13386 
13387   return SDValue();
13388 }
13389 
13390 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13391                                                   DAGCombinerInfo &DCI) const {
13392   SelectionDAG &DAG = DCI.DAG;
13393   SDLoc dl(N);
13394 
13395   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13396   // If we're tracking CR bits, we need to be careful that we don't have:
13397   //   trunc(binary-ops(zext(x), zext(y)))
13398   // or
13399   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13400   // such that we're unnecessarily moving things into GPRs when it would be
13401   // better to keep them in CR bits.
13402 
13403   // Note that trunc here can be an actual i1 trunc, or can be the effective
13404   // truncation that comes from a setcc or select_cc.
13405   if (N->getOpcode() == ISD::TRUNCATE &&
13406       N->getValueType(0) != MVT::i1)
13407     return SDValue();
13408 
13409   if (N->getOperand(0).getValueType() != MVT::i32 &&
13410       N->getOperand(0).getValueType() != MVT::i64)
13411     return SDValue();
13412 
13413   if (N->getOpcode() == ISD::SETCC ||
13414       N->getOpcode() == ISD::SELECT_CC) {
13415     // If we're looking at a comparison, then we need to make sure that the
13416     // high bits (all except for the first) don't matter the result.
13417     ISD::CondCode CC =
13418       cast<CondCodeSDNode>(N->getOperand(
13419         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13420     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13421 
13422     if (ISD::isSignedIntSetCC(CC)) {
13423       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13424           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13425         return SDValue();
13426     } else if (ISD::isUnsignedIntSetCC(CC)) {
13427       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13428                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13429           !DAG.MaskedValueIsZero(N->getOperand(1),
13430                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13431         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13432                                              : SDValue());
13433     } else {
13434       // This is neither a signed nor an unsigned comparison, just make sure
13435       // that the high bits are equal.
13436       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13437       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13438 
13439       // We don't really care about what is known about the first bit (if
13440       // anything), so pretend that it is known zero for both to ensure they can
13441       // be compared as constants.
13442       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13443       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13444 
13445       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13446           Op1Known.getConstant() != Op2Known.getConstant())
13447         return SDValue();
13448     }
13449   }
13450 
13451   // We now know that the higher-order bits are irrelevant, we just need to
13452   // make sure that all of the intermediate operations are bit operations, and
13453   // all inputs are extensions.
13454   if (N->getOperand(0).getOpcode() != ISD::AND &&
13455       N->getOperand(0).getOpcode() != ISD::OR  &&
13456       N->getOperand(0).getOpcode() != ISD::XOR &&
13457       N->getOperand(0).getOpcode() != ISD::SELECT &&
13458       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13459       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13460       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13461       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13462       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13463     return SDValue();
13464 
13465   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13466       N->getOperand(1).getOpcode() != ISD::AND &&
13467       N->getOperand(1).getOpcode() != ISD::OR  &&
13468       N->getOperand(1).getOpcode() != ISD::XOR &&
13469       N->getOperand(1).getOpcode() != ISD::SELECT &&
13470       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13471       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13472       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13473       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13474       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13475     return SDValue();
13476 
13477   SmallVector<SDValue, 4> Inputs;
13478   SmallVector<SDValue, 8> BinOps, PromOps;
13479   SmallPtrSet<SDNode *, 16> Visited;
13480 
13481   for (unsigned i = 0; i < 2; ++i) {
13482     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13483           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13484           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13485           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13486         isa<ConstantSDNode>(N->getOperand(i)))
13487       Inputs.push_back(N->getOperand(i));
13488     else
13489       BinOps.push_back(N->getOperand(i));
13490 
13491     if (N->getOpcode() == ISD::TRUNCATE)
13492       break;
13493   }
13494 
13495   // Visit all inputs, collect all binary operations (and, or, xor and
13496   // select) that are all fed by extensions.
13497   while (!BinOps.empty()) {
13498     SDValue BinOp = BinOps.pop_back_val();
13499 
13500     if (!Visited.insert(BinOp.getNode()).second)
13501       continue;
13502 
13503     PromOps.push_back(BinOp);
13504 
13505     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13506       // The condition of the select is not promoted.
13507       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13508         continue;
13509       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13510         continue;
13511 
13512       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13513             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13514             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13515            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13516           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13517         Inputs.push_back(BinOp.getOperand(i));
13518       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13519                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13520                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13521                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13522                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13523                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13524                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13525                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13526                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13527         BinOps.push_back(BinOp.getOperand(i));
13528       } else {
13529         // We have an input that is not an extension or another binary
13530         // operation; we'll abort this transformation.
13531         return SDValue();
13532       }
13533     }
13534   }
13535 
13536   // Make sure that this is a self-contained cluster of operations (which
13537   // is not quite the same thing as saying that everything has only one
13538   // use).
13539   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13540     if (isa<ConstantSDNode>(Inputs[i]))
13541       continue;
13542 
13543     for (const SDNode *User : Inputs[i].getNode()->uses()) {
13544       if (User != N && !Visited.count(User))
13545         return SDValue();
13546 
13547       // Make sure that we're not going to promote the non-output-value
13548       // operand(s) or SELECT or SELECT_CC.
13549       // FIXME: Although we could sometimes handle this, and it does occur in
13550       // practice that one of the condition inputs to the select is also one of
13551       // the outputs, we currently can't deal with this.
13552       if (User->getOpcode() == ISD::SELECT) {
13553         if (User->getOperand(0) == Inputs[i])
13554           return SDValue();
13555       } else if (User->getOpcode() == ISD::SELECT_CC) {
13556         if (User->getOperand(0) == Inputs[i] ||
13557             User->getOperand(1) == Inputs[i])
13558           return SDValue();
13559       }
13560     }
13561   }
13562 
13563   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13564     for (const SDNode *User : PromOps[i].getNode()->uses()) {
13565       if (User != N && !Visited.count(User))
13566         return SDValue();
13567 
13568       // Make sure that we're not going to promote the non-output-value
13569       // operand(s) or SELECT or SELECT_CC.
13570       // FIXME: Although we could sometimes handle this, and it does occur in
13571       // practice that one of the condition inputs to the select is also one of
13572       // the outputs, we currently can't deal with this.
13573       if (User->getOpcode() == ISD::SELECT) {
13574         if (User->getOperand(0) == PromOps[i])
13575           return SDValue();
13576       } else if (User->getOpcode() == ISD::SELECT_CC) {
13577         if (User->getOperand(0) == PromOps[i] ||
13578             User->getOperand(1) == PromOps[i])
13579           return SDValue();
13580       }
13581     }
13582   }
13583 
13584   // Replace all inputs with the extension operand.
13585   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13586     // Constants may have users outside the cluster of to-be-promoted nodes,
13587     // and so we need to replace those as we do the promotions.
13588     if (isa<ConstantSDNode>(Inputs[i]))
13589       continue;
13590     else
13591       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13592   }
13593 
13594   std::list<HandleSDNode> PromOpHandles;
13595   for (auto &PromOp : PromOps)
13596     PromOpHandles.emplace_back(PromOp);
13597 
13598   // Replace all operations (these are all the same, but have a different
13599   // (i1) return type). DAG.getNode will validate that the types of
13600   // a binary operator match, so go through the list in reverse so that
13601   // we've likely promoted both operands first. Any intermediate truncations or
13602   // extensions disappear.
13603   while (!PromOpHandles.empty()) {
13604     SDValue PromOp = PromOpHandles.back().getValue();
13605     PromOpHandles.pop_back();
13606 
13607     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13608         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13609         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13610         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13611       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13612           PromOp.getOperand(0).getValueType() != MVT::i1) {
13613         // The operand is not yet ready (see comment below).
13614         PromOpHandles.emplace_front(PromOp);
13615         continue;
13616       }
13617 
13618       SDValue RepValue = PromOp.getOperand(0);
13619       if (isa<ConstantSDNode>(RepValue))
13620         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13621 
13622       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13623       continue;
13624     }
13625 
13626     unsigned C;
13627     switch (PromOp.getOpcode()) {
13628     default:             C = 0; break;
13629     case ISD::SELECT:    C = 1; break;
13630     case ISD::SELECT_CC: C = 2; break;
13631     }
13632 
13633     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13634          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13635         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13636          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13637       // The to-be-promoted operands of this node have not yet been
13638       // promoted (this should be rare because we're going through the
13639       // list backward, but if one of the operands has several users in
13640       // this cluster of to-be-promoted nodes, it is possible).
13641       PromOpHandles.emplace_front(PromOp);
13642       continue;
13643     }
13644 
13645     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13646                                 PromOp.getNode()->op_end());
13647 
13648     // If there are any constant inputs, make sure they're replaced now.
13649     for (unsigned i = 0; i < 2; ++i)
13650       if (isa<ConstantSDNode>(Ops[C+i]))
13651         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13652 
13653     DAG.ReplaceAllUsesOfValueWith(PromOp,
13654       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13655   }
13656 
13657   // Now we're left with the initial truncation itself.
13658   if (N->getOpcode() == ISD::TRUNCATE)
13659     return N->getOperand(0);
13660 
13661   // Otherwise, this is a comparison. The operands to be compared have just
13662   // changed type (to i1), but everything else is the same.
13663   return SDValue(N, 0);
13664 }
13665 
13666 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13667                                                   DAGCombinerInfo &DCI) const {
13668   SelectionDAG &DAG = DCI.DAG;
13669   SDLoc dl(N);
13670 
13671   // If we're tracking CR bits, we need to be careful that we don't have:
13672   //   zext(binary-ops(trunc(x), trunc(y)))
13673   // or
13674   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13675   // such that we're unnecessarily moving things into CR bits that can more
13676   // efficiently stay in GPRs. Note that if we're not certain that the high
13677   // bits are set as required by the final extension, we still may need to do
13678   // some masking to get the proper behavior.
13679 
13680   // This same functionality is important on PPC64 when dealing with
13681   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13682   // the return values of functions. Because it is so similar, it is handled
13683   // here as well.
13684 
13685   if (N->getValueType(0) != MVT::i32 &&
13686       N->getValueType(0) != MVT::i64)
13687     return SDValue();
13688 
13689   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13690         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13691     return SDValue();
13692 
13693   if (N->getOperand(0).getOpcode() != ISD::AND &&
13694       N->getOperand(0).getOpcode() != ISD::OR  &&
13695       N->getOperand(0).getOpcode() != ISD::XOR &&
13696       N->getOperand(0).getOpcode() != ISD::SELECT &&
13697       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13698     return SDValue();
13699 
13700   SmallVector<SDValue, 4> Inputs;
13701   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13702   SmallPtrSet<SDNode *, 16> Visited;
13703 
13704   // Visit all inputs, collect all binary operations (and, or, xor and
13705   // select) that are all fed by truncations.
13706   while (!BinOps.empty()) {
13707     SDValue BinOp = BinOps.pop_back_val();
13708 
13709     if (!Visited.insert(BinOp.getNode()).second)
13710       continue;
13711 
13712     PromOps.push_back(BinOp);
13713 
13714     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13715       // The condition of the select is not promoted.
13716       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13717         continue;
13718       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13719         continue;
13720 
13721       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13722           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13723         Inputs.push_back(BinOp.getOperand(i));
13724       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13725                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13726                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13727                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13728                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13729         BinOps.push_back(BinOp.getOperand(i));
13730       } else {
13731         // We have an input that is not a truncation or another binary
13732         // operation; we'll abort this transformation.
13733         return SDValue();
13734       }
13735     }
13736   }
13737 
13738   // The operands of a select that must be truncated when the select is
13739   // promoted because the operand is actually part of the to-be-promoted set.
13740   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13741 
13742   // Make sure that this is a self-contained cluster of operations (which
13743   // is not quite the same thing as saying that everything has only one
13744   // use).
13745   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13746     if (isa<ConstantSDNode>(Inputs[i]))
13747       continue;
13748 
13749     for (SDNode *User : Inputs[i].getNode()->uses()) {
13750       if (User != N && !Visited.count(User))
13751         return SDValue();
13752 
13753       // If we're going to promote the non-output-value operand(s) or SELECT or
13754       // SELECT_CC, record them for truncation.
13755       if (User->getOpcode() == ISD::SELECT) {
13756         if (User->getOperand(0) == Inputs[i])
13757           SelectTruncOp[0].insert(std::make_pair(User,
13758                                     User->getOperand(0).getValueType()));
13759       } else if (User->getOpcode() == ISD::SELECT_CC) {
13760         if (User->getOperand(0) == Inputs[i])
13761           SelectTruncOp[0].insert(std::make_pair(User,
13762                                     User->getOperand(0).getValueType()));
13763         if (User->getOperand(1) == Inputs[i])
13764           SelectTruncOp[1].insert(std::make_pair(User,
13765                                     User->getOperand(1).getValueType()));
13766       }
13767     }
13768   }
13769 
13770   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13771     for (SDNode *User : PromOps[i].getNode()->uses()) {
13772       if (User != N && !Visited.count(User))
13773         return SDValue();
13774 
13775       // If we're going to promote the non-output-value operand(s) or SELECT or
13776       // SELECT_CC, record them for truncation.
13777       if (User->getOpcode() == ISD::SELECT) {
13778         if (User->getOperand(0) == PromOps[i])
13779           SelectTruncOp[0].insert(std::make_pair(User,
13780                                     User->getOperand(0).getValueType()));
13781       } else if (User->getOpcode() == ISD::SELECT_CC) {
13782         if (User->getOperand(0) == PromOps[i])
13783           SelectTruncOp[0].insert(std::make_pair(User,
13784                                     User->getOperand(0).getValueType()));
13785         if (User->getOperand(1) == PromOps[i])
13786           SelectTruncOp[1].insert(std::make_pair(User,
13787                                     User->getOperand(1).getValueType()));
13788       }
13789     }
13790   }
13791 
13792   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13793   bool ReallyNeedsExt = false;
13794   if (N->getOpcode() != ISD::ANY_EXTEND) {
13795     // If all of the inputs are not already sign/zero extended, then
13796     // we'll still need to do that at the end.
13797     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13798       if (isa<ConstantSDNode>(Inputs[i]))
13799         continue;
13800 
13801       unsigned OpBits =
13802         Inputs[i].getOperand(0).getValueSizeInBits();
13803       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13804 
13805       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13806            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13807                                   APInt::getHighBitsSet(OpBits,
13808                                                         OpBits-PromBits))) ||
13809           (N->getOpcode() == ISD::SIGN_EXTEND &&
13810            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13811              (OpBits-(PromBits-1)))) {
13812         ReallyNeedsExt = true;
13813         break;
13814       }
13815     }
13816   }
13817 
13818   // Replace all inputs, either with the truncation operand, or a
13819   // truncation or extension to the final output type.
13820   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13821     // Constant inputs need to be replaced with the to-be-promoted nodes that
13822     // use them because they might have users outside of the cluster of
13823     // promoted nodes.
13824     if (isa<ConstantSDNode>(Inputs[i]))
13825       continue;
13826 
13827     SDValue InSrc = Inputs[i].getOperand(0);
13828     if (Inputs[i].getValueType() == N->getValueType(0))
13829       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13830     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13831       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13832         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13833     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13834       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13835         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13836     else
13837       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13838         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13839   }
13840 
13841   std::list<HandleSDNode> PromOpHandles;
13842   for (auto &PromOp : PromOps)
13843     PromOpHandles.emplace_back(PromOp);
13844 
13845   // Replace all operations (these are all the same, but have a different
13846   // (promoted) return type). DAG.getNode will validate that the types of
13847   // a binary operator match, so go through the list in reverse so that
13848   // we've likely promoted both operands first.
13849   while (!PromOpHandles.empty()) {
13850     SDValue PromOp = PromOpHandles.back().getValue();
13851     PromOpHandles.pop_back();
13852 
13853     unsigned C;
13854     switch (PromOp.getOpcode()) {
13855     default:             C = 0; break;
13856     case ISD::SELECT:    C = 1; break;
13857     case ISD::SELECT_CC: C = 2; break;
13858     }
13859 
13860     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13861          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13862         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13863          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13864       // The to-be-promoted operands of this node have not yet been
13865       // promoted (this should be rare because we're going through the
13866       // list backward, but if one of the operands has several users in
13867       // this cluster of to-be-promoted nodes, it is possible).
13868       PromOpHandles.emplace_front(PromOp);
13869       continue;
13870     }
13871 
13872     // For SELECT and SELECT_CC nodes, we do a similar check for any
13873     // to-be-promoted comparison inputs.
13874     if (PromOp.getOpcode() == ISD::SELECT ||
13875         PromOp.getOpcode() == ISD::SELECT_CC) {
13876       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13877            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13878           (SelectTruncOp[1].count(PromOp.getNode()) &&
13879            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13880         PromOpHandles.emplace_front(PromOp);
13881         continue;
13882       }
13883     }
13884 
13885     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13886                                 PromOp.getNode()->op_end());
13887 
13888     // If this node has constant inputs, then they'll need to be promoted here.
13889     for (unsigned i = 0; i < 2; ++i) {
13890       if (!isa<ConstantSDNode>(Ops[C+i]))
13891         continue;
13892       if (Ops[C+i].getValueType() == N->getValueType(0))
13893         continue;
13894 
13895       if (N->getOpcode() == ISD::SIGN_EXTEND)
13896         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13897       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13898         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13899       else
13900         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13901     }
13902 
13903     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13904     // truncate them again to the original value type.
13905     if (PromOp.getOpcode() == ISD::SELECT ||
13906         PromOp.getOpcode() == ISD::SELECT_CC) {
13907       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13908       if (SI0 != SelectTruncOp[0].end())
13909         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13910       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13911       if (SI1 != SelectTruncOp[1].end())
13912         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13913     }
13914 
13915     DAG.ReplaceAllUsesOfValueWith(PromOp,
13916       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13917   }
13918 
13919   // Now we're left with the initial extension itself.
13920   if (!ReallyNeedsExt)
13921     return N->getOperand(0);
13922 
13923   // To zero extend, just mask off everything except for the first bit (in the
13924   // i1 case).
13925   if (N->getOpcode() == ISD::ZERO_EXTEND)
13926     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13927                        DAG.getConstant(APInt::getLowBitsSet(
13928                                          N->getValueSizeInBits(0), PromBits),
13929                                        dl, N->getValueType(0)));
13930 
13931   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13932          "Invalid extension type");
13933   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13934   SDValue ShiftCst =
13935       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13936   return DAG.getNode(
13937       ISD::SRA, dl, N->getValueType(0),
13938       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13939       ShiftCst);
13940 }
13941 
13942 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13943                                         DAGCombinerInfo &DCI) const {
13944   assert(N->getOpcode() == ISD::SETCC &&
13945          "Should be called with a SETCC node");
13946 
13947   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13948   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13949     SDValue LHS = N->getOperand(0);
13950     SDValue RHS = N->getOperand(1);
13951 
13952     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13953     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13954         LHS.hasOneUse())
13955       std::swap(LHS, RHS);
13956 
13957     // x == 0-y --> x+y == 0
13958     // x != 0-y --> x+y != 0
13959     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13960         RHS.hasOneUse()) {
13961       SDLoc DL(N);
13962       SelectionDAG &DAG = DCI.DAG;
13963       EVT VT = N->getValueType(0);
13964       EVT OpVT = LHS.getValueType();
13965       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13966       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13967     }
13968   }
13969 
13970   return DAGCombineTruncBoolExt(N, DCI);
13971 }
13972 
13973 // Is this an extending load from an f32 to an f64?
13974 static bool isFPExtLoad(SDValue Op) {
13975   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13976     return LD->getExtensionType() == ISD::EXTLOAD &&
13977       Op.getValueType() == MVT::f64;
13978   return false;
13979 }
13980 
13981 /// Reduces the number of fp-to-int conversion when building a vector.
13982 ///
13983 /// If this vector is built out of floating to integer conversions,
13984 /// transform it to a vector built out of floating point values followed by a
13985 /// single floating to integer conversion of the vector.
13986 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13987 /// becomes (fptosi (build_vector ($A, $B, ...)))
13988 SDValue PPCTargetLowering::
13989 combineElementTruncationToVectorTruncation(SDNode *N,
13990                                            DAGCombinerInfo &DCI) const {
13991   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13992          "Should be called with a BUILD_VECTOR node");
13993 
13994   SelectionDAG &DAG = DCI.DAG;
13995   SDLoc dl(N);
13996 
13997   SDValue FirstInput = N->getOperand(0);
13998   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13999          "The input operand must be an fp-to-int conversion.");
14000 
14001   // This combine happens after legalization so the fp_to_[su]i nodes are
14002   // already converted to PPCSISD nodes.
14003   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
14004   if (FirstConversion == PPCISD::FCTIDZ ||
14005       FirstConversion == PPCISD::FCTIDUZ ||
14006       FirstConversion == PPCISD::FCTIWZ ||
14007       FirstConversion == PPCISD::FCTIWUZ) {
14008     bool IsSplat = true;
14009     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
14010       FirstConversion == PPCISD::FCTIWUZ;
14011     EVT SrcVT = FirstInput.getOperand(0).getValueType();
14012     SmallVector<SDValue, 4> Ops;
14013     EVT TargetVT = N->getValueType(0);
14014     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14015       SDValue NextOp = N->getOperand(i);
14016       if (NextOp.getOpcode() != PPCISD::MFVSR)
14017         return SDValue();
14018       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
14019       if (NextConversion != FirstConversion)
14020         return SDValue();
14021       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
14022       // This is not valid if the input was originally double precision. It is
14023       // also not profitable to do unless this is an extending load in which
14024       // case doing this combine will allow us to combine consecutive loads.
14025       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
14026         return SDValue();
14027       if (N->getOperand(i) != FirstInput)
14028         IsSplat = false;
14029     }
14030 
14031     // If this is a splat, we leave it as-is since there will be only a single
14032     // fp-to-int conversion followed by a splat of the integer. This is better
14033     // for 32-bit and smaller ints and neutral for 64-bit ints.
14034     if (IsSplat)
14035       return SDValue();
14036 
14037     // Now that we know we have the right type of node, get its operands
14038     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14039       SDValue In = N->getOperand(i).getOperand(0);
14040       if (Is32Bit) {
14041         // For 32-bit values, we need to add an FP_ROUND node (if we made it
14042         // here, we know that all inputs are extending loads so this is safe).
14043         if (In.isUndef())
14044           Ops.push_back(DAG.getUNDEF(SrcVT));
14045         else {
14046           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
14047                                       MVT::f32, In.getOperand(0),
14048                                       DAG.getIntPtrConstant(1, dl));
14049           Ops.push_back(Trunc);
14050         }
14051       } else
14052         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
14053     }
14054 
14055     unsigned Opcode;
14056     if (FirstConversion == PPCISD::FCTIDZ ||
14057         FirstConversion == PPCISD::FCTIWZ)
14058       Opcode = ISD::FP_TO_SINT;
14059     else
14060       Opcode = ISD::FP_TO_UINT;
14061 
14062     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
14063     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
14064     return DAG.getNode(Opcode, dl, TargetVT, BV);
14065   }
14066   return SDValue();
14067 }
14068 
14069 /// Reduce the number of loads when building a vector.
14070 ///
14071 /// Building a vector out of multiple loads can be converted to a load
14072 /// of the vector type if the loads are consecutive. If the loads are
14073 /// consecutive but in descending order, a shuffle is added at the end
14074 /// to reorder the vector.
14075 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
14076   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14077          "Should be called with a BUILD_VECTOR node");
14078 
14079   SDLoc dl(N);
14080 
14081   // Return early for non byte-sized type, as they can't be consecutive.
14082   if (!N->getValueType(0).getVectorElementType().isByteSized())
14083     return SDValue();
14084 
14085   bool InputsAreConsecutiveLoads = true;
14086   bool InputsAreReverseConsecutive = true;
14087   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14088   SDValue FirstInput = N->getOperand(0);
14089   bool IsRoundOfExtLoad = false;
14090 
14091   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14092       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14093     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
14094     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
14095   }
14096   // Not a build vector of (possibly fp_rounded) loads.
14097   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14098       N->getNumOperands() == 1)
14099     return SDValue();
14100 
14101   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14102     // If any inputs are fp_round(extload), they all must be.
14103     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14104       return SDValue();
14105 
14106     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14107       N->getOperand(i);
14108     if (NextInput.getOpcode() != ISD::LOAD)
14109       return SDValue();
14110 
14111     SDValue PreviousInput =
14112       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14113     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
14114     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
14115 
14116     // If any inputs are fp_round(extload), they all must be.
14117     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14118       return SDValue();
14119 
14120     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
14121       InputsAreConsecutiveLoads = false;
14122     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14123       InputsAreReverseConsecutive = false;
14124 
14125     // Exit early if the loads are neither consecutive nor reverse consecutive.
14126     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14127       return SDValue();
14128   }
14129 
14130   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14131          "The loads cannot be both consecutive and reverse consecutive.");
14132 
14133   SDValue FirstLoadOp =
14134     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14135   SDValue LastLoadOp =
14136     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14137                        N->getOperand(N->getNumOperands()-1);
14138 
14139   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14140   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14141   if (InputsAreConsecutiveLoads) {
14142     assert(LD1 && "Input needs to be a LoadSDNode.");
14143     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14144                        LD1->getBasePtr(), LD1->getPointerInfo(),
14145                        LD1->getAlignment());
14146   }
14147   if (InputsAreReverseConsecutive) {
14148     assert(LDL && "Input needs to be a LoadSDNode.");
14149     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14150                                LDL->getBasePtr(), LDL->getPointerInfo(),
14151                                LDL->getAlignment());
14152     SmallVector<int, 16> Ops;
14153     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14154       Ops.push_back(i);
14155 
14156     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14157                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14158   }
14159   return SDValue();
14160 }
14161 
14162 // This function adds the required vector_shuffle needed to get
14163 // the elements of the vector extract in the correct position
14164 // as specified by the CorrectElems encoding.
14165 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14166                                       SDValue Input, uint64_t Elems,
14167                                       uint64_t CorrectElems) {
14168   SDLoc dl(N);
14169 
14170   unsigned NumElems = Input.getValueType().getVectorNumElements();
14171   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14172 
14173   // Knowing the element indices being extracted from the original
14174   // vector and the order in which they're being inserted, just put
14175   // them at element indices required for the instruction.
14176   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14177     if (DAG.getDataLayout().isLittleEndian())
14178       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14179     else
14180       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14181     CorrectElems = CorrectElems >> 8;
14182     Elems = Elems >> 8;
14183   }
14184 
14185   SDValue Shuffle =
14186       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14187                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14188 
14189   EVT VT = N->getValueType(0);
14190   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14191 
14192   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14193                                Input.getValueType().getVectorElementType(),
14194                                VT.getVectorNumElements());
14195   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14196                      DAG.getValueType(ExtVT));
14197 }
14198 
14199 // Look for build vector patterns where input operands come from sign
14200 // extended vector_extract elements of specific indices. If the correct indices
14201 // aren't used, add a vector shuffle to fix up the indices and create
14202 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14203 // during instruction selection.
14204 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14205   // This array encodes the indices that the vector sign extend instructions
14206   // extract from when extending from one type to another for both BE and LE.
14207   // The right nibble of each byte corresponds to the LE incides.
14208   // and the left nibble of each byte corresponds to the BE incides.
14209   // For example: 0x3074B8FC  byte->word
14210   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14211   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14212   // For example: 0x000070F8  byte->double word
14213   // For LE: the allowed indices are: 0x0,0x8
14214   // For BE: the allowed indices are: 0x7,0xF
14215   uint64_t TargetElems[] = {
14216       0x3074B8FC, // b->w
14217       0x000070F8, // b->d
14218       0x10325476, // h->w
14219       0x00003074, // h->d
14220       0x00001032, // w->d
14221   };
14222 
14223   uint64_t Elems = 0;
14224   int Index;
14225   SDValue Input;
14226 
14227   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14228     if (!Op)
14229       return false;
14230     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14231         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14232       return false;
14233 
14234     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14235     // of the right width.
14236     SDValue Extract = Op.getOperand(0);
14237     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14238       Extract = Extract.getOperand(0);
14239     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14240       return false;
14241 
14242     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14243     if (!ExtOp)
14244       return false;
14245 
14246     Index = ExtOp->getZExtValue();
14247     if (Input && Input != Extract.getOperand(0))
14248       return false;
14249 
14250     if (!Input)
14251       Input = Extract.getOperand(0);
14252 
14253     Elems = Elems << 8;
14254     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14255     Elems |= Index;
14256 
14257     return true;
14258   };
14259 
14260   // If the build vector operands aren't sign extended vector extracts,
14261   // of the same input vector, then return.
14262   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14263     if (!isSExtOfVecExtract(N->getOperand(i))) {
14264       return SDValue();
14265     }
14266   }
14267 
14268   // If the vector extract indicies are not correct, add the appropriate
14269   // vector_shuffle.
14270   int TgtElemArrayIdx;
14271   int InputSize = Input.getValueType().getScalarSizeInBits();
14272   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14273   if (InputSize + OutputSize == 40)
14274     TgtElemArrayIdx = 0;
14275   else if (InputSize + OutputSize == 72)
14276     TgtElemArrayIdx = 1;
14277   else if (InputSize + OutputSize == 48)
14278     TgtElemArrayIdx = 2;
14279   else if (InputSize + OutputSize == 80)
14280     TgtElemArrayIdx = 3;
14281   else if (InputSize + OutputSize == 96)
14282     TgtElemArrayIdx = 4;
14283   else
14284     return SDValue();
14285 
14286   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14287   CorrectElems = DAG.getDataLayout().isLittleEndian()
14288                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14289                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14290   if (Elems != CorrectElems) {
14291     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14292   }
14293 
14294   // Regular lowering will catch cases where a shuffle is not needed.
14295   return SDValue();
14296 }
14297 
14298 // Look for the pattern of a load from a narrow width to i128, feeding
14299 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14300 // (LXVRZX). This node represents a zero extending load that will be matched
14301 // to the Load VSX Vector Rightmost instructions.
14302 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14303   SDLoc DL(N);
14304 
14305   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14306   if (N->getValueType(0) != MVT::v1i128)
14307     return SDValue();
14308 
14309   SDValue Operand = N->getOperand(0);
14310   // Proceed with the transformation if the operand to the BUILD_VECTOR
14311   // is a load instruction.
14312   if (Operand.getOpcode() != ISD::LOAD)
14313     return SDValue();
14314 
14315   auto *LD = cast<LoadSDNode>(Operand);
14316   EVT MemoryType = LD->getMemoryVT();
14317 
14318   // This transformation is only valid if the we are loading either a byte,
14319   // halfword, word, or doubleword.
14320   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14321                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14322 
14323   // Ensure that the load from the narrow width is being zero extended to i128.
14324   if (!ValidLDType ||
14325       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14326        LD->getExtensionType() != ISD::EXTLOAD))
14327     return SDValue();
14328 
14329   SDValue LoadOps[] = {
14330       LD->getChain(), LD->getBasePtr(),
14331       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14332 
14333   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14334                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14335                                  LoadOps, MemoryType, LD->getMemOperand());
14336 }
14337 
14338 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14339                                                  DAGCombinerInfo &DCI) const {
14340   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14341          "Should be called with a BUILD_VECTOR node");
14342 
14343   SelectionDAG &DAG = DCI.DAG;
14344   SDLoc dl(N);
14345 
14346   if (!Subtarget.hasVSX())
14347     return SDValue();
14348 
14349   // The target independent DAG combiner will leave a build_vector of
14350   // float-to-int conversions intact. We can generate MUCH better code for
14351   // a float-to-int conversion of a vector of floats.
14352   SDValue FirstInput = N->getOperand(0);
14353   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14354     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14355     if (Reduced)
14356       return Reduced;
14357   }
14358 
14359   // If we're building a vector out of consecutive loads, just load that
14360   // vector type.
14361   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14362   if (Reduced)
14363     return Reduced;
14364 
14365   // If we're building a vector out of extended elements from another vector
14366   // we have P9 vector integer extend instructions. The code assumes legal
14367   // input types (i.e. it can't handle things like v4i16) so do not run before
14368   // legalization.
14369   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14370     Reduced = combineBVOfVecSExt(N, DAG);
14371     if (Reduced)
14372       return Reduced;
14373   }
14374 
14375   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14376   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14377   // is a load from <valid narrow width> to i128.
14378   if (Subtarget.isISA3_1()) {
14379     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14380     if (BVOfZLoad)
14381       return BVOfZLoad;
14382   }
14383 
14384   if (N->getValueType(0) != MVT::v2f64)
14385     return SDValue();
14386 
14387   // Looking for:
14388   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14389   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14390       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14391     return SDValue();
14392   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14393       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14394     return SDValue();
14395   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14396     return SDValue();
14397 
14398   SDValue Ext1 = FirstInput.getOperand(0);
14399   SDValue Ext2 = N->getOperand(1).getOperand(0);
14400   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14401      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14402     return SDValue();
14403 
14404   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14405   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14406   if (!Ext1Op || !Ext2Op)
14407     return SDValue();
14408   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14409       Ext1.getOperand(0) != Ext2.getOperand(0))
14410     return SDValue();
14411 
14412   int FirstElem = Ext1Op->getZExtValue();
14413   int SecondElem = Ext2Op->getZExtValue();
14414   int SubvecIdx;
14415   if (FirstElem == 0 && SecondElem == 1)
14416     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14417   else if (FirstElem == 2 && SecondElem == 3)
14418     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14419   else
14420     return SDValue();
14421 
14422   SDValue SrcVec = Ext1.getOperand(0);
14423   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14424     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14425   return DAG.getNode(NodeType, dl, MVT::v2f64,
14426                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14427 }
14428 
14429 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14430                                               DAGCombinerInfo &DCI) const {
14431   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14432           N->getOpcode() == ISD::UINT_TO_FP) &&
14433          "Need an int -> FP conversion node here");
14434 
14435   if (useSoftFloat() || !Subtarget.has64BitSupport())
14436     return SDValue();
14437 
14438   SelectionDAG &DAG = DCI.DAG;
14439   SDLoc dl(N);
14440   SDValue Op(N, 0);
14441 
14442   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14443   // from the hardware.
14444   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14445     return SDValue();
14446   if (!Op.getOperand(0).getValueType().isSimple())
14447     return SDValue();
14448   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14449       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14450     return SDValue();
14451 
14452   SDValue FirstOperand(Op.getOperand(0));
14453   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14454     (FirstOperand.getValueType() == MVT::i8 ||
14455      FirstOperand.getValueType() == MVT::i16);
14456   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14457     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14458     bool DstDouble = Op.getValueType() == MVT::f64;
14459     unsigned ConvOp = Signed ?
14460       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14461       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14462     SDValue WidthConst =
14463       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14464                             dl, false);
14465     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14466     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14467     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14468                                          DAG.getVTList(MVT::f64, MVT::Other),
14469                                          Ops, MVT::i8, LDN->getMemOperand());
14470 
14471     // For signed conversion, we need to sign-extend the value in the VSR
14472     if (Signed) {
14473       SDValue ExtOps[] = { Ld, WidthConst };
14474       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14475       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14476     } else
14477       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14478   }
14479 
14480 
14481   // For i32 intermediate values, unfortunately, the conversion functions
14482   // leave the upper 32 bits of the value are undefined. Within the set of
14483   // scalar instructions, we have no method for zero- or sign-extending the
14484   // value. Thus, we cannot handle i32 intermediate values here.
14485   if (Op.getOperand(0).getValueType() == MVT::i32)
14486     return SDValue();
14487 
14488   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14489          "UINT_TO_FP is supported only with FPCVT");
14490 
14491   // If we have FCFIDS, then use it when converting to single-precision.
14492   // Otherwise, convert to double-precision and then round.
14493   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14494                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14495                                                             : PPCISD::FCFIDS)
14496                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14497                                                             : PPCISD::FCFID);
14498   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14499                   ? MVT::f32
14500                   : MVT::f64;
14501 
14502   // If we're converting from a float, to an int, and back to a float again,
14503   // then we don't need the store/load pair at all.
14504   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14505        Subtarget.hasFPCVT()) ||
14506       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14507     SDValue Src = Op.getOperand(0).getOperand(0);
14508     if (Src.getValueType() == MVT::f32) {
14509       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14510       DCI.AddToWorklist(Src.getNode());
14511     } else if (Src.getValueType() != MVT::f64) {
14512       // Make sure that we don't pick up a ppc_fp128 source value.
14513       return SDValue();
14514     }
14515 
14516     unsigned FCTOp =
14517       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14518                                                         PPCISD::FCTIDUZ;
14519 
14520     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14521     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14522 
14523     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14524       FP = DAG.getNode(ISD::FP_ROUND, dl,
14525                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14526       DCI.AddToWorklist(FP.getNode());
14527     }
14528 
14529     return FP;
14530   }
14531 
14532   return SDValue();
14533 }
14534 
14535 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14536 // builtins) into loads with swaps.
14537 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14538                                               DAGCombinerInfo &DCI) const {
14539   SelectionDAG &DAG = DCI.DAG;
14540   SDLoc dl(N);
14541   SDValue Chain;
14542   SDValue Base;
14543   MachineMemOperand *MMO;
14544 
14545   switch (N->getOpcode()) {
14546   default:
14547     llvm_unreachable("Unexpected opcode for little endian VSX load");
14548   case ISD::LOAD: {
14549     LoadSDNode *LD = cast<LoadSDNode>(N);
14550     Chain = LD->getChain();
14551     Base = LD->getBasePtr();
14552     MMO = LD->getMemOperand();
14553     // If the MMO suggests this isn't a load of a full vector, leave
14554     // things alone.  For a built-in, we have to make the change for
14555     // correctness, so if there is a size problem that will be a bug.
14556     if (MMO->getSize() < 16)
14557       return SDValue();
14558     break;
14559   }
14560   case ISD::INTRINSIC_W_CHAIN: {
14561     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14562     Chain = Intrin->getChain();
14563     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14564     // us what we want. Get operand 2 instead.
14565     Base = Intrin->getOperand(2);
14566     MMO = Intrin->getMemOperand();
14567     break;
14568   }
14569   }
14570 
14571   MVT VecTy = N->getValueType(0).getSimpleVT();
14572 
14573   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14574   // aligned and the type is a vector with elements up to 4 bytes
14575   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14576       VecTy.getScalarSizeInBits() <= 32) {
14577     return SDValue();
14578   }
14579 
14580   SDValue LoadOps[] = { Chain, Base };
14581   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14582                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14583                                          LoadOps, MVT::v2f64, MMO);
14584 
14585   DCI.AddToWorklist(Load.getNode());
14586   Chain = Load.getValue(1);
14587   SDValue Swap = DAG.getNode(
14588       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14589   DCI.AddToWorklist(Swap.getNode());
14590 
14591   // Add a bitcast if the resulting load type doesn't match v2f64.
14592   if (VecTy != MVT::v2f64) {
14593     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14594     DCI.AddToWorklist(N.getNode());
14595     // Package {bitcast value, swap's chain} to match Load's shape.
14596     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14597                        N, Swap.getValue(1));
14598   }
14599 
14600   return Swap;
14601 }
14602 
14603 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14604 // builtins) into stores with swaps.
14605 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14606                                                DAGCombinerInfo &DCI) const {
14607   SelectionDAG &DAG = DCI.DAG;
14608   SDLoc dl(N);
14609   SDValue Chain;
14610   SDValue Base;
14611   unsigned SrcOpnd;
14612   MachineMemOperand *MMO;
14613 
14614   switch (N->getOpcode()) {
14615   default:
14616     llvm_unreachable("Unexpected opcode for little endian VSX store");
14617   case ISD::STORE: {
14618     StoreSDNode *ST = cast<StoreSDNode>(N);
14619     Chain = ST->getChain();
14620     Base = ST->getBasePtr();
14621     MMO = ST->getMemOperand();
14622     SrcOpnd = 1;
14623     // If the MMO suggests this isn't a store of a full vector, leave
14624     // things alone.  For a built-in, we have to make the change for
14625     // correctness, so if there is a size problem that will be a bug.
14626     if (MMO->getSize() < 16)
14627       return SDValue();
14628     break;
14629   }
14630   case ISD::INTRINSIC_VOID: {
14631     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14632     Chain = Intrin->getChain();
14633     // Intrin->getBasePtr() oddly does not get what we want.
14634     Base = Intrin->getOperand(3);
14635     MMO = Intrin->getMemOperand();
14636     SrcOpnd = 2;
14637     break;
14638   }
14639   }
14640 
14641   SDValue Src = N->getOperand(SrcOpnd);
14642   MVT VecTy = Src.getValueType().getSimpleVT();
14643 
14644   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14645   // aligned and the type is a vector with elements up to 4 bytes
14646   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14647       VecTy.getScalarSizeInBits() <= 32) {
14648     return SDValue();
14649   }
14650 
14651   // All stores are done as v2f64 and possible bit cast.
14652   if (VecTy != MVT::v2f64) {
14653     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14654     DCI.AddToWorklist(Src.getNode());
14655   }
14656 
14657   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14658                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14659   DCI.AddToWorklist(Swap.getNode());
14660   Chain = Swap.getValue(1);
14661   SDValue StoreOps[] = { Chain, Swap, Base };
14662   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14663                                           DAG.getVTList(MVT::Other),
14664                                           StoreOps, VecTy, MMO);
14665   DCI.AddToWorklist(Store.getNode());
14666   return Store;
14667 }
14668 
14669 // Handle DAG combine for STORE (FP_TO_INT F).
14670 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14671                                                DAGCombinerInfo &DCI) const {
14672 
14673   SelectionDAG &DAG = DCI.DAG;
14674   SDLoc dl(N);
14675   unsigned Opcode = N->getOperand(1).getOpcode();
14676 
14677   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14678          && "Not a FP_TO_INT Instruction!");
14679 
14680   SDValue Val = N->getOperand(1).getOperand(0);
14681   EVT Op1VT = N->getOperand(1).getValueType();
14682   EVT ResVT = Val.getValueType();
14683 
14684   if (!isTypeLegal(ResVT))
14685     return SDValue();
14686 
14687   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14688   bool ValidTypeForStoreFltAsInt =
14689         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14690          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14691 
14692   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14693     return SDValue();
14694 
14695   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14696       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14697     return SDValue();
14698 
14699   // Extend f32 values to f64
14700   if (ResVT.getScalarSizeInBits() == 32) {
14701     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14702     DCI.AddToWorklist(Val.getNode());
14703   }
14704 
14705   // Set signed or unsigned conversion opcode.
14706   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14707                           PPCISD::FP_TO_SINT_IN_VSR :
14708                           PPCISD::FP_TO_UINT_IN_VSR;
14709 
14710   Val = DAG.getNode(ConvOpcode,
14711                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14712   DCI.AddToWorklist(Val.getNode());
14713 
14714   // Set number of bytes being converted.
14715   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14716   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14717                     DAG.getIntPtrConstant(ByteSize, dl, false),
14718                     DAG.getValueType(Op1VT) };
14719 
14720   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14721           DAG.getVTList(MVT::Other), Ops,
14722           cast<StoreSDNode>(N)->getMemoryVT(),
14723           cast<StoreSDNode>(N)->getMemOperand());
14724 
14725   DCI.AddToWorklist(Val.getNode());
14726   return Val;
14727 }
14728 
14729 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14730   // Check that the source of the element keeps flipping
14731   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14732   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14733   for (int i = 1, e = Mask.size(); i < e; i++) {
14734     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14735       return false;
14736     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14737       return false;
14738     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14739   }
14740   return true;
14741 }
14742 
14743 static bool isSplatBV(SDValue Op) {
14744   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14745     return false;
14746   SDValue FirstOp;
14747 
14748   // Find first non-undef input.
14749   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14750     FirstOp = Op.getOperand(i);
14751     if (!FirstOp.isUndef())
14752       break;
14753   }
14754 
14755   // All inputs are undef or the same as the first non-undef input.
14756   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14757     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14758       return false;
14759   return true;
14760 }
14761 
14762 static SDValue isScalarToVec(SDValue Op) {
14763   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14764     return Op;
14765   if (Op.getOpcode() != ISD::BITCAST)
14766     return SDValue();
14767   Op = Op.getOperand(0);
14768   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14769     return Op;
14770   return SDValue();
14771 }
14772 
14773 // Fix up the shuffle mask to account for the fact that the result of
14774 // scalar_to_vector is not in lane zero. This just takes all values in
14775 // the ranges specified by the min/max indices and adds the number of
14776 // elements required to ensure each element comes from the respective
14777 // position in the valid lane.
14778 // On little endian, that's just the corresponding element in the other
14779 // half of the vector. On big endian, it is in the same half but right
14780 // justified rather than left justified in that half.
14781 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14782                                             int LHSMaxIdx, int RHSMinIdx,
14783                                             int RHSMaxIdx, int HalfVec,
14784                                             unsigned ValidLaneWidth,
14785                                             const PPCSubtarget &Subtarget) {
14786   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14787     int Idx = ShuffV[i];
14788     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14789       ShuffV[i] +=
14790           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14791   }
14792 }
14793 
14794 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14795 // the original is:
14796 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14797 // In such a case, just change the shuffle mask to extract the element
14798 // from the permuted index.
14799 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14800                                const PPCSubtarget &Subtarget) {
14801   SDLoc dl(OrigSToV);
14802   EVT VT = OrigSToV.getValueType();
14803   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14804          "Expecting a SCALAR_TO_VECTOR here");
14805   SDValue Input = OrigSToV.getOperand(0);
14806 
14807   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14808     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14809     SDValue OrigVector = Input.getOperand(0);
14810 
14811     // Can't handle non-const element indices or different vector types
14812     // for the input to the extract and the output of the scalar_to_vector.
14813     if (Idx && VT == OrigVector.getValueType()) {
14814       unsigned NumElts = VT.getVectorNumElements();
14815       assert(
14816           NumElts > 1 &&
14817           "Cannot produce a permuted scalar_to_vector for one element vector");
14818       SmallVector<int, 16> NewMask(NumElts, -1);
14819       unsigned ResultInElt = NumElts / 2;
14820       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14821       NewMask[ResultInElt] = Idx->getZExtValue();
14822       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14823     }
14824   }
14825   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14826                      OrigSToV.getOperand(0));
14827 }
14828 
14829 // On little endian subtargets, combine shuffles such as:
14830 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14831 // into:
14832 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14833 // because the latter can be matched to a single instruction merge.
14834 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14835 // to put the value into element zero. Adjust the shuffle mask so that the
14836 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14837 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14838 // nodes with elements smaller than doubleword because all the ways
14839 // of getting scalar data into a vector register put the value in the
14840 // rightmost element of the left half of the vector.
14841 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14842                                                 SelectionDAG &DAG) const {
14843   SDValue LHS = SVN->getOperand(0);
14844   SDValue RHS = SVN->getOperand(1);
14845   auto Mask = SVN->getMask();
14846   int NumElts = LHS.getValueType().getVectorNumElements();
14847   SDValue Res(SVN, 0);
14848   SDLoc dl(SVN);
14849   bool IsLittleEndian = Subtarget.isLittleEndian();
14850 
14851   // On big endian targets this is only useful for subtargets with direct moves.
14852   // On little endian targets it would be useful for all subtargets with VSX.
14853   // However adding special handling for LE subtargets without direct moves
14854   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14855   // which includes direct moves.
14856   if (!Subtarget.hasDirectMove())
14857     return Res;
14858 
14859   // If this is not a shuffle of a shuffle and the first element comes from
14860   // the second vector, canonicalize to the commuted form. This will make it
14861   // more likely to match one of the single instruction patterns.
14862   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14863       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14864     std::swap(LHS, RHS);
14865     Res = DAG.getCommutedVectorShuffle(*SVN);
14866     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14867   }
14868 
14869   // Adjust the shuffle mask if either input vector comes from a
14870   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14871   // form (to prevent the need for a swap).
14872   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14873   SDValue SToVLHS = isScalarToVec(LHS);
14874   SDValue SToVRHS = isScalarToVec(RHS);
14875   if (SToVLHS || SToVRHS) {
14876     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14877                             : SToVRHS.getValueType().getVectorNumElements();
14878     int NumEltsOut = ShuffV.size();
14879     // The width of the "valid lane" (i.e. the lane that contains the value that
14880     // is vectorized) needs to be expressed in terms of the number of elements
14881     // of the shuffle. It is thereby the ratio of the values before and after
14882     // any bitcast.
14883     unsigned ValidLaneWidth =
14884         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14885                       LHS.getValueType().getScalarSizeInBits()
14886                 : SToVRHS.getValueType().getScalarSizeInBits() /
14887                       RHS.getValueType().getScalarSizeInBits();
14888 
14889     // Initially assume that neither input is permuted. These will be adjusted
14890     // accordingly if either input is.
14891     int LHSMaxIdx = -1;
14892     int RHSMinIdx = -1;
14893     int RHSMaxIdx = -1;
14894     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14895 
14896     // Get the permuted scalar to vector nodes for the source(s) that come from
14897     // ISD::SCALAR_TO_VECTOR.
14898     // On big endian systems, this only makes sense for element sizes smaller
14899     // than 64 bits since for 64-bit elements, all instructions already put
14900     // the value into element zero. Since scalar size of LHS and RHS may differ
14901     // after isScalarToVec, this should be checked using their own sizes.
14902     if (SToVLHS) {
14903       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14904         return Res;
14905       // Set up the values for the shuffle vector fixup.
14906       LHSMaxIdx = NumEltsOut / NumEltsIn;
14907       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14908       if (SToVLHS.getValueType() != LHS.getValueType())
14909         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14910       LHS = SToVLHS;
14911     }
14912     if (SToVRHS) {
14913       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14914         return Res;
14915       RHSMinIdx = NumEltsOut;
14916       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14917       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14918       if (SToVRHS.getValueType() != RHS.getValueType())
14919         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14920       RHS = SToVRHS;
14921     }
14922 
14923     // Fix up the shuffle mask to reflect where the desired element actually is.
14924     // The minimum and maximum indices that correspond to element zero for both
14925     // the LHS and RHS are computed and will control which shuffle mask entries
14926     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14927     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14928     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14929                                     HalfVec, ValidLaneWidth, Subtarget);
14930     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14931 
14932     // We may have simplified away the shuffle. We won't be able to do anything
14933     // further with it here.
14934     if (!isa<ShuffleVectorSDNode>(Res))
14935       return Res;
14936     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14937   }
14938 
14939   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14940   // The common case after we commuted the shuffle is that the RHS is a splat
14941   // and we have elements coming in from the splat at indices that are not
14942   // conducive to using a merge.
14943   // Example:
14944   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14945   if (!isSplatBV(TheSplat))
14946     return Res;
14947 
14948   // We are looking for a mask such that all even elements are from
14949   // one vector and all odd elements from the other.
14950   if (!isAlternatingShuffMask(Mask, NumElts))
14951     return Res;
14952 
14953   // Adjust the mask so we are pulling in the same index from the splat
14954   // as the index from the interesting vector in consecutive elements.
14955   if (IsLittleEndian) {
14956     // Example (even elements from first vector):
14957     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14958     if (Mask[0] < NumElts)
14959       for (int i = 1, e = Mask.size(); i < e; i += 2)
14960         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14961     // Example (odd elements from first vector):
14962     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14963     else
14964       for (int i = 0, e = Mask.size(); i < e; i += 2)
14965         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14966   } else {
14967     // Example (even elements from first vector):
14968     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14969     if (Mask[0] < NumElts)
14970       for (int i = 0, e = Mask.size(); i < e; i += 2)
14971         ShuffV[i] = ShuffV[i + 1] - NumElts;
14972     // Example (odd elements from first vector):
14973     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14974     else
14975       for (int i = 1, e = Mask.size(); i < e; i += 2)
14976         ShuffV[i] = ShuffV[i - 1] - NumElts;
14977   }
14978 
14979   // If the RHS has undefs, we need to remove them since we may have created
14980   // a shuffle that adds those instead of the splat value.
14981   SDValue SplatVal =
14982       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14983   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14984 
14985   if (IsLittleEndian)
14986     RHS = TheSplat;
14987   else
14988     LHS = TheSplat;
14989   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14990 }
14991 
14992 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14993                                                 LSBaseSDNode *LSBase,
14994                                                 DAGCombinerInfo &DCI) const {
14995   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14996         "Not a reverse memop pattern!");
14997 
14998   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14999     auto Mask = SVN->getMask();
15000     int i = 0;
15001     auto I = Mask.rbegin();
15002     auto E = Mask.rend();
15003 
15004     for (; I != E; ++I) {
15005       if (*I != i)
15006         return false;
15007       i++;
15008     }
15009     return true;
15010   };
15011 
15012   SelectionDAG &DAG = DCI.DAG;
15013   EVT VT = SVN->getValueType(0);
15014 
15015   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
15016     return SDValue();
15017 
15018   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
15019   // See comment in PPCVSXSwapRemoval.cpp.
15020   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
15021   if (!Subtarget.hasP9Vector())
15022     return SDValue();
15023 
15024   if(!IsElementReverse(SVN))
15025     return SDValue();
15026 
15027   if (LSBase->getOpcode() == ISD::LOAD) {
15028     // If the load return value 0 has more than one user except the
15029     // shufflevector instruction, it is not profitable to replace the
15030     // shufflevector with a reverse load.
15031     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
15032          UI != UE; ++UI)
15033       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
15034         return SDValue();
15035 
15036     SDLoc dl(LSBase);
15037     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
15038     return DAG.getMemIntrinsicNode(
15039         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
15040         LSBase->getMemoryVT(), LSBase->getMemOperand());
15041   }
15042 
15043   if (LSBase->getOpcode() == ISD::STORE) {
15044     // If there are other uses of the shuffle, the swap cannot be avoided.
15045     // Forcing the use of an X-Form (since swapped stores only have
15046     // X-Forms) without removing the swap is unprofitable.
15047     if (!SVN->hasOneUse())
15048       return SDValue();
15049 
15050     SDLoc dl(LSBase);
15051     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
15052                           LSBase->getBasePtr()};
15053     return DAG.getMemIntrinsicNode(
15054         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
15055         LSBase->getMemoryVT(), LSBase->getMemOperand());
15056   }
15057 
15058   llvm_unreachable("Expected a load or store node here");
15059 }
15060 
15061 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
15062                                              DAGCombinerInfo &DCI) const {
15063   SelectionDAG &DAG = DCI.DAG;
15064   SDLoc dl(N);
15065   switch (N->getOpcode()) {
15066   default: break;
15067   case ISD::ADD:
15068     return combineADD(N, DCI);
15069   case ISD::SHL:
15070     return combineSHL(N, DCI);
15071   case ISD::SRA:
15072     return combineSRA(N, DCI);
15073   case ISD::SRL:
15074     return combineSRL(N, DCI);
15075   case ISD::MUL:
15076     return combineMUL(N, DCI);
15077   case ISD::FMA:
15078   case PPCISD::FNMSUB:
15079     return combineFMALike(N, DCI);
15080   case PPCISD::SHL:
15081     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
15082         return N->getOperand(0);
15083     break;
15084   case PPCISD::SRL:
15085     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15086         return N->getOperand(0);
15087     break;
15088   case PPCISD::SRA:
15089     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15090       if (C->isZero() ||  //  0 >>s V -> 0.
15091           C->isAllOnes()) // -1 >>s V -> -1.
15092         return N->getOperand(0);
15093     }
15094     break;
15095   case ISD::SIGN_EXTEND:
15096   case ISD::ZERO_EXTEND:
15097   case ISD::ANY_EXTEND:
15098     return DAGCombineExtBoolTrunc(N, DCI);
15099   case ISD::TRUNCATE:
15100     return combineTRUNCATE(N, DCI);
15101   case ISD::SETCC:
15102     if (SDValue CSCC = combineSetCC(N, DCI))
15103       return CSCC;
15104     LLVM_FALLTHROUGH;
15105   case ISD::SELECT_CC:
15106     return DAGCombineTruncBoolExt(N, DCI);
15107   case ISD::SINT_TO_FP:
15108   case ISD::UINT_TO_FP:
15109     return combineFPToIntToFP(N, DCI);
15110   case ISD::VECTOR_SHUFFLE:
15111     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15112       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15113       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15114     }
15115     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15116   case ISD::STORE: {
15117 
15118     EVT Op1VT = N->getOperand(1).getValueType();
15119     unsigned Opcode = N->getOperand(1).getOpcode();
15120 
15121     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15122       SDValue Val= combineStoreFPToInt(N, DCI);
15123       if (Val)
15124         return Val;
15125     }
15126 
15127     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15128       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15129       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15130       if (Val)
15131         return Val;
15132     }
15133 
15134     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15135     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15136         N->getOperand(1).getNode()->hasOneUse() &&
15137         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15138          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15139 
15140       // STBRX can only handle simple types and it makes no sense to store less
15141       // two bytes in byte-reversed order.
15142       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15143       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15144         break;
15145 
15146       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15147       // Do an any-extend to 32-bits if this is a half-word input.
15148       if (BSwapOp.getValueType() == MVT::i16)
15149         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15150 
15151       // If the type of BSWAP operand is wider than stored memory width
15152       // it need to be shifted to the right side before STBRX.
15153       if (Op1VT.bitsGT(mVT)) {
15154         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15155         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15156                               DAG.getConstant(Shift, dl, MVT::i32));
15157         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15158         if (Op1VT == MVT::i64)
15159           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15160       }
15161 
15162       SDValue Ops[] = {
15163         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15164       };
15165       return
15166         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15167                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15168                                 cast<StoreSDNode>(N)->getMemOperand());
15169     }
15170 
15171     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15172     // So it can increase the chance of CSE constant construction.
15173     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15174         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15175       // Need to sign-extended to 64-bits to handle negative values.
15176       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15177       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15178                                     MemVT.getSizeInBits());
15179       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15180 
15181       // DAG.getTruncStore() can't be used here because it doesn't accept
15182       // the general (base + offset) addressing mode.
15183       // So we use UpdateNodeOperands and setTruncatingStore instead.
15184       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15185                              N->getOperand(3));
15186       cast<StoreSDNode>(N)->setTruncatingStore(true);
15187       return SDValue(N, 0);
15188     }
15189 
15190     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15191     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15192     if (Op1VT.isSimple()) {
15193       MVT StoreVT = Op1VT.getSimpleVT();
15194       if (Subtarget.needsSwapsForVSXMemOps() &&
15195           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15196            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15197         return expandVSXStoreForLE(N, DCI);
15198     }
15199     break;
15200   }
15201   case ISD::LOAD: {
15202     LoadSDNode *LD = cast<LoadSDNode>(N);
15203     EVT VT = LD->getValueType(0);
15204 
15205     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15206     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15207     if (VT.isSimple()) {
15208       MVT LoadVT = VT.getSimpleVT();
15209       if (Subtarget.needsSwapsForVSXMemOps() &&
15210           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15211            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15212         return expandVSXLoadForLE(N, DCI);
15213     }
15214 
15215     // We sometimes end up with a 64-bit integer load, from which we extract
15216     // two single-precision floating-point numbers. This happens with
15217     // std::complex<float>, and other similar structures, because of the way we
15218     // canonicalize structure copies. However, if we lack direct moves,
15219     // then the final bitcasts from the extracted integer values to the
15220     // floating-point numbers turn into store/load pairs. Even with direct moves,
15221     // just loading the two floating-point numbers is likely better.
15222     auto ReplaceTwoFloatLoad = [&]() {
15223       if (VT != MVT::i64)
15224         return false;
15225 
15226       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15227           LD->isVolatile())
15228         return false;
15229 
15230       //  We're looking for a sequence like this:
15231       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15232       //      t16: i64 = srl t13, Constant:i32<32>
15233       //    t17: i32 = truncate t16
15234       //  t18: f32 = bitcast t17
15235       //    t19: i32 = truncate t13
15236       //  t20: f32 = bitcast t19
15237 
15238       if (!LD->hasNUsesOfValue(2, 0))
15239         return false;
15240 
15241       auto UI = LD->use_begin();
15242       while (UI.getUse().getResNo() != 0) ++UI;
15243       SDNode *Trunc = *UI++;
15244       while (UI.getUse().getResNo() != 0) ++UI;
15245       SDNode *RightShift = *UI;
15246       if (Trunc->getOpcode() != ISD::TRUNCATE)
15247         std::swap(Trunc, RightShift);
15248 
15249       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15250           Trunc->getValueType(0) != MVT::i32 ||
15251           !Trunc->hasOneUse())
15252         return false;
15253       if (RightShift->getOpcode() != ISD::SRL ||
15254           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15255           RightShift->getConstantOperandVal(1) != 32 ||
15256           !RightShift->hasOneUse())
15257         return false;
15258 
15259       SDNode *Trunc2 = *RightShift->use_begin();
15260       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15261           Trunc2->getValueType(0) != MVT::i32 ||
15262           !Trunc2->hasOneUse())
15263         return false;
15264 
15265       SDNode *Bitcast = *Trunc->use_begin();
15266       SDNode *Bitcast2 = *Trunc2->use_begin();
15267 
15268       if (Bitcast->getOpcode() != ISD::BITCAST ||
15269           Bitcast->getValueType(0) != MVT::f32)
15270         return false;
15271       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15272           Bitcast2->getValueType(0) != MVT::f32)
15273         return false;
15274 
15275       if (Subtarget.isLittleEndian())
15276         std::swap(Bitcast, Bitcast2);
15277 
15278       // Bitcast has the second float (in memory-layout order) and Bitcast2
15279       // has the first one.
15280 
15281       SDValue BasePtr = LD->getBasePtr();
15282       if (LD->isIndexed()) {
15283         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15284                "Non-pre-inc AM on PPC?");
15285         BasePtr =
15286           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15287                       LD->getOffset());
15288       }
15289 
15290       auto MMOFlags =
15291           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15292       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15293                                       LD->getPointerInfo(), LD->getAlignment(),
15294                                       MMOFlags, LD->getAAInfo());
15295       SDValue AddPtr =
15296         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15297                     BasePtr, DAG.getIntPtrConstant(4, dl));
15298       SDValue FloatLoad2 = DAG.getLoad(
15299           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15300           LD->getPointerInfo().getWithOffset(4),
15301           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15302 
15303       if (LD->isIndexed()) {
15304         // Note that DAGCombine should re-form any pre-increment load(s) from
15305         // what is produced here if that makes sense.
15306         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15307       }
15308 
15309       DCI.CombineTo(Bitcast2, FloatLoad);
15310       DCI.CombineTo(Bitcast, FloatLoad2);
15311 
15312       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15313                                     SDValue(FloatLoad2.getNode(), 1));
15314       return true;
15315     };
15316 
15317     if (ReplaceTwoFloatLoad())
15318       return SDValue(N, 0);
15319 
15320     EVT MemVT = LD->getMemoryVT();
15321     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15322     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15323     if (LD->isUnindexed() && VT.isVector() &&
15324         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15325           // P8 and later hardware should just use LOAD.
15326           !Subtarget.hasP8Vector() &&
15327           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15328            VT == MVT::v4f32))) &&
15329         LD->getAlign() < ABIAlignment) {
15330       // This is a type-legal unaligned Altivec load.
15331       SDValue Chain = LD->getChain();
15332       SDValue Ptr = LD->getBasePtr();
15333       bool isLittleEndian = Subtarget.isLittleEndian();
15334 
15335       // This implements the loading of unaligned vectors as described in
15336       // the venerable Apple Velocity Engine overview. Specifically:
15337       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15338       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15339       //
15340       // The general idea is to expand a sequence of one or more unaligned
15341       // loads into an alignment-based permutation-control instruction (lvsl
15342       // or lvsr), a series of regular vector loads (which always truncate
15343       // their input address to an aligned address), and a series of
15344       // permutations.  The results of these permutations are the requested
15345       // loaded values.  The trick is that the last "extra" load is not taken
15346       // from the address you might suspect (sizeof(vector) bytes after the
15347       // last requested load), but rather sizeof(vector) - 1 bytes after the
15348       // last requested vector. The point of this is to avoid a page fault if
15349       // the base address happened to be aligned. This works because if the
15350       // base address is aligned, then adding less than a full vector length
15351       // will cause the last vector in the sequence to be (re)loaded.
15352       // Otherwise, the next vector will be fetched as you might suspect was
15353       // necessary.
15354 
15355       // We might be able to reuse the permutation generation from
15356       // a different base address offset from this one by an aligned amount.
15357       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15358       // optimization later.
15359       Intrinsic::ID Intr, IntrLD, IntrPerm;
15360       MVT PermCntlTy, PermTy, LDTy;
15361       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15362                             : Intrinsic::ppc_altivec_lvsl;
15363       IntrLD = Intrinsic::ppc_altivec_lvx;
15364       IntrPerm = Intrinsic::ppc_altivec_vperm;
15365       PermCntlTy = MVT::v16i8;
15366       PermTy = MVT::v4i32;
15367       LDTy = MVT::v4i32;
15368 
15369       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15370 
15371       // Create the new MMO for the new base load. It is like the original MMO,
15372       // but represents an area in memory almost twice the vector size centered
15373       // on the original address. If the address is unaligned, we might start
15374       // reading up to (sizeof(vector)-1) bytes below the address of the
15375       // original unaligned load.
15376       MachineFunction &MF = DAG.getMachineFunction();
15377       MachineMemOperand *BaseMMO =
15378         MF.getMachineMemOperand(LD->getMemOperand(),
15379                                 -(long)MemVT.getStoreSize()+1,
15380                                 2*MemVT.getStoreSize()-1);
15381 
15382       // Create the new base load.
15383       SDValue LDXIntID =
15384           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15385       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15386       SDValue BaseLoad =
15387         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15388                                 DAG.getVTList(PermTy, MVT::Other),
15389                                 BaseLoadOps, LDTy, BaseMMO);
15390 
15391       // Note that the value of IncOffset (which is provided to the next
15392       // load's pointer info offset value, and thus used to calculate the
15393       // alignment), and the value of IncValue (which is actually used to
15394       // increment the pointer value) are different! This is because we
15395       // require the next load to appear to be aligned, even though it
15396       // is actually offset from the base pointer by a lesser amount.
15397       int IncOffset = VT.getSizeInBits() / 8;
15398       int IncValue = IncOffset;
15399 
15400       // Walk (both up and down) the chain looking for another load at the real
15401       // (aligned) offset (the alignment of the other load does not matter in
15402       // this case). If found, then do not use the offset reduction trick, as
15403       // that will prevent the loads from being later combined (as they would
15404       // otherwise be duplicates).
15405       if (!findConsecutiveLoad(LD, DAG))
15406         --IncValue;
15407 
15408       SDValue Increment =
15409           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15410       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15411 
15412       MachineMemOperand *ExtraMMO =
15413         MF.getMachineMemOperand(LD->getMemOperand(),
15414                                 1, 2*MemVT.getStoreSize()-1);
15415       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15416       SDValue ExtraLoad =
15417         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15418                                 DAG.getVTList(PermTy, MVT::Other),
15419                                 ExtraLoadOps, LDTy, ExtraMMO);
15420 
15421       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15422         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15423 
15424       // Because vperm has a big-endian bias, we must reverse the order
15425       // of the input vectors and complement the permute control vector
15426       // when generating little endian code.  We have already handled the
15427       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15428       // and ExtraLoad here.
15429       SDValue Perm;
15430       if (isLittleEndian)
15431         Perm = BuildIntrinsicOp(IntrPerm,
15432                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15433       else
15434         Perm = BuildIntrinsicOp(IntrPerm,
15435                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15436 
15437       if (VT != PermTy)
15438         Perm = Subtarget.hasAltivec()
15439                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15440                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15441                                  DAG.getTargetConstant(1, dl, MVT::i64));
15442                                // second argument is 1 because this rounding
15443                                // is always exact.
15444 
15445       // The output of the permutation is our loaded result, the TokenFactor is
15446       // our new chain.
15447       DCI.CombineTo(N, Perm, TF);
15448       return SDValue(N, 0);
15449     }
15450     }
15451     break;
15452     case ISD::INTRINSIC_WO_CHAIN: {
15453       bool isLittleEndian = Subtarget.isLittleEndian();
15454       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15455       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15456                                            : Intrinsic::ppc_altivec_lvsl);
15457       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15458         SDValue Add = N->getOperand(1);
15459 
15460         int Bits = 4 /* 16 byte alignment */;
15461 
15462         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15463                                   APInt::getAllOnes(Bits /* alignment */)
15464                                       .zext(Add.getScalarValueSizeInBits()))) {
15465           SDNode *BasePtr = Add->getOperand(0).getNode();
15466           for (SDNode *U : BasePtr->uses()) {
15467             if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15468                 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15469               // We've found another LVSL/LVSR, and this address is an aligned
15470               // multiple of that one. The results will be the same, so use the
15471               // one we've just found instead.
15472 
15473               return SDValue(U, 0);
15474             }
15475           }
15476         }
15477 
15478         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15479           SDNode *BasePtr = Add->getOperand(0).getNode();
15480           for (SDNode *U : BasePtr->uses()) {
15481             if (U->getOpcode() == ISD::ADD &&
15482                 isa<ConstantSDNode>(U->getOperand(1)) &&
15483                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15484                  cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15485                         (1ULL << Bits) ==
15486                     0) {
15487               SDNode *OtherAdd = U;
15488               for (SDNode *V : OtherAdd->uses()) {
15489                 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15490                     cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15491                         IID) {
15492                   return SDValue(V, 0);
15493                 }
15494               }
15495             }
15496           }
15497         }
15498       }
15499 
15500       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15501       // Expose the vabsduw/h/b opportunity for down stream
15502       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15503           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15504            IID == Intrinsic::ppc_altivec_vmaxsh ||
15505            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15506         SDValue V1 = N->getOperand(1);
15507         SDValue V2 = N->getOperand(2);
15508         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15509              V1.getSimpleValueType() == MVT::v8i16 ||
15510              V1.getSimpleValueType() == MVT::v16i8) &&
15511             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15512           // (0-a, a)
15513           if (V1.getOpcode() == ISD::SUB &&
15514               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15515               V1.getOperand(1) == V2) {
15516             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15517           }
15518           // (a, 0-a)
15519           if (V2.getOpcode() == ISD::SUB &&
15520               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15521               V2.getOperand(1) == V1) {
15522             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15523           }
15524           // (x-y, y-x)
15525           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15526               V1.getOperand(0) == V2.getOperand(1) &&
15527               V1.getOperand(1) == V2.getOperand(0)) {
15528             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15529           }
15530         }
15531       }
15532     }
15533 
15534     break;
15535   case ISD::INTRINSIC_W_CHAIN:
15536     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15537     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15538     if (Subtarget.needsSwapsForVSXMemOps()) {
15539       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15540       default:
15541         break;
15542       case Intrinsic::ppc_vsx_lxvw4x:
15543       case Intrinsic::ppc_vsx_lxvd2x:
15544         return expandVSXLoadForLE(N, DCI);
15545       }
15546     }
15547     break;
15548   case ISD::INTRINSIC_VOID:
15549     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15550     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15551     if (Subtarget.needsSwapsForVSXMemOps()) {
15552       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15553       default:
15554         break;
15555       case Intrinsic::ppc_vsx_stxvw4x:
15556       case Intrinsic::ppc_vsx_stxvd2x:
15557         return expandVSXStoreForLE(N, DCI);
15558       }
15559     }
15560     break;
15561   case ISD::BSWAP: {
15562     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15563     // For subtargets without LDBRX, we can still do better than the default
15564     // expansion even for 64-bit BSWAP (LOAD).
15565     bool Is64BitBswapOn64BitTgt =
15566         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15567     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15568                                N->getOperand(0).hasOneUse();
15569     if (IsSingleUseNormalLd &&
15570         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15571          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15572       SDValue Load = N->getOperand(0);
15573       LoadSDNode *LD = cast<LoadSDNode>(Load);
15574       // Create the byte-swapping load.
15575       SDValue Ops[] = {
15576         LD->getChain(),    // Chain
15577         LD->getBasePtr(),  // Ptr
15578         DAG.getValueType(N->getValueType(0)) // VT
15579       };
15580       SDValue BSLoad =
15581         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15582                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15583                                               MVT::i64 : MVT::i32, MVT::Other),
15584                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15585 
15586       // If this is an i16 load, insert the truncate.
15587       SDValue ResVal = BSLoad;
15588       if (N->getValueType(0) == MVT::i16)
15589         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15590 
15591       // First, combine the bswap away.  This makes the value produced by the
15592       // load dead.
15593       DCI.CombineTo(N, ResVal);
15594 
15595       // Next, combine the load away, we give it a bogus result value but a real
15596       // chain result.  The result value is dead because the bswap is dead.
15597       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15598 
15599       // Return N so it doesn't get rechecked!
15600       return SDValue(N, 0);
15601     }
15602     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15603     // before legalization so that the BUILD_PAIR is handled correctly.
15604     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15605         !IsSingleUseNormalLd)
15606       return SDValue();
15607     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15608 
15609     // Can't split volatile or atomic loads.
15610     if (!LD->isSimple())
15611       return SDValue();
15612     SDValue BasePtr = LD->getBasePtr();
15613     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15614                              LD->getPointerInfo(), LD->getAlignment());
15615     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15616     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15617                           DAG.getIntPtrConstant(4, dl));
15618     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15619         LD->getMemOperand(), 4, 4);
15620     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15621     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15622     SDValue Res;
15623     if (Subtarget.isLittleEndian())
15624       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15625     else
15626       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15627     SDValue TF =
15628         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15629                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15630     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15631     return Res;
15632   }
15633   case PPCISD::VCMP:
15634     // If a VCMP_rec node already exists with exactly the same operands as this
15635     // node, use its result instead of this node (VCMP_rec computes both a CR6
15636     // and a normal output).
15637     //
15638     if (!N->getOperand(0).hasOneUse() &&
15639         !N->getOperand(1).hasOneUse() &&
15640         !N->getOperand(2).hasOneUse()) {
15641 
15642       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15643       SDNode *VCMPrecNode = nullptr;
15644 
15645       SDNode *LHSN = N->getOperand(0).getNode();
15646       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15647            UI != E; ++UI)
15648         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15649             UI->getOperand(1) == N->getOperand(1) &&
15650             UI->getOperand(2) == N->getOperand(2) &&
15651             UI->getOperand(0) == N->getOperand(0)) {
15652           VCMPrecNode = *UI;
15653           break;
15654         }
15655 
15656       // If there is no VCMP_rec node, or if the flag value has a single use,
15657       // don't transform this.
15658       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15659         break;
15660 
15661       // Look at the (necessarily single) use of the flag value.  If it has a
15662       // chain, this transformation is more complex.  Note that multiple things
15663       // could use the value result, which we should ignore.
15664       SDNode *FlagUser = nullptr;
15665       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15666            FlagUser == nullptr; ++UI) {
15667         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15668         SDNode *User = *UI;
15669         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15670           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15671             FlagUser = User;
15672             break;
15673           }
15674         }
15675       }
15676 
15677       // If the user is a MFOCRF instruction, we know this is safe.
15678       // Otherwise we give up for right now.
15679       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15680         return SDValue(VCMPrecNode, 0);
15681     }
15682     break;
15683   case ISD::BRCOND: {
15684     SDValue Cond = N->getOperand(1);
15685     SDValue Target = N->getOperand(2);
15686 
15687     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15688         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15689           Intrinsic::loop_decrement) {
15690 
15691       // We now need to make the intrinsic dead (it cannot be instruction
15692       // selected).
15693       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15694       assert(Cond.getNode()->hasOneUse() &&
15695              "Counter decrement has more than one use");
15696 
15697       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15698                          N->getOperand(0), Target);
15699     }
15700   }
15701   break;
15702   case ISD::BR_CC: {
15703     // If this is a branch on an altivec predicate comparison, lower this so
15704     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15705     // lowering is done pre-legalize, because the legalizer lowers the predicate
15706     // compare down to code that is difficult to reassemble.
15707     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15708     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15709 
15710     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15711     // value. If so, pass-through the AND to get to the intrinsic.
15712     if (LHS.getOpcode() == ISD::AND &&
15713         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15714         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15715           Intrinsic::loop_decrement &&
15716         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15717         !isNullConstant(LHS.getOperand(1)))
15718       LHS = LHS.getOperand(0);
15719 
15720     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15721         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15722           Intrinsic::loop_decrement &&
15723         isa<ConstantSDNode>(RHS)) {
15724       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15725              "Counter decrement comparison is not EQ or NE");
15726 
15727       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15728       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15729                     (CC == ISD::SETNE && !Val);
15730 
15731       // We now need to make the intrinsic dead (it cannot be instruction
15732       // selected).
15733       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15734       assert(LHS.getNode()->hasOneUse() &&
15735              "Counter decrement has more than one use");
15736 
15737       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15738                          N->getOperand(0), N->getOperand(4));
15739     }
15740 
15741     int CompareOpc;
15742     bool isDot;
15743 
15744     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15745         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15746         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15747       assert(isDot && "Can't compare against a vector result!");
15748 
15749       // If this is a comparison against something other than 0/1, then we know
15750       // that the condition is never/always true.
15751       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15752       if (Val != 0 && Val != 1) {
15753         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15754           return N->getOperand(0);
15755         // Always !=, turn it into an unconditional branch.
15756         return DAG.getNode(ISD::BR, dl, MVT::Other,
15757                            N->getOperand(0), N->getOperand(4));
15758       }
15759 
15760       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15761 
15762       // Create the PPCISD altivec 'dot' comparison node.
15763       SDValue Ops[] = {
15764         LHS.getOperand(2),  // LHS of compare
15765         LHS.getOperand(3),  // RHS of compare
15766         DAG.getConstant(CompareOpc, dl, MVT::i32)
15767       };
15768       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15769       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15770 
15771       // Unpack the result based on how the target uses it.
15772       PPC::Predicate CompOpc;
15773       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15774       default:  // Can't happen, don't crash on invalid number though.
15775       case 0:   // Branch on the value of the EQ bit of CR6.
15776         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15777         break;
15778       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15779         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15780         break;
15781       case 2:   // Branch on the value of the LT bit of CR6.
15782         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15783         break;
15784       case 3:   // Branch on the inverted value of the LT bit of CR6.
15785         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15786         break;
15787       }
15788 
15789       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15790                          DAG.getConstant(CompOpc, dl, MVT::i32),
15791                          DAG.getRegister(PPC::CR6, MVT::i32),
15792                          N->getOperand(4), CompNode.getValue(1));
15793     }
15794     break;
15795   }
15796   case ISD::BUILD_VECTOR:
15797     return DAGCombineBuildVector(N, DCI);
15798   case ISD::ABS:
15799     return combineABS(N, DCI);
15800   case ISD::VSELECT:
15801     return combineVSelect(N, DCI);
15802   }
15803 
15804   return SDValue();
15805 }
15806 
15807 SDValue
15808 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15809                                  SelectionDAG &DAG,
15810                                  SmallVectorImpl<SDNode *> &Created) const {
15811   // fold (sdiv X, pow2)
15812   EVT VT = N->getValueType(0);
15813   if (VT == MVT::i64 && !Subtarget.isPPC64())
15814     return SDValue();
15815   if ((VT != MVT::i32 && VT != MVT::i64) ||
15816       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15817     return SDValue();
15818 
15819   SDLoc DL(N);
15820   SDValue N0 = N->getOperand(0);
15821 
15822   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15823   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15824   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15825 
15826   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15827   Created.push_back(Op.getNode());
15828 
15829   if (IsNegPow2) {
15830     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15831     Created.push_back(Op.getNode());
15832   }
15833 
15834   return Op;
15835 }
15836 
15837 //===----------------------------------------------------------------------===//
15838 // Inline Assembly Support
15839 //===----------------------------------------------------------------------===//
15840 
15841 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15842                                                       KnownBits &Known,
15843                                                       const APInt &DemandedElts,
15844                                                       const SelectionDAG &DAG,
15845                                                       unsigned Depth) const {
15846   Known.resetAll();
15847   switch (Op.getOpcode()) {
15848   default: break;
15849   case PPCISD::LBRX: {
15850     // lhbrx is known to have the top bits cleared out.
15851     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15852       Known.Zero = 0xFFFF0000;
15853     break;
15854   }
15855   case ISD::INTRINSIC_WO_CHAIN: {
15856     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15857     default: break;
15858     case Intrinsic::ppc_altivec_vcmpbfp_p:
15859     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15860     case Intrinsic::ppc_altivec_vcmpequb_p:
15861     case Intrinsic::ppc_altivec_vcmpequh_p:
15862     case Intrinsic::ppc_altivec_vcmpequw_p:
15863     case Intrinsic::ppc_altivec_vcmpequd_p:
15864     case Intrinsic::ppc_altivec_vcmpequq_p:
15865     case Intrinsic::ppc_altivec_vcmpgefp_p:
15866     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15867     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15868     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15869     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15870     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15871     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15872     case Intrinsic::ppc_altivec_vcmpgtub_p:
15873     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15874     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15875     case Intrinsic::ppc_altivec_vcmpgtud_p:
15876     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15877       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15878       break;
15879     }
15880     break;
15881   }
15882   case ISD::INTRINSIC_W_CHAIN: {
15883     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15884     default:
15885       break;
15886     case Intrinsic::ppc_load2r:
15887       // Top bits are cleared for load2r (which is the same as lhbrx).
15888       Known.Zero = 0xFFFF0000;
15889       break;
15890     }
15891     break;
15892   }
15893   }
15894 }
15895 
15896 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15897   switch (Subtarget.getCPUDirective()) {
15898   default: break;
15899   case PPC::DIR_970:
15900   case PPC::DIR_PWR4:
15901   case PPC::DIR_PWR5:
15902   case PPC::DIR_PWR5X:
15903   case PPC::DIR_PWR6:
15904   case PPC::DIR_PWR6X:
15905   case PPC::DIR_PWR7:
15906   case PPC::DIR_PWR8:
15907   case PPC::DIR_PWR9:
15908   case PPC::DIR_PWR10:
15909   case PPC::DIR_PWR_FUTURE: {
15910     if (!ML)
15911       break;
15912 
15913     if (!DisableInnermostLoopAlign32) {
15914       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15915       // so that we can decrease cache misses and branch-prediction misses.
15916       // Actual alignment of the loop will depend on the hotness check and other
15917       // logic in alignBlocks.
15918       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15919         return Align(32);
15920     }
15921 
15922     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15923 
15924     // For small loops (between 5 and 8 instructions), align to a 32-byte
15925     // boundary so that the entire loop fits in one instruction-cache line.
15926     uint64_t LoopSize = 0;
15927     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15928       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15929         LoopSize += TII->getInstSizeInBytes(*J);
15930         if (LoopSize > 32)
15931           break;
15932       }
15933 
15934     if (LoopSize > 16 && LoopSize <= 32)
15935       return Align(32);
15936 
15937     break;
15938   }
15939   }
15940 
15941   return TargetLowering::getPrefLoopAlignment(ML);
15942 }
15943 
15944 /// getConstraintType - Given a constraint, return the type of
15945 /// constraint it is for this target.
15946 PPCTargetLowering::ConstraintType
15947 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15948   if (Constraint.size() == 1) {
15949     switch (Constraint[0]) {
15950     default: break;
15951     case 'b':
15952     case 'r':
15953     case 'f':
15954     case 'd':
15955     case 'v':
15956     case 'y':
15957       return C_RegisterClass;
15958     case 'Z':
15959       // FIXME: While Z does indicate a memory constraint, it specifically
15960       // indicates an r+r address (used in conjunction with the 'y' modifier
15961       // in the replacement string). Currently, we're forcing the base
15962       // register to be r0 in the asm printer (which is interpreted as zero)
15963       // and forming the complete address in the second register. This is
15964       // suboptimal.
15965       return C_Memory;
15966     }
15967   } else if (Constraint == "wc") { // individual CR bits.
15968     return C_RegisterClass;
15969   } else if (Constraint == "wa" || Constraint == "wd" ||
15970              Constraint == "wf" || Constraint == "ws" ||
15971              Constraint == "wi" || Constraint == "ww") {
15972     return C_RegisterClass; // VSX registers.
15973   }
15974   return TargetLowering::getConstraintType(Constraint);
15975 }
15976 
15977 /// Examine constraint type and operand type and determine a weight value.
15978 /// This object must already have been set up with the operand type
15979 /// and the current alternative constraint selected.
15980 TargetLowering::ConstraintWeight
15981 PPCTargetLowering::getSingleConstraintMatchWeight(
15982     AsmOperandInfo &info, const char *constraint) const {
15983   ConstraintWeight weight = CW_Invalid;
15984   Value *CallOperandVal = info.CallOperandVal;
15985     // If we don't have a value, we can't do a match,
15986     // but allow it at the lowest weight.
15987   if (!CallOperandVal)
15988     return CW_Default;
15989   Type *type = CallOperandVal->getType();
15990 
15991   // Look at the constraint type.
15992   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15993     return CW_Register; // an individual CR bit.
15994   else if ((StringRef(constraint) == "wa" ||
15995             StringRef(constraint) == "wd" ||
15996             StringRef(constraint) == "wf") &&
15997            type->isVectorTy())
15998     return CW_Register;
15999   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
16000     return CW_Register; // just hold 64-bit integers data.
16001   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
16002     return CW_Register;
16003   else if (StringRef(constraint) == "ww" && type->isFloatTy())
16004     return CW_Register;
16005 
16006   switch (*constraint) {
16007   default:
16008     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16009     break;
16010   case 'b':
16011     if (type->isIntegerTy())
16012       weight = CW_Register;
16013     break;
16014   case 'f':
16015     if (type->isFloatTy())
16016       weight = CW_Register;
16017     break;
16018   case 'd':
16019     if (type->isDoubleTy())
16020       weight = CW_Register;
16021     break;
16022   case 'v':
16023     if (type->isVectorTy())
16024       weight = CW_Register;
16025     break;
16026   case 'y':
16027     weight = CW_Register;
16028     break;
16029   case 'Z':
16030     weight = CW_Memory;
16031     break;
16032   }
16033   return weight;
16034 }
16035 
16036 std::pair<unsigned, const TargetRegisterClass *>
16037 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
16038                                                 StringRef Constraint,
16039                                                 MVT VT) const {
16040   if (Constraint.size() == 1) {
16041     // GCC RS6000 Constraint Letters
16042     switch (Constraint[0]) {
16043     case 'b':   // R1-R31
16044       if (VT == MVT::i64 && Subtarget.isPPC64())
16045         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
16046       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
16047     case 'r':   // R0-R31
16048       if (VT == MVT::i64 && Subtarget.isPPC64())
16049         return std::make_pair(0U, &PPC::G8RCRegClass);
16050       return std::make_pair(0U, &PPC::GPRCRegClass);
16051     // 'd' and 'f' constraints are both defined to be "the floating point
16052     // registers", where one is for 32-bit and the other for 64-bit. We don't
16053     // really care overly much here so just give them all the same reg classes.
16054     case 'd':
16055     case 'f':
16056       if (Subtarget.hasSPE()) {
16057         if (VT == MVT::f32 || VT == MVT::i32)
16058           return std::make_pair(0U, &PPC::GPRCRegClass);
16059         if (VT == MVT::f64 || VT == MVT::i64)
16060           return std::make_pair(0U, &PPC::SPERCRegClass);
16061       } else {
16062         if (VT == MVT::f32 || VT == MVT::i32)
16063           return std::make_pair(0U, &PPC::F4RCRegClass);
16064         if (VT == MVT::f64 || VT == MVT::i64)
16065           return std::make_pair(0U, &PPC::F8RCRegClass);
16066       }
16067       break;
16068     case 'v':
16069       if (Subtarget.hasAltivec() && VT.isVector())
16070         return std::make_pair(0U, &PPC::VRRCRegClass);
16071       else if (Subtarget.hasVSX())
16072         // Scalars in Altivec registers only make sense with VSX.
16073         return std::make_pair(0U, &PPC::VFRCRegClass);
16074       break;
16075     case 'y':   // crrc
16076       return std::make_pair(0U, &PPC::CRRCRegClass);
16077     }
16078   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
16079     // An individual CR bit.
16080     return std::make_pair(0U, &PPC::CRBITRCRegClass);
16081   } else if ((Constraint == "wa" || Constraint == "wd" ||
16082              Constraint == "wf" || Constraint == "wi") &&
16083              Subtarget.hasVSX()) {
16084     // A VSX register for either a scalar (FP) or vector. There is no
16085     // support for single precision scalars on subtargets prior to Power8.
16086     if (VT.isVector())
16087       return std::make_pair(0U, &PPC::VSRCRegClass);
16088     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16089       return std::make_pair(0U, &PPC::VSSRCRegClass);
16090     return std::make_pair(0U, &PPC::VSFRCRegClass);
16091   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16092     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16093       return std::make_pair(0U, &PPC::VSSRCRegClass);
16094     else
16095       return std::make_pair(0U, &PPC::VSFRCRegClass);
16096   } else if (Constraint == "lr") {
16097     if (VT == MVT::i64)
16098       return std::make_pair(0U, &PPC::LR8RCRegClass);
16099     else
16100       return std::make_pair(0U, &PPC::LRRCRegClass);
16101   }
16102 
16103   // Handle special cases of physical registers that are not properly handled
16104   // by the base class.
16105   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16106     // If we name a VSX register, we can't defer to the base class because it
16107     // will not recognize the correct register (their names will be VSL{0-31}
16108     // and V{0-31} so they won't match). So we match them here.
16109     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16110       int VSNum = atoi(Constraint.data() + 3);
16111       assert(VSNum >= 0 && VSNum <= 63 &&
16112              "Attempted to access a vsr out of range");
16113       if (VSNum < 32)
16114         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16115       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16116     }
16117 
16118     // For float registers, we can't defer to the base class as it will match
16119     // the SPILLTOVSRRC class.
16120     if (Constraint.size() > 3 && Constraint[1] == 'f') {
16121       int RegNum = atoi(Constraint.data() + 2);
16122       if (RegNum > 31 || RegNum < 0)
16123         report_fatal_error("Invalid floating point register number");
16124       if (VT == MVT::f32 || VT == MVT::i32)
16125         return Subtarget.hasSPE()
16126                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16127                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16128       if (VT == MVT::f64 || VT == MVT::i64)
16129         return Subtarget.hasSPE()
16130                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16131                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16132     }
16133   }
16134 
16135   std::pair<unsigned, const TargetRegisterClass *> R =
16136       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16137 
16138   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16139   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16140   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16141   // register.
16142   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16143   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16144   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16145       PPC::GPRCRegClass.contains(R.first))
16146     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16147                             PPC::sub_32, &PPC::G8RCRegClass),
16148                           &PPC::G8RCRegClass);
16149 
16150   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16151   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16152     R.first = PPC::CR0;
16153     R.second = &PPC::CRRCRegClass;
16154   }
16155   // FIXME: This warning should ideally be emitted in the front end.
16156   const auto &TM = getTargetMachine();
16157   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16158     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16159          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16160         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16161       errs() << "warning: vector registers 20 to 32 are reserved in the "
16162                 "default AIX AltiVec ABI and cannot be used\n";
16163   }
16164 
16165   return R;
16166 }
16167 
16168 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16169 /// vector.  If it is invalid, don't add anything to Ops.
16170 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16171                                                      std::string &Constraint,
16172                                                      std::vector<SDValue>&Ops,
16173                                                      SelectionDAG &DAG) const {
16174   SDValue Result;
16175 
16176   // Only support length 1 constraints.
16177   if (Constraint.length() > 1) return;
16178 
16179   char Letter = Constraint[0];
16180   switch (Letter) {
16181   default: break;
16182   case 'I':
16183   case 'J':
16184   case 'K':
16185   case 'L':
16186   case 'M':
16187   case 'N':
16188   case 'O':
16189   case 'P': {
16190     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16191     if (!CST) return; // Must be an immediate to match.
16192     SDLoc dl(Op);
16193     int64_t Value = CST->getSExtValue();
16194     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16195                          // numbers are printed as such.
16196     switch (Letter) {
16197     default: llvm_unreachable("Unknown constraint letter!");
16198     case 'I':  // "I" is a signed 16-bit constant.
16199       if (isInt<16>(Value))
16200         Result = DAG.getTargetConstant(Value, dl, TCVT);
16201       break;
16202     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16203       if (isShiftedUInt<16, 16>(Value))
16204         Result = DAG.getTargetConstant(Value, dl, TCVT);
16205       break;
16206     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16207       if (isShiftedInt<16, 16>(Value))
16208         Result = DAG.getTargetConstant(Value, dl, TCVT);
16209       break;
16210     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16211       if (isUInt<16>(Value))
16212         Result = DAG.getTargetConstant(Value, dl, TCVT);
16213       break;
16214     case 'M':  // "M" is a constant that is greater than 31.
16215       if (Value > 31)
16216         Result = DAG.getTargetConstant(Value, dl, TCVT);
16217       break;
16218     case 'N':  // "N" is a positive constant that is an exact power of two.
16219       if (Value > 0 && isPowerOf2_64(Value))
16220         Result = DAG.getTargetConstant(Value, dl, TCVT);
16221       break;
16222     case 'O':  // "O" is the constant zero.
16223       if (Value == 0)
16224         Result = DAG.getTargetConstant(Value, dl, TCVT);
16225       break;
16226     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16227       if (isInt<16>(-Value))
16228         Result = DAG.getTargetConstant(Value, dl, TCVT);
16229       break;
16230     }
16231     break;
16232   }
16233   }
16234 
16235   if (Result.getNode()) {
16236     Ops.push_back(Result);
16237     return;
16238   }
16239 
16240   // Handle standard constraint letters.
16241   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16242 }
16243 
16244 // isLegalAddressingMode - Return true if the addressing mode represented
16245 // by AM is legal for this target, for a load/store of the specified type.
16246 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16247                                               const AddrMode &AM, Type *Ty,
16248                                               unsigned AS,
16249                                               Instruction *I) const {
16250   // Vector type r+i form is supported since power9 as DQ form. We don't check
16251   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16252   // imm form is preferred and the offset can be adjusted to use imm form later
16253   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16254   // max offset to check legal addressing mode, we should be a little aggressive
16255   // to contain other offsets for that LSRUse.
16256   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16257     return false;
16258 
16259   // PPC allows a sign-extended 16-bit immediate field.
16260   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16261     return false;
16262 
16263   // No global is ever allowed as a base.
16264   if (AM.BaseGV)
16265     return false;
16266 
16267   // PPC only support r+r,
16268   switch (AM.Scale) {
16269   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16270     break;
16271   case 1:
16272     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16273       return false;
16274     // Otherwise we have r+r or r+i.
16275     break;
16276   case 2:
16277     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16278       return false;
16279     // Allow 2*r as r+r.
16280     break;
16281   default:
16282     // No other scales are supported.
16283     return false;
16284   }
16285 
16286   return true;
16287 }
16288 
16289 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16290                                            SelectionDAG &DAG) const {
16291   MachineFunction &MF = DAG.getMachineFunction();
16292   MachineFrameInfo &MFI = MF.getFrameInfo();
16293   MFI.setReturnAddressIsTaken(true);
16294 
16295   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16296     return SDValue();
16297 
16298   SDLoc dl(Op);
16299   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16300 
16301   // Make sure the function does not optimize away the store of the RA to
16302   // the stack.
16303   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16304   FuncInfo->setLRStoreRequired();
16305   bool isPPC64 = Subtarget.isPPC64();
16306   auto PtrVT = getPointerTy(MF.getDataLayout());
16307 
16308   if (Depth > 0) {
16309     // The link register (return address) is saved in the caller's frame
16310     // not the callee's stack frame. So we must get the caller's frame
16311     // address and load the return address at the LR offset from there.
16312     SDValue FrameAddr =
16313         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16314                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16315     SDValue Offset =
16316         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16317                         isPPC64 ? MVT::i64 : MVT::i32);
16318     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16319                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16320                        MachinePointerInfo());
16321   }
16322 
16323   // Just load the return address off the stack.
16324   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16325   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16326                      MachinePointerInfo());
16327 }
16328 
16329 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16330                                           SelectionDAG &DAG) const {
16331   SDLoc dl(Op);
16332   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16333 
16334   MachineFunction &MF = DAG.getMachineFunction();
16335   MachineFrameInfo &MFI = MF.getFrameInfo();
16336   MFI.setFrameAddressIsTaken(true);
16337 
16338   EVT PtrVT = getPointerTy(MF.getDataLayout());
16339   bool isPPC64 = PtrVT == MVT::i64;
16340 
16341   // Naked functions never have a frame pointer, and so we use r1. For all
16342   // other functions, this decision must be delayed until during PEI.
16343   unsigned FrameReg;
16344   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16345     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16346   else
16347     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16348 
16349   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16350                                          PtrVT);
16351   while (Depth--)
16352     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16353                             FrameAddr, MachinePointerInfo());
16354   return FrameAddr;
16355 }
16356 
16357 // FIXME? Maybe this could be a TableGen attribute on some registers and
16358 // this table could be generated automatically from RegInfo.
16359 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16360                                               const MachineFunction &MF) const {
16361   bool isPPC64 = Subtarget.isPPC64();
16362 
16363   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16364   if (!is64Bit && VT != LLT::scalar(32))
16365     report_fatal_error("Invalid register global variable type");
16366 
16367   Register Reg = StringSwitch<Register>(RegName)
16368                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16369                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16370                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16371                      .Default(Register());
16372 
16373   if (Reg)
16374     return Reg;
16375   report_fatal_error("Invalid register name global variable");
16376 }
16377 
16378 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16379   // 32-bit SVR4 ABI access everything as got-indirect.
16380   if (Subtarget.is32BitELFABI())
16381     return true;
16382 
16383   // AIX accesses everything indirectly through the TOC, which is similar to
16384   // the GOT.
16385   if (Subtarget.isAIXABI())
16386     return true;
16387 
16388   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16389   // If it is small or large code model, module locals are accessed
16390   // indirectly by loading their address from .toc/.got.
16391   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16392     return true;
16393 
16394   // JumpTable and BlockAddress are accessed as got-indirect.
16395   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16396     return true;
16397 
16398   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16399     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16400 
16401   return false;
16402 }
16403 
16404 bool
16405 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16406   // The PowerPC target isn't yet aware of offsets.
16407   return false;
16408 }
16409 
16410 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16411                                            const CallInst &I,
16412                                            MachineFunction &MF,
16413                                            unsigned Intrinsic) const {
16414   switch (Intrinsic) {
16415   case Intrinsic::ppc_atomicrmw_xchg_i128:
16416   case Intrinsic::ppc_atomicrmw_add_i128:
16417   case Intrinsic::ppc_atomicrmw_sub_i128:
16418   case Intrinsic::ppc_atomicrmw_nand_i128:
16419   case Intrinsic::ppc_atomicrmw_and_i128:
16420   case Intrinsic::ppc_atomicrmw_or_i128:
16421   case Intrinsic::ppc_atomicrmw_xor_i128:
16422   case Intrinsic::ppc_cmpxchg_i128:
16423     Info.opc = ISD::INTRINSIC_W_CHAIN;
16424     Info.memVT = MVT::i128;
16425     Info.ptrVal = I.getArgOperand(0);
16426     Info.offset = 0;
16427     Info.align = Align(16);
16428     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16429                  MachineMemOperand::MOVolatile;
16430     return true;
16431   case Intrinsic::ppc_atomic_load_i128:
16432     Info.opc = ISD::INTRINSIC_W_CHAIN;
16433     Info.memVT = MVT::i128;
16434     Info.ptrVal = I.getArgOperand(0);
16435     Info.offset = 0;
16436     Info.align = Align(16);
16437     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16438     return true;
16439   case Intrinsic::ppc_atomic_store_i128:
16440     Info.opc = ISD::INTRINSIC_VOID;
16441     Info.memVT = MVT::i128;
16442     Info.ptrVal = I.getArgOperand(2);
16443     Info.offset = 0;
16444     Info.align = Align(16);
16445     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16446     return true;
16447   case Intrinsic::ppc_altivec_lvx:
16448   case Intrinsic::ppc_altivec_lvxl:
16449   case Intrinsic::ppc_altivec_lvebx:
16450   case Intrinsic::ppc_altivec_lvehx:
16451   case Intrinsic::ppc_altivec_lvewx:
16452   case Intrinsic::ppc_vsx_lxvd2x:
16453   case Intrinsic::ppc_vsx_lxvw4x:
16454   case Intrinsic::ppc_vsx_lxvd2x_be:
16455   case Intrinsic::ppc_vsx_lxvw4x_be:
16456   case Intrinsic::ppc_vsx_lxvl:
16457   case Intrinsic::ppc_vsx_lxvll: {
16458     EVT VT;
16459     switch (Intrinsic) {
16460     case Intrinsic::ppc_altivec_lvebx:
16461       VT = MVT::i8;
16462       break;
16463     case Intrinsic::ppc_altivec_lvehx:
16464       VT = MVT::i16;
16465       break;
16466     case Intrinsic::ppc_altivec_lvewx:
16467       VT = MVT::i32;
16468       break;
16469     case Intrinsic::ppc_vsx_lxvd2x:
16470     case Intrinsic::ppc_vsx_lxvd2x_be:
16471       VT = MVT::v2f64;
16472       break;
16473     default:
16474       VT = MVT::v4i32;
16475       break;
16476     }
16477 
16478     Info.opc = ISD::INTRINSIC_W_CHAIN;
16479     Info.memVT = VT;
16480     Info.ptrVal = I.getArgOperand(0);
16481     Info.offset = -VT.getStoreSize()+1;
16482     Info.size = 2*VT.getStoreSize()-1;
16483     Info.align = Align(1);
16484     Info.flags = MachineMemOperand::MOLoad;
16485     return true;
16486   }
16487   case Intrinsic::ppc_altivec_stvx:
16488   case Intrinsic::ppc_altivec_stvxl:
16489   case Intrinsic::ppc_altivec_stvebx:
16490   case Intrinsic::ppc_altivec_stvehx:
16491   case Intrinsic::ppc_altivec_stvewx:
16492   case Intrinsic::ppc_vsx_stxvd2x:
16493   case Intrinsic::ppc_vsx_stxvw4x:
16494   case Intrinsic::ppc_vsx_stxvd2x_be:
16495   case Intrinsic::ppc_vsx_stxvw4x_be:
16496   case Intrinsic::ppc_vsx_stxvl:
16497   case Intrinsic::ppc_vsx_stxvll: {
16498     EVT VT;
16499     switch (Intrinsic) {
16500     case Intrinsic::ppc_altivec_stvebx:
16501       VT = MVT::i8;
16502       break;
16503     case Intrinsic::ppc_altivec_stvehx:
16504       VT = MVT::i16;
16505       break;
16506     case Intrinsic::ppc_altivec_stvewx:
16507       VT = MVT::i32;
16508       break;
16509     case Intrinsic::ppc_vsx_stxvd2x:
16510     case Intrinsic::ppc_vsx_stxvd2x_be:
16511       VT = MVT::v2f64;
16512       break;
16513     default:
16514       VT = MVT::v4i32;
16515       break;
16516     }
16517 
16518     Info.opc = ISD::INTRINSIC_VOID;
16519     Info.memVT = VT;
16520     Info.ptrVal = I.getArgOperand(1);
16521     Info.offset = -VT.getStoreSize()+1;
16522     Info.size = 2*VT.getStoreSize()-1;
16523     Info.align = Align(1);
16524     Info.flags = MachineMemOperand::MOStore;
16525     return true;
16526   }
16527   default:
16528     break;
16529   }
16530 
16531   return false;
16532 }
16533 
16534 /// It returns EVT::Other if the type should be determined using generic
16535 /// target-independent logic.
16536 EVT PPCTargetLowering::getOptimalMemOpType(
16537     const MemOp &Op, const AttributeList &FuncAttributes) const {
16538   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16539     // We should use Altivec/VSX loads and stores when available. For unaligned
16540     // addresses, unaligned VSX loads are only fast starting with the P8.
16541     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16542         (Op.isAligned(Align(16)) ||
16543          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16544       return MVT::v4i32;
16545   }
16546 
16547   if (Subtarget.isPPC64()) {
16548     return MVT::i64;
16549   }
16550 
16551   return MVT::i32;
16552 }
16553 
16554 /// Returns true if it is beneficial to convert a load of a constant
16555 /// to just the constant itself.
16556 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16557                                                           Type *Ty) const {
16558   assert(Ty->isIntegerTy());
16559 
16560   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16561   return !(BitSize == 0 || BitSize > 64);
16562 }
16563 
16564 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16565   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16566     return false;
16567   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16568   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16569   return NumBits1 == 64 && NumBits2 == 32;
16570 }
16571 
16572 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16573   if (!VT1.isInteger() || !VT2.isInteger())
16574     return false;
16575   unsigned NumBits1 = VT1.getSizeInBits();
16576   unsigned NumBits2 = VT2.getSizeInBits();
16577   return NumBits1 == 64 && NumBits2 == 32;
16578 }
16579 
16580 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16581   // Generally speaking, zexts are not free, but they are free when they can be
16582   // folded with other operations.
16583   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16584     EVT MemVT = LD->getMemoryVT();
16585     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16586          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16587         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16588          LD->getExtensionType() == ISD::ZEXTLOAD))
16589       return true;
16590   }
16591 
16592   // FIXME: Add other cases...
16593   //  - 32-bit shifts with a zext to i64
16594   //  - zext after ctlz, bswap, etc.
16595   //  - zext after and by a constant mask
16596 
16597   return TargetLowering::isZExtFree(Val, VT2);
16598 }
16599 
16600 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16601   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16602          "invalid fpext types");
16603   // Extending to float128 is not free.
16604   if (DestVT == MVT::f128)
16605     return false;
16606   return true;
16607 }
16608 
16609 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16610   return isInt<16>(Imm) || isUInt<16>(Imm);
16611 }
16612 
16613 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16614   return isInt<16>(Imm) || isUInt<16>(Imm);
16615 }
16616 
16617 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16618                                                        MachineMemOperand::Flags,
16619                                                        bool *Fast) const {
16620   if (DisablePPCUnaligned)
16621     return false;
16622 
16623   // PowerPC supports unaligned memory access for simple non-vector types.
16624   // Although accessing unaligned addresses is not as efficient as accessing
16625   // aligned addresses, it is generally more efficient than manual expansion,
16626   // and generally only traps for software emulation when crossing page
16627   // boundaries.
16628 
16629   if (!VT.isSimple())
16630     return false;
16631 
16632   if (VT.isFloatingPoint() && !VT.isVector() &&
16633       !Subtarget.allowsUnalignedFPAccess())
16634     return false;
16635 
16636   if (VT.getSimpleVT().isVector()) {
16637     if (Subtarget.hasVSX()) {
16638       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16639           VT != MVT::v4f32 && VT != MVT::v4i32)
16640         return false;
16641     } else {
16642       return false;
16643     }
16644   }
16645 
16646   if (VT == MVT::ppcf128)
16647     return false;
16648 
16649   if (Fast)
16650     *Fast = true;
16651 
16652   return true;
16653 }
16654 
16655 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16656                                                SDValue C) const {
16657   // Check integral scalar types.
16658   if (!VT.isScalarInteger())
16659     return false;
16660   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16661     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16662       return false;
16663     // This transformation will generate >= 2 operations. But the following
16664     // cases will generate <= 2 instructions during ISEL. So exclude them.
16665     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16666     // HW instruction, ie. MULLI
16667     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16668     // instruction is needed than case 1, ie. MULLI and RLDICR
16669     int64_t Imm = ConstNode->getSExtValue();
16670     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16671     Imm >>= Shift;
16672     if (isInt<16>(Imm))
16673       return false;
16674     uint64_t UImm = static_cast<uint64_t>(Imm);
16675     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16676         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16677       return true;
16678   }
16679   return false;
16680 }
16681 
16682 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16683                                                    EVT VT) const {
16684   return isFMAFasterThanFMulAndFAdd(
16685       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16686 }
16687 
16688 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16689                                                    Type *Ty) const {
16690   switch (Ty->getScalarType()->getTypeID()) {
16691   case Type::FloatTyID:
16692   case Type::DoubleTyID:
16693     return true;
16694   case Type::FP128TyID:
16695     return Subtarget.hasP9Vector();
16696   default:
16697     return false;
16698   }
16699 }
16700 
16701 // FIXME: add more patterns which are not profitable to hoist.
16702 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16703   if (!I->hasOneUse())
16704     return true;
16705 
16706   Instruction *User = I->user_back();
16707   assert(User && "A single use instruction with no uses.");
16708 
16709   switch (I->getOpcode()) {
16710   case Instruction::FMul: {
16711     // Don't break FMA, PowerPC prefers FMA.
16712     if (User->getOpcode() != Instruction::FSub &&
16713         User->getOpcode() != Instruction::FAdd)
16714       return true;
16715 
16716     const TargetOptions &Options = getTargetMachine().Options;
16717     const Function *F = I->getFunction();
16718     const DataLayout &DL = F->getParent()->getDataLayout();
16719     Type *Ty = User->getOperand(0)->getType();
16720 
16721     return !(
16722         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16723         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16724         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16725   }
16726   case Instruction::Load: {
16727     // Don't break "store (load float*)" pattern, this pattern will be combined
16728     // to "store (load int32)" in later InstCombine pass. See function
16729     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16730     // cycles than loading a 32 bit integer.
16731     LoadInst *LI = cast<LoadInst>(I);
16732     // For the loads that combineLoadToOperationType does nothing, like
16733     // ordered load, it should be profitable to hoist them.
16734     // For swifterror load, it can only be used for pointer to pointer type, so
16735     // later type check should get rid of this case.
16736     if (!LI->isUnordered())
16737       return true;
16738 
16739     if (User->getOpcode() != Instruction::Store)
16740       return true;
16741 
16742     if (I->getType()->getTypeID() != Type::FloatTyID)
16743       return true;
16744 
16745     return false;
16746   }
16747   default:
16748     return true;
16749   }
16750   return true;
16751 }
16752 
16753 const MCPhysReg *
16754 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16755   // LR is a callee-save register, but we must treat it as clobbered by any call
16756   // site. Hence we include LR in the scratch registers, which are in turn added
16757   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16758   // to CTR, which is used by any indirect call.
16759   static const MCPhysReg ScratchRegs[] = {
16760     PPC::X12, PPC::LR8, PPC::CTR8, 0
16761   };
16762 
16763   return ScratchRegs;
16764 }
16765 
16766 Register PPCTargetLowering::getExceptionPointerRegister(
16767     const Constant *PersonalityFn) const {
16768   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16769 }
16770 
16771 Register PPCTargetLowering::getExceptionSelectorRegister(
16772     const Constant *PersonalityFn) const {
16773   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16774 }
16775 
16776 bool
16777 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16778                      EVT VT , unsigned DefinedValues) const {
16779   if (VT == MVT::v2i64)
16780     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16781 
16782   if (Subtarget.hasVSX())
16783     return true;
16784 
16785   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16786 }
16787 
16788 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16789   if (DisableILPPref || Subtarget.enableMachineScheduler())
16790     return TargetLowering::getSchedulingPreference(N);
16791 
16792   return Sched::ILP;
16793 }
16794 
16795 // Create a fast isel object.
16796 FastISel *
16797 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16798                                   const TargetLibraryInfo *LibInfo) const {
16799   return PPC::createFastISel(FuncInfo, LibInfo);
16800 }
16801 
16802 // 'Inverted' means the FMA opcode after negating one multiplicand.
16803 // For example, (fma -a b c) = (fnmsub a b c)
16804 static unsigned invertFMAOpcode(unsigned Opc) {
16805   switch (Opc) {
16806   default:
16807     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16808   case ISD::FMA:
16809     return PPCISD::FNMSUB;
16810   case PPCISD::FNMSUB:
16811     return ISD::FMA;
16812   }
16813 }
16814 
16815 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16816                                                 bool LegalOps, bool OptForSize,
16817                                                 NegatibleCost &Cost,
16818                                                 unsigned Depth) const {
16819   if (Depth > SelectionDAG::MaxRecursionDepth)
16820     return SDValue();
16821 
16822   unsigned Opc = Op.getOpcode();
16823   EVT VT = Op.getValueType();
16824   SDNodeFlags Flags = Op.getNode()->getFlags();
16825 
16826   switch (Opc) {
16827   case PPCISD::FNMSUB:
16828     if (!Op.hasOneUse() || !isTypeLegal(VT))
16829       break;
16830 
16831     const TargetOptions &Options = getTargetMachine().Options;
16832     SDValue N0 = Op.getOperand(0);
16833     SDValue N1 = Op.getOperand(1);
16834     SDValue N2 = Op.getOperand(2);
16835     SDLoc Loc(Op);
16836 
16837     NegatibleCost N2Cost = NegatibleCost::Expensive;
16838     SDValue NegN2 =
16839         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16840 
16841     if (!NegN2)
16842       return SDValue();
16843 
16844     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16845     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16846     // These transformations may change sign of zeroes. For example,
16847     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16848     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16849       // Try and choose the cheaper one to negate.
16850       NegatibleCost N0Cost = NegatibleCost::Expensive;
16851       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16852                                            N0Cost, Depth + 1);
16853 
16854       NegatibleCost N1Cost = NegatibleCost::Expensive;
16855       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16856                                            N1Cost, Depth + 1);
16857 
16858       if (NegN0 && N0Cost <= N1Cost) {
16859         Cost = std::min(N0Cost, N2Cost);
16860         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16861       } else if (NegN1) {
16862         Cost = std::min(N1Cost, N2Cost);
16863         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16864       }
16865     }
16866 
16867     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16868     if (isOperationLegal(ISD::FMA, VT)) {
16869       Cost = N2Cost;
16870       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16871     }
16872 
16873     break;
16874   }
16875 
16876   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16877                                               Cost, Depth);
16878 }
16879 
16880 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16881 bool PPCTargetLowering::useLoadStackGuardNode() const {
16882   if (!Subtarget.isTargetLinux())
16883     return TargetLowering::useLoadStackGuardNode();
16884   return true;
16885 }
16886 
16887 // Override to disable global variable loading on Linux and insert AIX canary
16888 // word declaration.
16889 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16890   if (Subtarget.isAIXABI()) {
16891     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16892                         Type::getInt8PtrTy(M.getContext()));
16893     return;
16894   }
16895   if (!Subtarget.isTargetLinux())
16896     return TargetLowering::insertSSPDeclarations(M);
16897 }
16898 
16899 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16900   if (Subtarget.isAIXABI())
16901     return M.getGlobalVariable(AIXSSPCanaryWordName);
16902   return TargetLowering::getSDagStackGuard(M);
16903 }
16904 
16905 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16906                                      bool ForCodeSize) const {
16907   if (!VT.isSimple() || !Subtarget.hasVSX())
16908     return false;
16909 
16910   switch(VT.getSimpleVT().SimpleTy) {
16911   default:
16912     // For FP types that are currently not supported by PPC backend, return
16913     // false. Examples: f16, f80.
16914     return false;
16915   case MVT::f32:
16916   case MVT::f64:
16917     if (Subtarget.hasPrefixInstrs()) {
16918       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16919       return true;
16920     }
16921     LLVM_FALLTHROUGH;
16922   case MVT::ppcf128:
16923     return Imm.isPosZero();
16924   }
16925 }
16926 
16927 // For vector shift operation op, fold
16928 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16929 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16930                                   SelectionDAG &DAG) {
16931   SDValue N0 = N->getOperand(0);
16932   SDValue N1 = N->getOperand(1);
16933   EVT VT = N0.getValueType();
16934   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16935   unsigned Opcode = N->getOpcode();
16936   unsigned TargetOpcode;
16937 
16938   switch (Opcode) {
16939   default:
16940     llvm_unreachable("Unexpected shift operation");
16941   case ISD::SHL:
16942     TargetOpcode = PPCISD::SHL;
16943     break;
16944   case ISD::SRL:
16945     TargetOpcode = PPCISD::SRL;
16946     break;
16947   case ISD::SRA:
16948     TargetOpcode = PPCISD::SRA;
16949     break;
16950   }
16951 
16952   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16953       N1->getOpcode() == ISD::AND)
16954     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16955       if (Mask->getZExtValue() == OpSizeInBits - 1)
16956         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16957 
16958   return SDValue();
16959 }
16960 
16961 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16962   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16963     return Value;
16964 
16965   SDValue N0 = N->getOperand(0);
16966   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16967   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16968       N0.getOpcode() != ISD::SIGN_EXTEND ||
16969       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16970       N->getValueType(0) != MVT::i64)
16971     return SDValue();
16972 
16973   // We can't save an operation here if the value is already extended, and
16974   // the existing shift is easier to combine.
16975   SDValue ExtsSrc = N0.getOperand(0);
16976   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16977       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16978     return SDValue();
16979 
16980   SDLoc DL(N0);
16981   SDValue ShiftBy = SDValue(CN1, 0);
16982   // We want the shift amount to be i32 on the extswli, but the shift could
16983   // have an i64.
16984   if (ShiftBy.getValueType() == MVT::i64)
16985     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16986 
16987   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16988                          ShiftBy);
16989 }
16990 
16991 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16992   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16993     return Value;
16994 
16995   return SDValue();
16996 }
16997 
16998 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16999   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
17000     return Value;
17001 
17002   return SDValue();
17003 }
17004 
17005 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
17006 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
17007 // When C is zero, the equation (addi Z, -C) can be simplified to Z
17008 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
17009 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
17010                                  const PPCSubtarget &Subtarget) {
17011   if (!Subtarget.isPPC64())
17012     return SDValue();
17013 
17014   SDValue LHS = N->getOperand(0);
17015   SDValue RHS = N->getOperand(1);
17016 
17017   auto isZextOfCompareWithConstant = [](SDValue Op) {
17018     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
17019         Op.getValueType() != MVT::i64)
17020       return false;
17021 
17022     SDValue Cmp = Op.getOperand(0);
17023     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
17024         Cmp.getOperand(0).getValueType() != MVT::i64)
17025       return false;
17026 
17027     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
17028       int64_t NegConstant = 0 - Constant->getSExtValue();
17029       // Due to the limitations of the addi instruction,
17030       // -C is required to be [-32768, 32767].
17031       return isInt<16>(NegConstant);
17032     }
17033 
17034     return false;
17035   };
17036 
17037   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
17038   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
17039 
17040   // If there is a pattern, canonicalize a zext operand to the RHS.
17041   if (LHSHasPattern && !RHSHasPattern)
17042     std::swap(LHS, RHS);
17043   else if (!LHSHasPattern && !RHSHasPattern)
17044     return SDValue();
17045 
17046   SDLoc DL(N);
17047   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
17048   SDValue Cmp = RHS.getOperand(0);
17049   SDValue Z = Cmp.getOperand(0);
17050   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
17051   int64_t NegConstant = 0 - Constant->getSExtValue();
17052 
17053   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
17054   default: break;
17055   case ISD::SETNE: {
17056     //                                 when C == 0
17057     //                             --> addze X, (addic Z, -1).carry
17058     //                            /
17059     // add X, (zext(setne Z, C))--
17060     //                            \    when -32768 <= -C <= 32767 && C != 0
17061     //                             --> addze X, (addic (addi Z, -C), -1).carry
17062     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17063                               DAG.getConstant(NegConstant, DL, MVT::i64));
17064     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17065     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17066                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
17067     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17068                        SDValue(Addc.getNode(), 1));
17069     }
17070   case ISD::SETEQ: {
17071     //                                 when C == 0
17072     //                             --> addze X, (subfic Z, 0).carry
17073     //                            /
17074     // add X, (zext(sete  Z, C))--
17075     //                            \    when -32768 <= -C <= 32767 && C != 0
17076     //                             --> addze X, (subfic (addi Z, -C), 0).carry
17077     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17078                               DAG.getConstant(NegConstant, DL, MVT::i64));
17079     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17080     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17081                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
17082     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17083                        SDValue(Subc.getNode(), 1));
17084     }
17085   }
17086 
17087   return SDValue();
17088 }
17089 
17090 // Transform
17091 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17092 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17093 // In this case both C1 and C2 must be known constants.
17094 // C1+C2 must fit into a 34 bit signed integer.
17095 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17096                                           const PPCSubtarget &Subtarget) {
17097   if (!Subtarget.isUsingPCRelativeCalls())
17098     return SDValue();
17099 
17100   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17101   // If we find that node try to cast the Global Address and the Constant.
17102   SDValue LHS = N->getOperand(0);
17103   SDValue RHS = N->getOperand(1);
17104 
17105   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17106     std::swap(LHS, RHS);
17107 
17108   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17109     return SDValue();
17110 
17111   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17112   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17113   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17114 
17115   // Check that both casts succeeded.
17116   if (!GSDN || !ConstNode)
17117     return SDValue();
17118 
17119   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17120   SDLoc DL(GSDN);
17121 
17122   // The signed int offset needs to fit in 34 bits.
17123   if (!isInt<34>(NewOffset))
17124     return SDValue();
17125 
17126   // The new global address is a copy of the old global address except
17127   // that it has the updated Offset.
17128   SDValue GA =
17129       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17130                                  NewOffset, GSDN->getTargetFlags());
17131   SDValue MatPCRel =
17132       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17133   return MatPCRel;
17134 }
17135 
17136 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17137   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17138     return Value;
17139 
17140   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17141     return Value;
17142 
17143   return SDValue();
17144 }
17145 
17146 // Detect TRUNCATE operations on bitcasts of float128 values.
17147 // What we are looking for here is the situtation where we extract a subset
17148 // of bits from a 128 bit float.
17149 // This can be of two forms:
17150 // 1) BITCAST of f128 feeding TRUNCATE
17151 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17152 // The reason this is required is because we do not have a legal i128 type
17153 // and so we want to prevent having to store the f128 and then reload part
17154 // of it.
17155 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17156                                            DAGCombinerInfo &DCI) const {
17157   // If we are using CRBits then try that first.
17158   if (Subtarget.useCRBits()) {
17159     // Check if CRBits did anything and return that if it did.
17160     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17161       return CRTruncValue;
17162   }
17163 
17164   SDLoc dl(N);
17165   SDValue Op0 = N->getOperand(0);
17166 
17167   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17168   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17169     EVT VT = N->getValueType(0);
17170     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17171       return SDValue();
17172     SDValue Sub = Op0.getOperand(0);
17173     if (Sub.getOpcode() == ISD::SUB) {
17174       SDValue SubOp0 = Sub.getOperand(0);
17175       SDValue SubOp1 = Sub.getOperand(1);
17176       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17177           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17178         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17179                                SubOp1.getOperand(0),
17180                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17181       }
17182     }
17183   }
17184 
17185   // Looking for a truncate of i128 to i64.
17186   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17187     return SDValue();
17188 
17189   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17190 
17191   // SRL feeding TRUNCATE.
17192   if (Op0.getOpcode() == ISD::SRL) {
17193     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17194     // The right shift has to be by 64 bits.
17195     if (!ConstNode || ConstNode->getZExtValue() != 64)
17196       return SDValue();
17197 
17198     // Switch the element number to extract.
17199     EltToExtract = EltToExtract ? 0 : 1;
17200     // Update Op0 past the SRL.
17201     Op0 = Op0.getOperand(0);
17202   }
17203 
17204   // BITCAST feeding a TRUNCATE possibly via SRL.
17205   if (Op0.getOpcode() == ISD::BITCAST &&
17206       Op0.getValueType() == MVT::i128 &&
17207       Op0.getOperand(0).getValueType() == MVT::f128) {
17208     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17209     return DCI.DAG.getNode(
17210         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17211         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17212   }
17213   return SDValue();
17214 }
17215 
17216 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17217   SelectionDAG &DAG = DCI.DAG;
17218 
17219   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17220   if (!ConstOpOrElement)
17221     return SDValue();
17222 
17223   // An imul is usually smaller than the alternative sequence for legal type.
17224   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17225       isOperationLegal(ISD::MUL, N->getValueType(0)))
17226     return SDValue();
17227 
17228   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17229     switch (this->Subtarget.getCPUDirective()) {
17230     default:
17231       // TODO: enhance the condition for subtarget before pwr8
17232       return false;
17233     case PPC::DIR_PWR8:
17234       //  type        mul     add    shl
17235       // scalar        4       1      1
17236       // vector        7       2      2
17237       return true;
17238     case PPC::DIR_PWR9:
17239     case PPC::DIR_PWR10:
17240     case PPC::DIR_PWR_FUTURE:
17241       //  type        mul     add    shl
17242       // scalar        5       2      2
17243       // vector        7       2      2
17244 
17245       // The cycle RATIO of related operations are showed as a table above.
17246       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17247       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17248       // are 4, it is always profitable; but for 3 instrs patterns
17249       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17250       // So we should only do it for vector type.
17251       return IsAddOne && IsNeg ? VT.isVector() : true;
17252     }
17253   };
17254 
17255   EVT VT = N->getValueType(0);
17256   SDLoc DL(N);
17257 
17258   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17259   bool IsNeg = MulAmt.isNegative();
17260   APInt MulAmtAbs = MulAmt.abs();
17261 
17262   if ((MulAmtAbs - 1).isPowerOf2()) {
17263     // (mul x, 2^N + 1) => (add (shl x, N), x)
17264     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17265 
17266     if (!IsProfitable(IsNeg, true, VT))
17267       return SDValue();
17268 
17269     SDValue Op0 = N->getOperand(0);
17270     SDValue Op1 =
17271         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17272                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17273     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17274 
17275     if (!IsNeg)
17276       return Res;
17277 
17278     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17279   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17280     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17281     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17282 
17283     if (!IsProfitable(IsNeg, false, VT))
17284       return SDValue();
17285 
17286     SDValue Op0 = N->getOperand(0);
17287     SDValue Op1 =
17288         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17289                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17290 
17291     if (!IsNeg)
17292       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17293     else
17294       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17295 
17296   } else {
17297     return SDValue();
17298   }
17299 }
17300 
17301 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17302 // in combiner since we need to check SD flags and other subtarget features.
17303 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17304                                           DAGCombinerInfo &DCI) const {
17305   SDValue N0 = N->getOperand(0);
17306   SDValue N1 = N->getOperand(1);
17307   SDValue N2 = N->getOperand(2);
17308   SDNodeFlags Flags = N->getFlags();
17309   EVT VT = N->getValueType(0);
17310   SelectionDAG &DAG = DCI.DAG;
17311   const TargetOptions &Options = getTargetMachine().Options;
17312   unsigned Opc = N->getOpcode();
17313   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17314   bool LegalOps = !DCI.isBeforeLegalizeOps();
17315   SDLoc Loc(N);
17316 
17317   if (!isOperationLegal(ISD::FMA, VT))
17318     return SDValue();
17319 
17320   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17321   // since (fnmsub a b c)=-0 while c-ab=+0.
17322   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17323     return SDValue();
17324 
17325   // (fma (fneg a) b c) => (fnmsub a b c)
17326   // (fnmsub (fneg a) b c) => (fma a b c)
17327   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17328     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17329 
17330   // (fma a (fneg b) c) => (fnmsub a b c)
17331   // (fnmsub a (fneg b) c) => (fma a b c)
17332   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17333     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17334 
17335   return SDValue();
17336 }
17337 
17338 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17339   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17340   if (!Subtarget.is64BitELFABI())
17341     return false;
17342 
17343   // If not a tail call then no need to proceed.
17344   if (!CI->isTailCall())
17345     return false;
17346 
17347   // If sibling calls have been disabled and tail-calls aren't guaranteed
17348   // there is no reason to duplicate.
17349   auto &TM = getTargetMachine();
17350   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17351     return false;
17352 
17353   // Can't tail call a function called indirectly, or if it has variadic args.
17354   const Function *Callee = CI->getCalledFunction();
17355   if (!Callee || Callee->isVarArg())
17356     return false;
17357 
17358   // Make sure the callee and caller calling conventions are eligible for tco.
17359   const Function *Caller = CI->getParent()->getParent();
17360   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17361                                            CI->getCallingConv()))
17362       return false;
17363 
17364   // If the function is local then we have a good chance at tail-calling it
17365   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17366 }
17367 
17368 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17369   if (!Subtarget.hasVSX())
17370     return false;
17371   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17372     return true;
17373   return VT == MVT::f32 || VT == MVT::f64 ||
17374     VT == MVT::v4f32 || VT == MVT::v2f64;
17375 }
17376 
17377 bool PPCTargetLowering::
17378 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17379   const Value *Mask = AndI.getOperand(1);
17380   // If the mask is suitable for andi. or andis. we should sink the and.
17381   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17382     // Can't handle constants wider than 64-bits.
17383     if (CI->getBitWidth() > 64)
17384       return false;
17385     int64_t ConstVal = CI->getZExtValue();
17386     return isUInt<16>(ConstVal) ||
17387       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17388   }
17389 
17390   // For non-constant masks, we can always use the record-form and.
17391   return true;
17392 }
17393 
17394 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17395 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17396 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17397 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17398 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17399 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17400   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17401   assert(Subtarget.hasP9Altivec() &&
17402          "Only combine this when P9 altivec supported!");
17403   EVT VT = N->getValueType(0);
17404   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17405     return SDValue();
17406 
17407   SelectionDAG &DAG = DCI.DAG;
17408   SDLoc dl(N);
17409   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17410     // Even for signed integers, if it's known to be positive (as signed
17411     // integer) due to zero-extended inputs.
17412     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17413     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17414     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17415          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17416         (SubOpcd1 == ISD::ZERO_EXTEND ||
17417          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17418       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17419                          N->getOperand(0)->getOperand(0),
17420                          N->getOperand(0)->getOperand(1),
17421                          DAG.getTargetConstant(0, dl, MVT::i32));
17422     }
17423 
17424     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17425     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17426         N->getOperand(0).hasOneUse()) {
17427       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17428                          N->getOperand(0)->getOperand(0),
17429                          N->getOperand(0)->getOperand(1),
17430                          DAG.getTargetConstant(1, dl, MVT::i32));
17431     }
17432   }
17433 
17434   return SDValue();
17435 }
17436 
17437 // For type v4i32/v8ii16/v16i8, transform
17438 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17439 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17440 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17441 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17442 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17443                                           DAGCombinerInfo &DCI) const {
17444   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17445   assert(Subtarget.hasP9Altivec() &&
17446          "Only combine this when P9 altivec supported!");
17447 
17448   SelectionDAG &DAG = DCI.DAG;
17449   SDLoc dl(N);
17450   SDValue Cond = N->getOperand(0);
17451   SDValue TrueOpnd = N->getOperand(1);
17452   SDValue FalseOpnd = N->getOperand(2);
17453   EVT VT = N->getOperand(1).getValueType();
17454 
17455   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17456       FalseOpnd.getOpcode() != ISD::SUB)
17457     return SDValue();
17458 
17459   // ABSD only available for type v4i32/v8i16/v16i8
17460   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17461     return SDValue();
17462 
17463   // At least to save one more dependent computation
17464   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17465     return SDValue();
17466 
17467   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17468 
17469   // Can only handle unsigned comparison here
17470   switch (CC) {
17471   default:
17472     return SDValue();
17473   case ISD::SETUGT:
17474   case ISD::SETUGE:
17475     break;
17476   case ISD::SETULT:
17477   case ISD::SETULE:
17478     std::swap(TrueOpnd, FalseOpnd);
17479     break;
17480   }
17481 
17482   SDValue CmpOpnd1 = Cond.getOperand(0);
17483   SDValue CmpOpnd2 = Cond.getOperand(1);
17484 
17485   // SETCC CmpOpnd1 CmpOpnd2 cond
17486   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17487   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17488   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17489       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17490       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17491       FalseOpnd.getOperand(1) == CmpOpnd1) {
17492     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17493                        CmpOpnd1, CmpOpnd2,
17494                        DAG.getTargetConstant(0, dl, MVT::i32));
17495   }
17496 
17497   return SDValue();
17498 }
17499 
17500 /// getAddrModeForFlags - Based on the set of address flags, select the most
17501 /// optimal instruction format to match by.
17502 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17503   // This is not a node we should be handling here.
17504   if (Flags == PPC::MOF_None)
17505     return PPC::AM_None;
17506   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17507   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17508     if ((Flags & FlagSet) == FlagSet)
17509       return PPC::AM_DForm;
17510   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17511     if ((Flags & FlagSet) == FlagSet)
17512       return PPC::AM_DSForm;
17513   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17514     if ((Flags & FlagSet) == FlagSet)
17515       return PPC::AM_DQForm;
17516   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17517     if ((Flags & FlagSet) == FlagSet)
17518       return PPC::AM_PrefixDForm;
17519   // If no other forms are selected, return an X-Form as it is the most
17520   // general addressing mode.
17521   return PPC::AM_XForm;
17522 }
17523 
17524 /// Set alignment flags based on whether or not the Frame Index is aligned.
17525 /// Utilized when computing flags for address computation when selecting
17526 /// load and store instructions.
17527 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17528                                SelectionDAG &DAG) {
17529   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17530   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17531   if (!FI)
17532     return;
17533   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17534   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17535   // If this is (add $FI, $S16Imm), the alignment flags are already set
17536   // based on the immediate. We just need to clear the alignment flags
17537   // if the FI alignment is weaker.
17538   if ((FrameIndexAlign % 4) != 0)
17539     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17540   if ((FrameIndexAlign % 16) != 0)
17541     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17542   // If the address is a plain FrameIndex, set alignment flags based on
17543   // FI alignment.
17544   if (!IsAdd) {
17545     if ((FrameIndexAlign % 4) == 0)
17546       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17547     if ((FrameIndexAlign % 16) == 0)
17548       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17549   }
17550 }
17551 
17552 /// Given a node, compute flags that are used for address computation when
17553 /// selecting load and store instructions. The flags computed are stored in
17554 /// FlagSet. This function takes into account whether the node is a constant,
17555 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17556 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17557                                               SelectionDAG &DAG) {
17558   // Set the alignment flags for the node depending on if the node is
17559   // 4-byte or 16-byte aligned.
17560   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17561     if ((Imm & 0x3) == 0)
17562       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17563     if ((Imm & 0xf) == 0)
17564       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17565   };
17566 
17567   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17568     // All 32-bit constants can be computed as LIS + Disp.
17569     const APInt &ConstImm = CN->getAPIntValue();
17570     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17571       FlagSet |= PPC::MOF_AddrIsSImm32;
17572       SetAlignFlagsForImm(ConstImm.getZExtValue());
17573       setAlignFlagsForFI(N, FlagSet, DAG);
17574     }
17575     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17576       FlagSet |= PPC::MOF_RPlusSImm34;
17577     else // Let constant materialization handle large constants.
17578       FlagSet |= PPC::MOF_NotAddNorCst;
17579   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17580     // This address can be represented as an addition of:
17581     // - Register + Imm16 (possibly a multiple of 4/16)
17582     // - Register + Imm34
17583     // - Register + PPCISD::Lo
17584     // - Register + Register
17585     // In any case, we won't have to match this as Base + Zero.
17586     SDValue RHS = N.getOperand(1);
17587     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17588       const APInt &ConstImm = CN->getAPIntValue();
17589       if (ConstImm.isSignedIntN(16)) {
17590         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17591         SetAlignFlagsForImm(ConstImm.getZExtValue());
17592         setAlignFlagsForFI(N, FlagSet, DAG);
17593       }
17594       if (ConstImm.isSignedIntN(34))
17595         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17596       else
17597         FlagSet |= PPC::MOF_RPlusR; // Register.
17598     } else if (RHS.getOpcode() == PPCISD::Lo &&
17599                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17600       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17601     else
17602       FlagSet |= PPC::MOF_RPlusR;
17603   } else { // The address computation is not a constant or an addition.
17604     setAlignFlagsForFI(N, FlagSet, DAG);
17605     FlagSet |= PPC::MOF_NotAddNorCst;
17606   }
17607 }
17608 
17609 static bool isPCRelNode(SDValue N) {
17610   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17611       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17612       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17613       isValidPCRelNode<JumpTableSDNode>(N) ||
17614       isValidPCRelNode<BlockAddressSDNode>(N));
17615 }
17616 
17617 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17618 /// the address flags of the load/store instruction that is to be matched.
17619 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17620                                            SelectionDAG &DAG) const {
17621   unsigned FlagSet = PPC::MOF_None;
17622 
17623   // Compute subtarget flags.
17624   if (!Subtarget.hasP9Vector())
17625     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17626   else {
17627     FlagSet |= PPC::MOF_SubtargetP9;
17628     if (Subtarget.hasPrefixInstrs())
17629       FlagSet |= PPC::MOF_SubtargetP10;
17630   }
17631   if (Subtarget.hasSPE())
17632     FlagSet |= PPC::MOF_SubtargetSPE;
17633 
17634   // Check if we have a PCRel node and return early.
17635   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17636     return FlagSet;
17637 
17638   // If the node is the paired load/store intrinsics, compute flags for
17639   // address computation and return early.
17640   unsigned ParentOp = Parent->getOpcode();
17641   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17642                                (ParentOp == ISD::INTRINSIC_VOID))) {
17643     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17644     if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
17645       SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
17646                              ? Parent->getOperand(2)
17647                              : Parent->getOperand(3);
17648       computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17649       FlagSet |= PPC::MOF_Vector;
17650       return FlagSet;
17651     }
17652   }
17653 
17654   // Mark this as something we don't want to handle here if it is atomic
17655   // or pre-increment instruction.
17656   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17657     if (LSB->isIndexed())
17658       return PPC::MOF_None;
17659 
17660   // Compute in-memory type flags. This is based on if there are scalars,
17661   // floats or vectors.
17662   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17663   assert(MN && "Parent should be a MemSDNode!");
17664   EVT MemVT = MN->getMemoryVT();
17665   unsigned Size = MemVT.getSizeInBits();
17666   if (MemVT.isScalarInteger()) {
17667     assert(Size <= 128 &&
17668            "Not expecting scalar integers larger than 16 bytes!");
17669     if (Size < 32)
17670       FlagSet |= PPC::MOF_SubWordInt;
17671     else if (Size == 32)
17672       FlagSet |= PPC::MOF_WordInt;
17673     else
17674       FlagSet |= PPC::MOF_DoubleWordInt;
17675   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17676     if (Size == 128)
17677       FlagSet |= PPC::MOF_Vector;
17678     else if (Size == 256) {
17679       assert(Subtarget.pairedVectorMemops() &&
17680              "256-bit vectors are only available when paired vector memops is "
17681              "enabled!");
17682       FlagSet |= PPC::MOF_Vector;
17683     } else
17684       llvm_unreachable("Not expecting illegal vectors!");
17685   } else { // Floating point type: can be scalar, f128 or vector types.
17686     if (Size == 32 || Size == 64)
17687       FlagSet |= PPC::MOF_ScalarFloat;
17688     else if (MemVT == MVT::f128 || MemVT.isVector())
17689       FlagSet |= PPC::MOF_Vector;
17690     else
17691       llvm_unreachable("Not expecting illegal scalar floats!");
17692   }
17693 
17694   // Compute flags for address computation.
17695   computeFlagsForAddressComputation(N, FlagSet, DAG);
17696 
17697   // Compute type extension flags.
17698   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17699     switch (LN->getExtensionType()) {
17700     case ISD::SEXTLOAD:
17701       FlagSet |= PPC::MOF_SExt;
17702       break;
17703     case ISD::EXTLOAD:
17704     case ISD::ZEXTLOAD:
17705       FlagSet |= PPC::MOF_ZExt;
17706       break;
17707     case ISD::NON_EXTLOAD:
17708       FlagSet |= PPC::MOF_NoExt;
17709       break;
17710     }
17711   } else
17712     FlagSet |= PPC::MOF_NoExt;
17713 
17714   // For integers, no extension is the same as zero extension.
17715   // We set the extension mode to zero extension so we don't have
17716   // to add separate entries in AddrModesMap for loads and stores.
17717   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17718     FlagSet |= PPC::MOF_ZExt;
17719     FlagSet &= ~PPC::MOF_NoExt;
17720   }
17721 
17722   // If we don't have prefixed instructions, 34-bit constants should be
17723   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17724   bool IsNonP1034BitConst =
17725       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17726        FlagSet) == PPC::MOF_RPlusSImm34;
17727   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17728       IsNonP1034BitConst)
17729     FlagSet |= PPC::MOF_NotAddNorCst;
17730 
17731   return FlagSet;
17732 }
17733 
17734 /// SelectForceXFormMode - Given the specified address, force it to be
17735 /// represented as an indexed [r+r] operation (an XForm instruction).
17736 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17737                                                       SDValue &Base,
17738                                                       SelectionDAG &DAG) const {
17739 
17740   PPC::AddrMode Mode = PPC::AM_XForm;
17741   int16_t ForceXFormImm = 0;
17742   if (provablyDisjointOr(DAG, N) &&
17743       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17744     Disp = N.getOperand(0);
17745     Base = N.getOperand(1);
17746     return Mode;
17747   }
17748 
17749   // If the address is the result of an add, we will utilize the fact that the
17750   // address calculation includes an implicit add.  However, we can reduce
17751   // register pressure if we do not materialize a constant just for use as the
17752   // index register.  We only get rid of the add if it is not an add of a
17753   // value and a 16-bit signed constant and both have a single use.
17754   if (N.getOpcode() == ISD::ADD &&
17755       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17756        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17757     Disp = N.getOperand(0);
17758     Base = N.getOperand(1);
17759     return Mode;
17760   }
17761 
17762   // Otherwise, use R0 as the base register.
17763   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17764                          N.getValueType());
17765   Base = N;
17766 
17767   return Mode;
17768 }
17769 
17770 bool PPCTargetLowering::splitValueIntoRegisterParts(
17771     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
17772     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
17773   EVT ValVT = Val.getValueType();
17774   // If we are splitting a scalar integer into f64 parts (i.e. so they
17775   // can be placed into VFRC registers), we need to zero extend and
17776   // bitcast the values. This will ensure the value is placed into a
17777   // VSR using direct moves or stack operations as needed.
17778   if (PartVT == MVT::f64 &&
17779       (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
17780     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
17781     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
17782     Parts[0] = Val;
17783     return true;
17784   }
17785   return false;
17786 }
17787 
17788 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
17789                                           SelectionDAG &DAG) const {
17790   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17791   TargetLowering::CallLoweringInfo CLI(DAG);
17792   EVT RetVT = Op.getValueType();
17793   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
17794   SDValue Callee =
17795       DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
17796   bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
17797   TargetLowering::ArgListTy Args;
17798   TargetLowering::ArgListEntry Entry;
17799   for (const SDValue &N : Op->op_values()) {
17800     EVT ArgVT = N.getValueType();
17801     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17802     Entry.Node = N;
17803     Entry.Ty = ArgTy;
17804     Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
17805     Entry.IsZExt = !Entry.IsSExt;
17806     Args.push_back(Entry);
17807   }
17808 
17809   SDValue InChain = DAG.getEntryNode();
17810   SDValue TCChain = InChain;
17811   const Function &F = DAG.getMachineFunction().getFunction();
17812   bool isTailCall =
17813       TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
17814       (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
17815   if (isTailCall)
17816     InChain = TCChain;
17817   CLI.setDebugLoc(SDLoc(Op))
17818       .setChain(InChain)
17819       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
17820       .setTailCall(isTailCall)
17821       .setSExtResult(SignExtend)
17822       .setZExtResult(!SignExtend)
17823       .setIsPostTypeLegalization(true);
17824   return TLI.LowerCallTo(CLI).first;
17825 }
17826 
17827 SDValue PPCTargetLowering::lowerLibCallBasedOnType(
17828     const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
17829     SelectionDAG &DAG) const {
17830   if (Op.getValueType() == MVT::f32)
17831     return lowerToLibCall(LibCallFloatName, Op, DAG);
17832 
17833   if (Op.getValueType() == MVT::f64)
17834     return lowerToLibCall(LibCallDoubleName, Op, DAG);
17835 
17836   return SDValue();
17837 }
17838 
17839 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
17840   SDNodeFlags Flags = Op.getNode()->getFlags();
17841   return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
17842          Flags.hasNoNaNs() && Flags.hasNoInfs();
17843 }
17844 
17845 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
17846   return Op.getNode()->getFlags().hasApproximateFuncs();
17847 }
17848 
17849 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
17850                                             const char *LibCallFloatName,
17851                                             const char *LibCallDoubleNameFinite,
17852                                             const char *LibCallFloatNameFinite,
17853                                             SDValue Op,
17854                                             SelectionDAG &DAG) const {
17855   if (!isLowringToMASSSafe(Op))
17856     return SDValue();
17857 
17858   if (!isLowringToMASSFiniteSafe(Op))
17859     return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
17860                                    DAG);
17861 
17862   return lowerLibCallBasedOnType(LibCallFloatNameFinite,
17863                                  LibCallDoubleNameFinite, Op, DAG);
17864 }
17865 
17866 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
17867   return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
17868                           "__xl_powf_finite", Op, DAG);
17869 }
17870 
17871 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
17872   return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
17873                           "__xl_sinf_finite", Op, DAG);
17874 }
17875 
17876 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
17877   return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
17878                           "__xl_cosf_finite", Op, DAG);
17879 }
17880 
17881 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
17882   return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
17883                           "__xl_logf_finite", Op, DAG);
17884 }
17885 
17886 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
17887   return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
17888                           "__xl_log10f_finite", Op, DAG);
17889 }
17890 
17891 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
17892   return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
17893                           "__xl_expf_finite", Op, DAG);
17894 }
17895 
17896 // If we happen to match to an aligned D-Form, check if the Frame Index is
17897 // adequately aligned. If it is not, reset the mode to match to X-Form.
17898 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17899                                    PPC::AddrMode &Mode) {
17900   if (!isa<FrameIndexSDNode>(N))
17901     return;
17902   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17903       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17904     Mode = PPC::AM_XForm;
17905 }
17906 
17907 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17908 /// compute the address flags of the node, get the optimal address mode based
17909 /// on the flags, and set the Base and Disp based on the address mode.
17910 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17911                                                        SDValue N, SDValue &Disp,
17912                                                        SDValue &Base,
17913                                                        SelectionDAG &DAG,
17914                                                        MaybeAlign Align) const {
17915   SDLoc DL(Parent);
17916 
17917   // Compute the address flags.
17918   unsigned Flags = computeMOFlags(Parent, N, DAG);
17919 
17920   // Get the optimal address mode based on the Flags.
17921   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17922 
17923   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17924   // Select an X-Form load if it is not.
17925   setXFormForUnalignedFI(N, Flags, Mode);
17926 
17927   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17928   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17929     assert(Subtarget.isUsingPCRelativeCalls() &&
17930            "Must be using PC-Relative calls when a valid PC-Relative node is "
17931            "present!");
17932     Mode = PPC::AM_PCRel;
17933   }
17934 
17935   // Set Base and Disp accordingly depending on the address mode.
17936   switch (Mode) {
17937   case PPC::AM_DForm:
17938   case PPC::AM_DSForm:
17939   case PPC::AM_DQForm: {
17940     // This is a register plus a 16-bit immediate. The base will be the
17941     // register and the displacement will be the immediate unless it
17942     // isn't sufficiently aligned.
17943     if (Flags & PPC::MOF_RPlusSImm16) {
17944       SDValue Op0 = N.getOperand(0);
17945       SDValue Op1 = N.getOperand(1);
17946       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17947       if (!Align || isAligned(*Align, Imm)) {
17948         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17949         Base = Op0;
17950         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17951           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17952           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17953         }
17954         break;
17955       }
17956     }
17957     // This is a register plus the @lo relocation. The base is the register
17958     // and the displacement is the global address.
17959     else if (Flags & PPC::MOF_RPlusLo) {
17960       Disp = N.getOperand(1).getOperand(0); // The global address.
17961       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17962              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17963              Disp.getOpcode() == ISD::TargetConstantPool ||
17964              Disp.getOpcode() == ISD::TargetJumpTable);
17965       Base = N.getOperand(0);
17966       break;
17967     }
17968     // This is a constant address at most 32 bits. The base will be
17969     // zero or load-immediate-shifted and the displacement will be
17970     // the low 16 bits of the address.
17971     else if (Flags & PPC::MOF_AddrIsSImm32) {
17972       auto *CN = cast<ConstantSDNode>(N);
17973       EVT CNType = CN->getValueType(0);
17974       uint64_t CNImm = CN->getZExtValue();
17975       // If this address fits entirely in a 16-bit sext immediate field, codegen
17976       // this as "d, 0".
17977       int16_t Imm;
17978       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17979         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17980         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17981                                CNType);
17982         break;
17983       }
17984       // Handle 32-bit sext immediate with LIS + Addr mode.
17985       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17986           (!Align || isAligned(*Align, CNImm))) {
17987         int32_t Addr = (int32_t)CNImm;
17988         // Otherwise, break this down into LIS + Disp.
17989         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17990         Base =
17991             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17992         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17993         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17994         break;
17995       }
17996     }
17997     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17998     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17999     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
18000       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18001       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
18002     } else
18003       Base = N;
18004     break;
18005   }
18006   case PPC::AM_PrefixDForm: {
18007     int64_t Imm34 = 0;
18008     unsigned Opcode = N.getOpcode();
18009     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
18010         (isIntS34Immediate(N.getOperand(1), Imm34))) {
18011       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
18012       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18013       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
18014         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18015       else
18016         Base = N.getOperand(0);
18017     } else if (isIntS34Immediate(N, Imm34)) {
18018       // The address is a 34-bit signed immediate.
18019       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18020       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
18021     }
18022     break;
18023   }
18024   case PPC::AM_PCRel: {
18025     // When selecting PC-Relative instructions, "Base" is not utilized as
18026     // we select the address as [PC+imm].
18027     Disp = N;
18028     break;
18029   }
18030   case PPC::AM_None:
18031     break;
18032   default: { // By default, X-Form is always available to be selected.
18033     // When a frame index is not aligned, we also match by XForm.
18034     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
18035     Base = FI ? N : N.getOperand(1);
18036     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18037                                 N.getValueType())
18038               : N.getOperand(0);
18039     break;
18040   }
18041   }
18042   return Mode;
18043 }
18044 
18045 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
18046                                                  bool Return,
18047                                                  bool IsVarArg) const {
18048   switch (CC) {
18049   case CallingConv::Cold:
18050     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
18051   default:
18052     return CC_PPC64_ELF_FIS;
18053   }
18054 }
18055 
18056 TargetLowering::AtomicExpansionKind
18057 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18058   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18059   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18060     return AtomicExpansionKind::MaskedIntrinsic;
18061   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
18062 }
18063 
18064 TargetLowering::AtomicExpansionKind
18065 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18066   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
18067   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18068     return AtomicExpansionKind::MaskedIntrinsic;
18069   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
18070 }
18071 
18072 static Intrinsic::ID
18073 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
18074   switch (BinOp) {
18075   default:
18076     llvm_unreachable("Unexpected AtomicRMW BinOp");
18077   case AtomicRMWInst::Xchg:
18078     return Intrinsic::ppc_atomicrmw_xchg_i128;
18079   case AtomicRMWInst::Add:
18080     return Intrinsic::ppc_atomicrmw_add_i128;
18081   case AtomicRMWInst::Sub:
18082     return Intrinsic::ppc_atomicrmw_sub_i128;
18083   case AtomicRMWInst::And:
18084     return Intrinsic::ppc_atomicrmw_and_i128;
18085   case AtomicRMWInst::Or:
18086     return Intrinsic::ppc_atomicrmw_or_i128;
18087   case AtomicRMWInst::Xor:
18088     return Intrinsic::ppc_atomicrmw_xor_i128;
18089   case AtomicRMWInst::Nand:
18090     return Intrinsic::ppc_atomicrmw_nand_i128;
18091   }
18092 }
18093 
18094 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
18095     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
18096     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
18097   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18098          "Only support quadword now");
18099   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18100   Type *ValTy = Incr->getType();
18101   assert(ValTy->getPrimitiveSizeInBits() == 128);
18102   Function *RMW = Intrinsic::getDeclaration(
18103       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
18104   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18105   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
18106   Value *IncrHi =
18107       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
18108   Value *Addr =
18109       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18110   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
18111   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18112   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18113   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18114   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18115   return Builder.CreateOr(
18116       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18117 }
18118 
18119 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
18120     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
18121     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
18122   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18123          "Only support quadword now");
18124   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18125   Type *ValTy = CmpVal->getType();
18126   assert(ValTy->getPrimitiveSizeInBits() == 128);
18127   Function *IntCmpXchg =
18128       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
18129   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18130   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
18131   Value *CmpHi =
18132       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
18133   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
18134   Value *NewHi =
18135       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
18136   Value *Addr =
18137       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18138   emitLeadingFence(Builder, CI, Ord);
18139   Value *LoHi =
18140       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
18141   emitTrailingFence(Builder, CI, Ord);
18142   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18143   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18144   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18145   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18146   return Builder.CreateOr(
18147       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18148 }
18149