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);
1355   setTargetDAGCombine(ISD::SHL);
1356   setTargetDAGCombine(ISD::SRA);
1357   setTargetDAGCombine(ISD::SRL);
1358   setTargetDAGCombine(ISD::MUL);
1359   setTargetDAGCombine(ISD::FMA);
1360   setTargetDAGCombine(ISD::SINT_TO_FP);
1361   setTargetDAGCombine(ISD::BUILD_VECTOR);
1362   if (Subtarget.hasFPCVT())
1363     setTargetDAGCombine(ISD::UINT_TO_FP);
1364   setTargetDAGCombine(ISD::LOAD);
1365   setTargetDAGCombine(ISD::STORE);
1366   setTargetDAGCombine(ISD::BR_CC);
1367   if (Subtarget.useCRBits())
1368     setTargetDAGCombine(ISD::BRCOND);
1369   setTargetDAGCombine(ISD::BSWAP);
1370   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1371   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1372   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1373 
1374   setTargetDAGCombine(ISD::SIGN_EXTEND);
1375   setTargetDAGCombine(ISD::ZERO_EXTEND);
1376   setTargetDAGCombine(ISD::ANY_EXTEND);
1377 
1378   setTargetDAGCombine(ISD::TRUNCATE);
1379   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1380 
1381 
1382   if (Subtarget.useCRBits()) {
1383     setTargetDAGCombine(ISD::TRUNCATE);
1384     setTargetDAGCombine(ISD::SETCC);
1385     setTargetDAGCombine(ISD::SELECT_CC);
1386   }
1387 
1388   if (Subtarget.hasP9Altivec()) {
1389     setTargetDAGCombine(ISD::ABS);
1390     setTargetDAGCombine(ISD::VSELECT);
1391   }
1392 
1393   setLibcallName(RTLIB::LOG_F128, "logf128");
1394   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1395   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1396   setLibcallName(RTLIB::EXP_F128, "expf128");
1397   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1398   setLibcallName(RTLIB::SIN_F128, "sinf128");
1399   setLibcallName(RTLIB::COS_F128, "cosf128");
1400   setLibcallName(RTLIB::POW_F128, "powf128");
1401   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1402   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1403   setLibcallName(RTLIB::REM_F128, "fmodf128");
1404   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1405   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1406   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1407   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1408   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1409   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1410   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1411   setLibcallName(RTLIB::RINT_F128, "rintf128");
1412   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1413   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1414   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1415   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1416 
1417   // With 32 condition bits, we don't need to sink (and duplicate) compares
1418   // aggressively in CodeGenPrep.
1419   if (Subtarget.useCRBits()) {
1420     setHasMultipleConditionRegisters();
1421     setJumpIsExpensive();
1422   }
1423 
1424   setMinFunctionAlignment(Align(4));
1425 
1426   switch (Subtarget.getCPUDirective()) {
1427   default: break;
1428   case PPC::DIR_970:
1429   case PPC::DIR_A2:
1430   case PPC::DIR_E500:
1431   case PPC::DIR_E500mc:
1432   case PPC::DIR_E5500:
1433   case PPC::DIR_PWR4:
1434   case PPC::DIR_PWR5:
1435   case PPC::DIR_PWR5X:
1436   case PPC::DIR_PWR6:
1437   case PPC::DIR_PWR6X:
1438   case PPC::DIR_PWR7:
1439   case PPC::DIR_PWR8:
1440   case PPC::DIR_PWR9:
1441   case PPC::DIR_PWR10:
1442   case PPC::DIR_PWR_FUTURE:
1443     setPrefLoopAlignment(Align(16));
1444     setPrefFunctionAlignment(Align(16));
1445     break;
1446   }
1447 
1448   if (Subtarget.enableMachineScheduler())
1449     setSchedulingPreference(Sched::Source);
1450   else
1451     setSchedulingPreference(Sched::Hybrid);
1452 
1453   computeRegisterProperties(STI.getRegisterInfo());
1454 
1455   // The Freescale cores do better with aggressive inlining of memcpy and
1456   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1457   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1458       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1459     MaxStoresPerMemset = 32;
1460     MaxStoresPerMemsetOptSize = 16;
1461     MaxStoresPerMemcpy = 32;
1462     MaxStoresPerMemcpyOptSize = 8;
1463     MaxStoresPerMemmove = 32;
1464     MaxStoresPerMemmoveOptSize = 8;
1465   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1466     // The A2 also benefits from (very) aggressive inlining of memcpy and
1467     // friends. The overhead of a the function call, even when warm, can be
1468     // over one hundred cycles.
1469     MaxStoresPerMemset = 128;
1470     MaxStoresPerMemcpy = 128;
1471     MaxStoresPerMemmove = 128;
1472     MaxLoadsPerMemcmp = 128;
1473   } else {
1474     MaxLoadsPerMemcmp = 8;
1475     MaxLoadsPerMemcmpOptSize = 4;
1476   }
1477 
1478   IsStrictFPEnabled = true;
1479 
1480   // Let the subtarget (CPU) decide if a predictable select is more expensive
1481   // than the corresponding branch. This information is used in CGP to decide
1482   // when to convert selects into branches.
1483   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1484 }
1485 
1486 // *********************************** NOTE ************************************
1487 // For selecting load and store instructions, the addressing modes are defined
1488 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1489 // patterns to match the load the store instructions.
1490 //
1491 // The TD definitions for the addressing modes correspond to their respective
1492 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1493 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1494 // address mode flags of a particular node. Afterwards, the computed address
1495 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1496 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1497 // accordingly, based on the preferred addressing mode.
1498 //
1499 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1500 // MemOpFlags contains all the possible flags that can be used to compute the
1501 // optimal addressing mode for load and store instructions.
1502 // AddrMode contains all the possible load and store addressing modes available
1503 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1504 //
1505 // When adding new load and store instructions, it is possible that new address
1506 // flags may need to be added into MemOpFlags, and a new addressing mode will
1507 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1508 // of the minimal and main distinguishing address flags for the new load/store
1509 // instructions) will need to be added into initializeAddrModeMap() below.
1510 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1511 // need to be updated to account for selecting the optimal addressing mode.
1512 // *****************************************************************************
1513 /// Initialize the map that relates the different addressing modes of the load
1514 /// and store instructions to a set of flags. This ensures the load/store
1515 /// instruction is correctly matched during instruction selection.
1516 void PPCTargetLowering::initializeAddrModeMap() {
1517   AddrModesMap[PPC::AM_DForm] = {
1518       // LWZ, STW
1519       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1520       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1521       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1522       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1523       // LBZ, LHZ, STB, STH
1524       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1525       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1526       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1527       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1528       // LHA
1529       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1530       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1531       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1532       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1533       // LFS, LFD, STFS, STFD
1534       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1535       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1536       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1537       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1538   };
1539   AddrModesMap[PPC::AM_DSForm] = {
1540       // LWA
1541       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1542       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1543       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1544       // LD, STD
1545       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1546       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1547       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1548       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1549       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1550       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1551       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1552   };
1553   AddrModesMap[PPC::AM_DQForm] = {
1554       // LXV, STXV
1555       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1556       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1557       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1558   };
1559   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1560                                        PPC::MOF_SubtargetP10};
1561   // TODO: Add mapping for quadword load/store.
1562 }
1563 
1564 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1565 /// the desired ByVal argument alignment.
1566 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1567   if (MaxAlign == MaxMaxAlign)
1568     return;
1569   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1570     if (MaxMaxAlign >= 32 &&
1571         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1572       MaxAlign = Align(32);
1573     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1574              MaxAlign < 16)
1575       MaxAlign = Align(16);
1576   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1577     Align EltAlign;
1578     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1579     if (EltAlign > MaxAlign)
1580       MaxAlign = EltAlign;
1581   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1582     for (auto *EltTy : STy->elements()) {
1583       Align EltAlign;
1584       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1585       if (EltAlign > MaxAlign)
1586         MaxAlign = EltAlign;
1587       if (MaxAlign == MaxMaxAlign)
1588         break;
1589     }
1590   }
1591 }
1592 
1593 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1594 /// function arguments in the caller parameter area.
1595 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1596                                                   const DataLayout &DL) const {
1597   // 16byte and wider vectors are passed on 16byte boundary.
1598   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1599   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1600   if (Subtarget.hasAltivec())
1601     getMaxByValAlign(Ty, Alignment, Align(16));
1602   return Alignment.value();
1603 }
1604 
1605 bool PPCTargetLowering::useSoftFloat() const {
1606   return Subtarget.useSoftFloat();
1607 }
1608 
1609 bool PPCTargetLowering::hasSPE() const {
1610   return Subtarget.hasSPE();
1611 }
1612 
1613 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1614   return VT.isScalarInteger();
1615 }
1616 
1617 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1618   switch ((PPCISD::NodeType)Opcode) {
1619   case PPCISD::FIRST_NUMBER:    break;
1620   case PPCISD::FSEL:            return "PPCISD::FSEL";
1621   case PPCISD::XSMAXC:          return "PPCISD::XSMAXC";
1622   case PPCISD::XSMINC:          return "PPCISD::XSMINC";
1623   case PPCISD::FCFID:           return "PPCISD::FCFID";
1624   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1625   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1626   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1627   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1628   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1629   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1630   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1631   case PPCISD::FP_TO_UINT_IN_VSR:
1632                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1633   case PPCISD::FP_TO_SINT_IN_VSR:
1634                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1635   case PPCISD::FRE:             return "PPCISD::FRE";
1636   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1637   case PPCISD::FTSQRT:
1638     return "PPCISD::FTSQRT";
1639   case PPCISD::FSQRT:
1640     return "PPCISD::FSQRT";
1641   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1642   case PPCISD::VPERM:           return "PPCISD::VPERM";
1643   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1644   case PPCISD::XXSPLTI_SP_TO_DP:
1645     return "PPCISD::XXSPLTI_SP_TO_DP";
1646   case PPCISD::XXSPLTI32DX:
1647     return "PPCISD::XXSPLTI32DX";
1648   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1649   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1650   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1651   case PPCISD::CMPB:            return "PPCISD::CMPB";
1652   case PPCISD::Hi:              return "PPCISD::Hi";
1653   case PPCISD::Lo:              return "PPCISD::Lo";
1654   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1655   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1656   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1657   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1658   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1659   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1660   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1661   case PPCISD::SRL:             return "PPCISD::SRL";
1662   case PPCISD::SRA:             return "PPCISD::SRA";
1663   case PPCISD::SHL:             return "PPCISD::SHL";
1664   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1665   case PPCISD::CALL:            return "PPCISD::CALL";
1666   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1667   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1668   case PPCISD::CALL_RM:
1669     return "PPCISD::CALL_RM";
1670   case PPCISD::CALL_NOP_RM:
1671     return "PPCISD::CALL_NOP_RM";
1672   case PPCISD::CALL_NOTOC_RM:
1673     return "PPCISD::CALL_NOTOC_RM";
1674   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1675   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1676   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1677   case PPCISD::BCTRL_RM:
1678     return "PPCISD::BCTRL_RM";
1679   case PPCISD::BCTRL_LOAD_TOC_RM:
1680     return "PPCISD::BCTRL_LOAD_TOC_RM";
1681   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1682   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1683   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1684   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1685   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1686   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1687   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1688   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1689   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1690   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1691   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1692     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1693   case PPCISD::ANDI_rec_1_EQ_BIT:
1694     return "PPCISD::ANDI_rec_1_EQ_BIT";
1695   case PPCISD::ANDI_rec_1_GT_BIT:
1696     return "PPCISD::ANDI_rec_1_GT_BIT";
1697   case PPCISD::VCMP:            return "PPCISD::VCMP";
1698   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1699   case PPCISD::LBRX:            return "PPCISD::LBRX";
1700   case PPCISD::STBRX:           return "PPCISD::STBRX";
1701   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1702   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1703   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1704   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1705   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1706   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1707   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1708   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1709   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1710   case PPCISD::ST_VSR_SCAL_INT:
1711                                 return "PPCISD::ST_VSR_SCAL_INT";
1712   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1713   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1714   case PPCISD::BDZ:             return "PPCISD::BDZ";
1715   case PPCISD::MFFS:            return "PPCISD::MFFS";
1716   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1717   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1718   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1719   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1720   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1721   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1722   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1723   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1724   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1725   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1726   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1727   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1728   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1729   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1730   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1731   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1732   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1733   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1734   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1735   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1736   case PPCISD::PADDI_DTPREL:
1737     return "PPCISD::PADDI_DTPREL";
1738   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1739   case PPCISD::SC:              return "PPCISD::SC";
1740   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1741   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1742   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1743   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1744   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1745   case PPCISD::VABSD:           return "PPCISD::VABSD";
1746   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1747   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1748   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1749   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1750   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1751   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1752   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1753   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1754     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1755   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1756     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1757   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1758   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1759   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1760   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1761   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1762   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1763   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1764   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1765   case PPCISD::STRICT_FADDRTZ:
1766     return "PPCISD::STRICT_FADDRTZ";
1767   case PPCISD::STRICT_FCTIDZ:
1768     return "PPCISD::STRICT_FCTIDZ";
1769   case PPCISD::STRICT_FCTIWZ:
1770     return "PPCISD::STRICT_FCTIWZ";
1771   case PPCISD::STRICT_FCTIDUZ:
1772     return "PPCISD::STRICT_FCTIDUZ";
1773   case PPCISD::STRICT_FCTIWUZ:
1774     return "PPCISD::STRICT_FCTIWUZ";
1775   case PPCISD::STRICT_FCFID:
1776     return "PPCISD::STRICT_FCFID";
1777   case PPCISD::STRICT_FCFIDU:
1778     return "PPCISD::STRICT_FCFIDU";
1779   case PPCISD::STRICT_FCFIDS:
1780     return "PPCISD::STRICT_FCFIDS";
1781   case PPCISD::STRICT_FCFIDUS:
1782     return "PPCISD::STRICT_FCFIDUS";
1783   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1784   }
1785   return nullptr;
1786 }
1787 
1788 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1789                                           EVT VT) const {
1790   if (!VT.isVector())
1791     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1792 
1793   return VT.changeVectorElementTypeToInteger();
1794 }
1795 
1796 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1797   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1798   return true;
1799 }
1800 
1801 //===----------------------------------------------------------------------===//
1802 // Node matching predicates, for use by the tblgen matching code.
1803 //===----------------------------------------------------------------------===//
1804 
1805 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1806 static bool isFloatingPointZero(SDValue Op) {
1807   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1808     return CFP->getValueAPF().isZero();
1809   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1810     // Maybe this has already been legalized into the constant pool?
1811     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1812       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1813         return CFP->getValueAPF().isZero();
1814   }
1815   return false;
1816 }
1817 
1818 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1819 /// true if Op is undef or if it matches the specified value.
1820 static bool isConstantOrUndef(int Op, int Val) {
1821   return Op < 0 || Op == Val;
1822 }
1823 
1824 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1825 /// VPKUHUM instruction.
1826 /// The ShuffleKind distinguishes between big-endian operations with
1827 /// two different inputs (0), either-endian operations with two identical
1828 /// inputs (1), and little-endian operations with two different inputs (2).
1829 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1830 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1831                                SelectionDAG &DAG) {
1832   bool IsLE = DAG.getDataLayout().isLittleEndian();
1833   if (ShuffleKind == 0) {
1834     if (IsLE)
1835       return false;
1836     for (unsigned i = 0; i != 16; ++i)
1837       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1838         return false;
1839   } else if (ShuffleKind == 2) {
1840     if (!IsLE)
1841       return false;
1842     for (unsigned i = 0; i != 16; ++i)
1843       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1844         return false;
1845   } else if (ShuffleKind == 1) {
1846     unsigned j = IsLE ? 0 : 1;
1847     for (unsigned i = 0; i != 8; ++i)
1848       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1849           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1850         return false;
1851   }
1852   return true;
1853 }
1854 
1855 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1856 /// VPKUWUM instruction.
1857 /// The ShuffleKind distinguishes between big-endian operations with
1858 /// two different inputs (0), either-endian operations with two identical
1859 /// inputs (1), and little-endian operations with two different inputs (2).
1860 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1861 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1862                                SelectionDAG &DAG) {
1863   bool IsLE = DAG.getDataLayout().isLittleEndian();
1864   if (ShuffleKind == 0) {
1865     if (IsLE)
1866       return false;
1867     for (unsigned i = 0; i != 16; i += 2)
1868       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1869           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1870         return false;
1871   } else if (ShuffleKind == 2) {
1872     if (!IsLE)
1873       return false;
1874     for (unsigned i = 0; i != 16; i += 2)
1875       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1876           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1877         return false;
1878   } else if (ShuffleKind == 1) {
1879     unsigned j = IsLE ? 0 : 2;
1880     for (unsigned i = 0; i != 8; i += 2)
1881       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1882           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1883           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1884           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1885         return false;
1886   }
1887   return true;
1888 }
1889 
1890 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1891 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1892 /// current subtarget.
1893 ///
1894 /// The ShuffleKind distinguishes between big-endian operations with
1895 /// two different inputs (0), either-endian operations with two identical
1896 /// inputs (1), and little-endian operations with two different inputs (2).
1897 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1898 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1899                                SelectionDAG &DAG) {
1900   const PPCSubtarget& Subtarget =
1901       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1902   if (!Subtarget.hasP8Vector())
1903     return false;
1904 
1905   bool IsLE = DAG.getDataLayout().isLittleEndian();
1906   if (ShuffleKind == 0) {
1907     if (IsLE)
1908       return false;
1909     for (unsigned i = 0; i != 16; i += 4)
1910       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1911           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1912           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1913           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1914         return false;
1915   } else if (ShuffleKind == 2) {
1916     if (!IsLE)
1917       return false;
1918     for (unsigned i = 0; i != 16; i += 4)
1919       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1920           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1921           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1922           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1923         return false;
1924   } else if (ShuffleKind == 1) {
1925     unsigned j = IsLE ? 0 : 4;
1926     for (unsigned i = 0; i != 8; i += 4)
1927       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1928           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1929           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1930           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1931           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1932           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1933           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1934           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1935         return false;
1936   }
1937   return true;
1938 }
1939 
1940 /// isVMerge - Common function, used to match vmrg* shuffles.
1941 ///
1942 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1943                      unsigned LHSStart, unsigned RHSStart) {
1944   if (N->getValueType(0) != MVT::v16i8)
1945     return false;
1946   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1947          "Unsupported merge size!");
1948 
1949   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1950     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1951       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1952                              LHSStart+j+i*UnitSize) ||
1953           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1954                              RHSStart+j+i*UnitSize))
1955         return false;
1956     }
1957   return true;
1958 }
1959 
1960 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1961 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1962 /// The ShuffleKind distinguishes between big-endian merges with two
1963 /// different inputs (0), either-endian merges with two identical inputs (1),
1964 /// and little-endian merges with two different inputs (2).  For the latter,
1965 /// the input operands are swapped (see PPCInstrAltivec.td).
1966 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1967                              unsigned ShuffleKind, SelectionDAG &DAG) {
1968   if (DAG.getDataLayout().isLittleEndian()) {
1969     if (ShuffleKind == 1) // unary
1970       return isVMerge(N, UnitSize, 0, 0);
1971     else if (ShuffleKind == 2) // swapped
1972       return isVMerge(N, UnitSize, 0, 16);
1973     else
1974       return false;
1975   } else {
1976     if (ShuffleKind == 1) // unary
1977       return isVMerge(N, UnitSize, 8, 8);
1978     else if (ShuffleKind == 0) // normal
1979       return isVMerge(N, UnitSize, 8, 24);
1980     else
1981       return false;
1982   }
1983 }
1984 
1985 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1986 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1987 /// The ShuffleKind distinguishes between big-endian merges with two
1988 /// different inputs (0), either-endian merges with two identical inputs (1),
1989 /// and little-endian merges with two different inputs (2).  For the latter,
1990 /// the input operands are swapped (see PPCInstrAltivec.td).
1991 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1992                              unsigned ShuffleKind, SelectionDAG &DAG) {
1993   if (DAG.getDataLayout().isLittleEndian()) {
1994     if (ShuffleKind == 1) // unary
1995       return isVMerge(N, UnitSize, 8, 8);
1996     else if (ShuffleKind == 2) // swapped
1997       return isVMerge(N, UnitSize, 8, 24);
1998     else
1999       return false;
2000   } else {
2001     if (ShuffleKind == 1) // unary
2002       return isVMerge(N, UnitSize, 0, 0);
2003     else if (ShuffleKind == 0) // normal
2004       return isVMerge(N, UnitSize, 0, 16);
2005     else
2006       return false;
2007   }
2008 }
2009 
2010 /**
2011  * Common function used to match vmrgew and vmrgow shuffles
2012  *
2013  * The indexOffset determines whether to look for even or odd words in
2014  * the shuffle mask. This is based on the of the endianness of the target
2015  * machine.
2016  *   - Little Endian:
2017  *     - Use offset of 0 to check for odd elements
2018  *     - Use offset of 4 to check for even elements
2019  *   - Big Endian:
2020  *     - Use offset of 0 to check for even elements
2021  *     - Use offset of 4 to check for odd elements
2022  * A detailed description of the vector element ordering for little endian and
2023  * big endian can be found at
2024  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2025  * Targeting your applications - what little endian and big endian IBM XL C/C++
2026  * compiler differences mean to you
2027  *
2028  * The mask to the shuffle vector instruction specifies the indices of the
2029  * elements from the two input vectors to place in the result. The elements are
2030  * numbered in array-access order, starting with the first vector. These vectors
2031  * are always of type v16i8, thus each vector will contain 16 elements of size
2032  * 8. More info on the shuffle vector can be found in the
2033  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2034  * Language Reference.
2035  *
2036  * The RHSStartValue indicates whether the same input vectors are used (unary)
2037  * or two different input vectors are used, based on the following:
2038  *   - If the instruction uses the same vector for both inputs, the range of the
2039  *     indices will be 0 to 15. In this case, the RHSStart value passed should
2040  *     be 0.
2041  *   - If the instruction has two different vectors then the range of the
2042  *     indices will be 0 to 31. In this case, the RHSStart value passed should
2043  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
2044  *     to 31 specify elements in the second vector).
2045  *
2046  * \param[in] N The shuffle vector SD Node to analyze
2047  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2048  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2049  * vector to the shuffle_vector instruction
2050  * \return true iff this shuffle vector represents an even or odd word merge
2051  */
2052 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2053                      unsigned RHSStartValue) {
2054   if (N->getValueType(0) != MVT::v16i8)
2055     return false;
2056 
2057   for (unsigned i = 0; i < 2; ++i)
2058     for (unsigned j = 0; j < 4; ++j)
2059       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2060                              i*RHSStartValue+j+IndexOffset) ||
2061           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2062                              i*RHSStartValue+j+IndexOffset+8))
2063         return false;
2064   return true;
2065 }
2066 
2067 /**
2068  * Determine if the specified shuffle mask is suitable for the vmrgew or
2069  * vmrgow instructions.
2070  *
2071  * \param[in] N The shuffle vector SD Node to analyze
2072  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2073  * \param[in] ShuffleKind Identify the type of merge:
2074  *   - 0 = big-endian merge with two different inputs;
2075  *   - 1 = either-endian merge with two identical inputs;
2076  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2077  *     little-endian merges).
2078  * \param[in] DAG The current SelectionDAG
2079  * \return true iff this shuffle mask
2080  */
2081 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2082                               unsigned ShuffleKind, SelectionDAG &DAG) {
2083   if (DAG.getDataLayout().isLittleEndian()) {
2084     unsigned indexOffset = CheckEven ? 4 : 0;
2085     if (ShuffleKind == 1) // Unary
2086       return isVMerge(N, indexOffset, 0);
2087     else if (ShuffleKind == 2) // swapped
2088       return isVMerge(N, indexOffset, 16);
2089     else
2090       return false;
2091   }
2092   else {
2093     unsigned indexOffset = CheckEven ? 0 : 4;
2094     if (ShuffleKind == 1) // Unary
2095       return isVMerge(N, indexOffset, 0);
2096     else if (ShuffleKind == 0) // Normal
2097       return isVMerge(N, indexOffset, 16);
2098     else
2099       return false;
2100   }
2101   return false;
2102 }
2103 
2104 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2105 /// amount, otherwise return -1.
2106 /// The ShuffleKind distinguishes between big-endian operations with two
2107 /// different inputs (0), either-endian operations with two identical inputs
2108 /// (1), and little-endian operations with two different inputs (2).  For the
2109 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2110 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2111                              SelectionDAG &DAG) {
2112   if (N->getValueType(0) != MVT::v16i8)
2113     return -1;
2114 
2115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2116 
2117   // Find the first non-undef value in the shuffle mask.
2118   unsigned i;
2119   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2120     /*search*/;
2121 
2122   if (i == 16) return -1;  // all undef.
2123 
2124   // Otherwise, check to see if the rest of the elements are consecutively
2125   // numbered from this value.
2126   unsigned ShiftAmt = SVOp->getMaskElt(i);
2127   if (ShiftAmt < i) return -1;
2128 
2129   ShiftAmt -= i;
2130   bool isLE = DAG.getDataLayout().isLittleEndian();
2131 
2132   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2133     // Check the rest of the elements to see if they are consecutive.
2134     for (++i; i != 16; ++i)
2135       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2136         return -1;
2137   } else if (ShuffleKind == 1) {
2138     // Check the rest of the elements to see if they are consecutive.
2139     for (++i; i != 16; ++i)
2140       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2141         return -1;
2142   } else
2143     return -1;
2144 
2145   if (isLE)
2146     ShiftAmt = 16 - ShiftAmt;
2147 
2148   return ShiftAmt;
2149 }
2150 
2151 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2152 /// specifies a splat of a single element that is suitable for input to
2153 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2154 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2155   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2156          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2157 
2158   // The consecutive indices need to specify an element, not part of two
2159   // different elements.  So abandon ship early if this isn't the case.
2160   if (N->getMaskElt(0) % EltSize != 0)
2161     return false;
2162 
2163   // This is a splat operation if each element of the permute is the same, and
2164   // if the value doesn't reference the second vector.
2165   unsigned ElementBase = N->getMaskElt(0);
2166 
2167   // FIXME: Handle UNDEF elements too!
2168   if (ElementBase >= 16)
2169     return false;
2170 
2171   // Check that the indices are consecutive, in the case of a multi-byte element
2172   // splatted with a v16i8 mask.
2173   for (unsigned i = 1; i != EltSize; ++i)
2174     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2175       return false;
2176 
2177   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2178     if (N->getMaskElt(i) < 0) continue;
2179     for (unsigned j = 0; j != EltSize; ++j)
2180       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2181         return false;
2182   }
2183   return true;
2184 }
2185 
2186 /// Check that the mask is shuffling N byte elements. Within each N byte
2187 /// element of the mask, the indices could be either in increasing or
2188 /// decreasing order as long as they are consecutive.
2189 /// \param[in] N the shuffle vector SD Node to analyze
2190 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2191 /// Word/DoubleWord/QuadWord).
2192 /// \param[in] StepLen the delta indices number among the N byte element, if
2193 /// the mask is in increasing/decreasing order then it is 1/-1.
2194 /// \return true iff the mask is shuffling N byte elements.
2195 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2196                                    int StepLen) {
2197   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2198          "Unexpected element width.");
2199   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2200 
2201   unsigned NumOfElem = 16 / Width;
2202   unsigned MaskVal[16]; //  Width is never greater than 16
2203   for (unsigned i = 0; i < NumOfElem; ++i) {
2204     MaskVal[0] = N->getMaskElt(i * Width);
2205     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2206       return false;
2207     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2208       return false;
2209     }
2210 
2211     for (unsigned int j = 1; j < Width; ++j) {
2212       MaskVal[j] = N->getMaskElt(i * Width + j);
2213       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2214         return false;
2215       }
2216     }
2217   }
2218 
2219   return true;
2220 }
2221 
2222 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2223                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2224   if (!isNByteElemShuffleMask(N, 4, 1))
2225     return false;
2226 
2227   // Now we look at mask elements 0,4,8,12
2228   unsigned M0 = N->getMaskElt(0) / 4;
2229   unsigned M1 = N->getMaskElt(4) / 4;
2230   unsigned M2 = N->getMaskElt(8) / 4;
2231   unsigned M3 = N->getMaskElt(12) / 4;
2232   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2233   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2234 
2235   // Below, let H and L be arbitrary elements of the shuffle mask
2236   // where H is in the range [4,7] and L is in the range [0,3].
2237   // H, 1, 2, 3 or L, 5, 6, 7
2238   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2239       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2240     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2241     InsertAtByte = IsLE ? 12 : 0;
2242     Swap = M0 < 4;
2243     return true;
2244   }
2245   // 0, H, 2, 3 or 4, L, 6, 7
2246   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2247       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2248     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2249     InsertAtByte = IsLE ? 8 : 4;
2250     Swap = M1 < 4;
2251     return true;
2252   }
2253   // 0, 1, H, 3 or 4, 5, L, 7
2254   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2255       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2256     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2257     InsertAtByte = IsLE ? 4 : 8;
2258     Swap = M2 < 4;
2259     return true;
2260   }
2261   // 0, 1, 2, H or 4, 5, 6, L
2262   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2263       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2264     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2265     InsertAtByte = IsLE ? 0 : 12;
2266     Swap = M3 < 4;
2267     return true;
2268   }
2269 
2270   // If both vector operands for the shuffle are the same vector, the mask will
2271   // contain only elements from the first one and the second one will be undef.
2272   if (N->getOperand(1).isUndef()) {
2273     ShiftElts = 0;
2274     Swap = true;
2275     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2276     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2277       InsertAtByte = IsLE ? 12 : 0;
2278       return true;
2279     }
2280     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2281       InsertAtByte = IsLE ? 8 : 4;
2282       return true;
2283     }
2284     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2285       InsertAtByte = IsLE ? 4 : 8;
2286       return true;
2287     }
2288     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2289       InsertAtByte = IsLE ? 0 : 12;
2290       return true;
2291     }
2292   }
2293 
2294   return false;
2295 }
2296 
2297 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2298                                bool &Swap, bool IsLE) {
2299   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2300   // Ensure each byte index of the word is consecutive.
2301   if (!isNByteElemShuffleMask(N, 4, 1))
2302     return false;
2303 
2304   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2305   unsigned M0 = N->getMaskElt(0) / 4;
2306   unsigned M1 = N->getMaskElt(4) / 4;
2307   unsigned M2 = N->getMaskElt(8) / 4;
2308   unsigned M3 = N->getMaskElt(12) / 4;
2309 
2310   // If both vector operands for the shuffle are the same vector, the mask will
2311   // contain only elements from the first one and the second one will be undef.
2312   if (N->getOperand(1).isUndef()) {
2313     assert(M0 < 4 && "Indexing into an undef vector?");
2314     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2315       return false;
2316 
2317     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2318     Swap = false;
2319     return true;
2320   }
2321 
2322   // Ensure each word index of the ShuffleVector Mask is consecutive.
2323   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2324     return false;
2325 
2326   if (IsLE) {
2327     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2328       // Input vectors don't need to be swapped if the leading element
2329       // of the result is one of the 3 left elements of the second vector
2330       // (or if there is no shift to be done at all).
2331       Swap = false;
2332       ShiftElts = (8 - M0) % 8;
2333     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2334       // Input vectors need to be swapped if the leading element
2335       // of the result is one of the 3 left elements of the first vector
2336       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2337       Swap = true;
2338       ShiftElts = (4 - M0) % 4;
2339     }
2340 
2341     return true;
2342   } else {                                          // BE
2343     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2344       // Input vectors don't need to be swapped if the leading element
2345       // of the result is one of the 4 elements of the first vector.
2346       Swap = false;
2347       ShiftElts = M0;
2348     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2349       // Input vectors need to be swapped if the leading element
2350       // of the result is one of the 4 elements of the right vector.
2351       Swap = true;
2352       ShiftElts = M0 - 4;
2353     }
2354 
2355     return true;
2356   }
2357 }
2358 
2359 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2360   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2361 
2362   if (!isNByteElemShuffleMask(N, Width, -1))
2363     return false;
2364 
2365   for (int i = 0; i < 16; i += Width)
2366     if (N->getMaskElt(i) != i + Width - 1)
2367       return false;
2368 
2369   return true;
2370 }
2371 
2372 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2373   return isXXBRShuffleMaskHelper(N, 2);
2374 }
2375 
2376 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2377   return isXXBRShuffleMaskHelper(N, 4);
2378 }
2379 
2380 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2381   return isXXBRShuffleMaskHelper(N, 8);
2382 }
2383 
2384 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2385   return isXXBRShuffleMaskHelper(N, 16);
2386 }
2387 
2388 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2389 /// if the inputs to the instruction should be swapped and set \p DM to the
2390 /// value for the immediate.
2391 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2392 /// AND element 0 of the result comes from the first input (LE) or second input
2393 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2394 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2395 /// mask.
2396 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2397                                bool &Swap, bool IsLE) {
2398   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2399 
2400   // Ensure each byte index of the double word is consecutive.
2401   if (!isNByteElemShuffleMask(N, 8, 1))
2402     return false;
2403 
2404   unsigned M0 = N->getMaskElt(0) / 8;
2405   unsigned M1 = N->getMaskElt(8) / 8;
2406   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2407 
2408   // If both vector operands for the shuffle are the same vector, the mask will
2409   // contain only elements from the first one and the second one will be undef.
2410   if (N->getOperand(1).isUndef()) {
2411     if ((M0 | M1) < 2) {
2412       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2413       Swap = false;
2414       return true;
2415     } else
2416       return false;
2417   }
2418 
2419   if (IsLE) {
2420     if (M0 > 1 && M1 < 2) {
2421       Swap = false;
2422     } else if (M0 < 2 && M1 > 1) {
2423       M0 = (M0 + 2) % 4;
2424       M1 = (M1 + 2) % 4;
2425       Swap = true;
2426     } else
2427       return false;
2428 
2429     // Note: if control flow comes here that means Swap is already set above
2430     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2431     return true;
2432   } else { // BE
2433     if (M0 < 2 && M1 > 1) {
2434       Swap = false;
2435     } else if (M0 > 1 && M1 < 2) {
2436       M0 = (M0 + 2) % 4;
2437       M1 = (M1 + 2) % 4;
2438       Swap = true;
2439     } else
2440       return false;
2441 
2442     // Note: if control flow comes here that means Swap is already set above
2443     DM = (M0 << 1) + (M1 & 1);
2444     return true;
2445   }
2446 }
2447 
2448 
2449 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2450 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2451 /// elements are counted from the left of the vector register).
2452 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2453                                          SelectionDAG &DAG) {
2454   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2455   assert(isSplatShuffleMask(SVOp, EltSize));
2456   if (DAG.getDataLayout().isLittleEndian())
2457     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2458   else
2459     return SVOp->getMaskElt(0) / EltSize;
2460 }
2461 
2462 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2463 /// by using a vspltis[bhw] instruction of the specified element size, return
2464 /// the constant being splatted.  The ByteSize field indicates the number of
2465 /// bytes of each element [124] -> [bhw].
2466 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2467   SDValue OpVal;
2468 
2469   // If ByteSize of the splat is bigger than the element size of the
2470   // build_vector, then we have a case where we are checking for a splat where
2471   // multiple elements of the buildvector are folded together into a single
2472   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2473   unsigned EltSize = 16/N->getNumOperands();
2474   if (EltSize < ByteSize) {
2475     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2476     SDValue UniquedVals[4];
2477     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2478 
2479     // See if all of the elements in the buildvector agree across.
2480     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2481       if (N->getOperand(i).isUndef()) continue;
2482       // If the element isn't a constant, bail fully out.
2483       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2484 
2485       if (!UniquedVals[i&(Multiple-1)].getNode())
2486         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2487       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2488         return SDValue();  // no match.
2489     }
2490 
2491     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2492     // either constant or undef values that are identical for each chunk.  See
2493     // if these chunks can form into a larger vspltis*.
2494 
2495     // Check to see if all of the leading entries are either 0 or -1.  If
2496     // neither, then this won't fit into the immediate field.
2497     bool LeadingZero = true;
2498     bool LeadingOnes = true;
2499     for (unsigned i = 0; i != Multiple-1; ++i) {
2500       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2501 
2502       LeadingZero &= isNullConstant(UniquedVals[i]);
2503       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2504     }
2505     // Finally, check the least significant entry.
2506     if (LeadingZero) {
2507       if (!UniquedVals[Multiple-1].getNode())
2508         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2509       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2510       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2511         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2512     }
2513     if (LeadingOnes) {
2514       if (!UniquedVals[Multiple-1].getNode())
2515         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2516       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2517       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2518         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2519     }
2520 
2521     return SDValue();
2522   }
2523 
2524   // Check to see if this buildvec has a single non-undef value in its elements.
2525   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2526     if (N->getOperand(i).isUndef()) continue;
2527     if (!OpVal.getNode())
2528       OpVal = N->getOperand(i);
2529     else if (OpVal != N->getOperand(i))
2530       return SDValue();
2531   }
2532 
2533   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2534 
2535   unsigned ValSizeInBytes = EltSize;
2536   uint64_t Value = 0;
2537   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2538     Value = CN->getZExtValue();
2539   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2540     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2541     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2542   }
2543 
2544   // If the splat value is larger than the element value, then we can never do
2545   // this splat.  The only case that we could fit the replicated bits into our
2546   // immediate field for would be zero, and we prefer to use vxor for it.
2547   if (ValSizeInBytes < ByteSize) return SDValue();
2548 
2549   // If the element value is larger than the splat value, check if it consists
2550   // of a repeated bit pattern of size ByteSize.
2551   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2552     return SDValue();
2553 
2554   // Properly sign extend the value.
2555   int MaskVal = SignExtend32(Value, ByteSize * 8);
2556 
2557   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2558   if (MaskVal == 0) return SDValue();
2559 
2560   // Finally, if this value fits in a 5 bit sext field, return it
2561   if (SignExtend32<5>(MaskVal) == MaskVal)
2562     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2563   return SDValue();
2564 }
2565 
2566 //===----------------------------------------------------------------------===//
2567 //  Addressing Mode Selection
2568 //===----------------------------------------------------------------------===//
2569 
2570 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2571 /// or 64-bit immediate, and if the value can be accurately represented as a
2572 /// sign extension from a 16-bit value.  If so, this returns true and the
2573 /// immediate.
2574 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2575   if (!isa<ConstantSDNode>(N))
2576     return false;
2577 
2578   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2579   if (N->getValueType(0) == MVT::i32)
2580     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2581   else
2582     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2583 }
2584 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2585   return isIntS16Immediate(Op.getNode(), Imm);
2586 }
2587 
2588 /// Used when computing address flags for selecting loads and stores.
2589 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2590 /// An OR of two provably disjoint values is equivalent to an ADD.
2591 /// Most PPC load/store instructions compute the effective address as a sum,
2592 /// so doing this conversion is useful.
2593 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2594   if (N.getOpcode() != ISD::OR)
2595     return false;
2596   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2597   if (!LHSKnown.Zero.getBoolValue())
2598     return false;
2599   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2600   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2601 }
2602 
2603 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2604 /// be represented as an indexed [r+r] operation.
2605 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2606                                                SDValue &Index,
2607                                                SelectionDAG &DAG) const {
2608   for (SDNode *U : N->uses()) {
2609     if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2610       if (Memop->getMemoryVT() == MVT::f64) {
2611           Base = N.getOperand(0);
2612           Index = N.getOperand(1);
2613           return true;
2614       }
2615     }
2616   }
2617   return false;
2618 }
2619 
2620 /// isIntS34Immediate - This method tests if value of node given can be
2621 /// accurately represented as a sign extension from a 34-bit value.  If so,
2622 /// this returns true and the immediate.
2623 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2624   if (!isa<ConstantSDNode>(N))
2625     return false;
2626 
2627   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2628   return isInt<34>(Imm);
2629 }
2630 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2631   return isIntS34Immediate(Op.getNode(), Imm);
2632 }
2633 
2634 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2635 /// can be represented as an indexed [r+r] operation.  Returns false if it
2636 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2637 /// non-zero and N can be represented by a base register plus a signed 16-bit
2638 /// displacement, make a more precise judgement by checking (displacement % \p
2639 /// EncodingAlignment).
2640 bool PPCTargetLowering::SelectAddressRegReg(
2641     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2642     MaybeAlign EncodingAlignment) const {
2643   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2644   // a [pc+imm].
2645   if (SelectAddressPCRel(N, Base))
2646     return false;
2647 
2648   int16_t Imm = 0;
2649   if (N.getOpcode() == ISD::ADD) {
2650     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2651     // SPE load/store can only handle 8-bit offsets.
2652     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2653         return true;
2654     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2655         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2656       return false; // r+i
2657     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2658       return false;    // r+i
2659 
2660     Base = N.getOperand(0);
2661     Index = N.getOperand(1);
2662     return true;
2663   } else if (N.getOpcode() == ISD::OR) {
2664     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2665         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2666       return false; // r+i can fold it if we can.
2667 
2668     // If this is an or of disjoint bitfields, we can codegen this as an add
2669     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2670     // disjoint.
2671     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2672 
2673     if (LHSKnown.Zero.getBoolValue()) {
2674       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2675       // If all of the bits are known zero on the LHS or RHS, the add won't
2676       // carry.
2677       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2678         Base = N.getOperand(0);
2679         Index = N.getOperand(1);
2680         return true;
2681       }
2682     }
2683   }
2684 
2685   return false;
2686 }
2687 
2688 // If we happen to be doing an i64 load or store into a stack slot that has
2689 // less than a 4-byte alignment, then the frame-index elimination may need to
2690 // use an indexed load or store instruction (because the offset may not be a
2691 // multiple of 4). The extra register needed to hold the offset comes from the
2692 // register scavenger, and it is possible that the scavenger will need to use
2693 // an emergency spill slot. As a result, we need to make sure that a spill slot
2694 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2695 // stack slot.
2696 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2697   // FIXME: This does not handle the LWA case.
2698   if (VT != MVT::i64)
2699     return;
2700 
2701   // NOTE: We'll exclude negative FIs here, which come from argument
2702   // lowering, because there are no known test cases triggering this problem
2703   // using packed structures (or similar). We can remove this exclusion if
2704   // we find such a test case. The reason why this is so test-case driven is
2705   // because this entire 'fixup' is only to prevent crashes (from the
2706   // register scavenger) on not-really-valid inputs. For example, if we have:
2707   //   %a = alloca i1
2708   //   %b = bitcast i1* %a to i64*
2709   //   store i64* a, i64 b
2710   // then the store should really be marked as 'align 1', but is not. If it
2711   // were marked as 'align 1' then the indexed form would have been
2712   // instruction-selected initially, and the problem this 'fixup' is preventing
2713   // won't happen regardless.
2714   if (FrameIdx < 0)
2715     return;
2716 
2717   MachineFunction &MF = DAG.getMachineFunction();
2718   MachineFrameInfo &MFI = MF.getFrameInfo();
2719 
2720   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2721     return;
2722 
2723   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2724   FuncInfo->setHasNonRISpills();
2725 }
2726 
2727 /// Returns true if the address N can be represented by a base register plus
2728 /// a signed 16-bit displacement [r+imm], and if it is not better
2729 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2730 /// displacements that are multiples of that value.
2731 bool PPCTargetLowering::SelectAddressRegImm(
2732     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2733     MaybeAlign EncodingAlignment) const {
2734   // FIXME dl should come from parent load or store, not from address
2735   SDLoc dl(N);
2736 
2737   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2738   // a [pc+imm].
2739   if (SelectAddressPCRel(N, Base))
2740     return false;
2741 
2742   // If this can be more profitably realized as r+r, fail.
2743   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2744     return false;
2745 
2746   if (N.getOpcode() == ISD::ADD) {
2747     int16_t imm = 0;
2748     if (isIntS16Immediate(N.getOperand(1), imm) &&
2749         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2750       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2751       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2752         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2753         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2754       } else {
2755         Base = N.getOperand(0);
2756       }
2757       return true; // [r+i]
2758     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2759       // Match LOAD (ADD (X, Lo(G))).
2760       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2761              && "Cannot handle constant offsets yet!");
2762       Disp = N.getOperand(1).getOperand(0);  // The global address.
2763       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2764              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2765              Disp.getOpcode() == ISD::TargetConstantPool ||
2766              Disp.getOpcode() == ISD::TargetJumpTable);
2767       Base = N.getOperand(0);
2768       return true;  // [&g+r]
2769     }
2770   } else if (N.getOpcode() == ISD::OR) {
2771     int16_t imm = 0;
2772     if (isIntS16Immediate(N.getOperand(1), imm) &&
2773         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2774       // If this is an or of disjoint bitfields, we can codegen this as an add
2775       // (for better address arithmetic) if the LHS and RHS of the OR are
2776       // provably disjoint.
2777       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2778 
2779       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2780         // If all of the bits are known zero on the LHS or RHS, the add won't
2781         // carry.
2782         if (FrameIndexSDNode *FI =
2783               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2784           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2785           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2786         } else {
2787           Base = N.getOperand(0);
2788         }
2789         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2790         return true;
2791       }
2792     }
2793   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2794     // Loading from a constant address.
2795 
2796     // If this address fits entirely in a 16-bit sext immediate field, codegen
2797     // this as "d, 0"
2798     int16_t Imm;
2799     if (isIntS16Immediate(CN, Imm) &&
2800         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2801       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2802       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2803                              CN->getValueType(0));
2804       return true;
2805     }
2806 
2807     // Handle 32-bit sext immediates with LIS + addr mode.
2808     if ((CN->getValueType(0) == MVT::i32 ||
2809          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2810         (!EncodingAlignment ||
2811          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2812       int Addr = (int)CN->getZExtValue();
2813 
2814       // Otherwise, break this down into an LIS + disp.
2815       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2816 
2817       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2818                                    MVT::i32);
2819       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2820       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2821       return true;
2822     }
2823   }
2824 
2825   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2826   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2827     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2828     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2829   } else
2830     Base = N;
2831   return true;      // [r+0]
2832 }
2833 
2834 /// Similar to the 16-bit case but for instructions that take a 34-bit
2835 /// displacement field (prefixed loads/stores).
2836 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2837                                               SDValue &Base,
2838                                               SelectionDAG &DAG) const {
2839   // Only on 64-bit targets.
2840   if (N.getValueType() != MVT::i64)
2841     return false;
2842 
2843   SDLoc dl(N);
2844   int64_t Imm = 0;
2845 
2846   if (N.getOpcode() == ISD::ADD) {
2847     if (!isIntS34Immediate(N.getOperand(1), Imm))
2848       return false;
2849     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2850     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2851       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2852     else
2853       Base = N.getOperand(0);
2854     return true;
2855   }
2856 
2857   if (N.getOpcode() == ISD::OR) {
2858     if (!isIntS34Immediate(N.getOperand(1), Imm))
2859       return false;
2860     // If this is an or of disjoint bitfields, we can codegen this as an add
2861     // (for better address arithmetic) if the LHS and RHS of the OR are
2862     // provably disjoint.
2863     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2864     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2865       return false;
2866     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2867       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2868     else
2869       Base = N.getOperand(0);
2870     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2871     return true;
2872   }
2873 
2874   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2875     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2876     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2877     return true;
2878   }
2879 
2880   return false;
2881 }
2882 
2883 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2884 /// represented as an indexed [r+r] operation.
2885 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2886                                                 SDValue &Index,
2887                                                 SelectionDAG &DAG) const {
2888   // Check to see if we can easily represent this as an [r+r] address.  This
2889   // will fail if it thinks that the address is more profitably represented as
2890   // reg+imm, e.g. where imm = 0.
2891   if (SelectAddressRegReg(N, Base, Index, DAG))
2892     return true;
2893 
2894   // If the address is the result of an add, we will utilize the fact that the
2895   // address calculation includes an implicit add.  However, we can reduce
2896   // register pressure if we do not materialize a constant just for use as the
2897   // index register.  We only get rid of the add if it is not an add of a
2898   // value and a 16-bit signed constant and both have a single use.
2899   int16_t imm = 0;
2900   if (N.getOpcode() == ISD::ADD &&
2901       (!isIntS16Immediate(N.getOperand(1), imm) ||
2902        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2903     Base = N.getOperand(0);
2904     Index = N.getOperand(1);
2905     return true;
2906   }
2907 
2908   // Otherwise, do it the hard way, using R0 as the base register.
2909   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2910                          N.getValueType());
2911   Index = N;
2912   return true;
2913 }
2914 
2915 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2916   Ty *PCRelCand = dyn_cast<Ty>(N);
2917   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2918 }
2919 
2920 /// Returns true if this address is a PC Relative address.
2921 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2922 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2923 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2924   // This is a materialize PC Relative node. Always select this as PC Relative.
2925   Base = N;
2926   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2927     return true;
2928   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2929       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2930       isValidPCRelNode<JumpTableSDNode>(N) ||
2931       isValidPCRelNode<BlockAddressSDNode>(N))
2932     return true;
2933   return false;
2934 }
2935 
2936 /// Returns true if we should use a direct load into vector instruction
2937 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2938 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2939 
2940   // If there are any other uses other than scalar to vector, then we should
2941   // keep it as a scalar load -> direct move pattern to prevent multiple
2942   // loads.
2943   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2944   if (!LD)
2945     return false;
2946 
2947   EVT MemVT = LD->getMemoryVT();
2948   if (!MemVT.isSimple())
2949     return false;
2950   switch(MemVT.getSimpleVT().SimpleTy) {
2951   case MVT::i64:
2952     break;
2953   case MVT::i32:
2954     if (!ST.hasP8Vector())
2955       return false;
2956     break;
2957   case MVT::i16:
2958   case MVT::i8:
2959     if (!ST.hasP9Vector())
2960       return false;
2961     break;
2962   default:
2963     return false;
2964   }
2965 
2966   SDValue LoadedVal(N, 0);
2967   if (!LoadedVal.hasOneUse())
2968     return false;
2969 
2970   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2971        UI != UE; ++UI)
2972     if (UI.getUse().get().getResNo() == 0 &&
2973         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2974         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2975       return false;
2976 
2977   return true;
2978 }
2979 
2980 /// getPreIndexedAddressParts - returns true by value, base pointer and
2981 /// offset pointer and addressing mode by reference if the node's address
2982 /// can be legally represented as pre-indexed load / store address.
2983 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2984                                                   SDValue &Offset,
2985                                                   ISD::MemIndexedMode &AM,
2986                                                   SelectionDAG &DAG) const {
2987   if (DisablePPCPreinc) return false;
2988 
2989   bool isLoad = true;
2990   SDValue Ptr;
2991   EVT VT;
2992   unsigned Alignment;
2993   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2994     Ptr = LD->getBasePtr();
2995     VT = LD->getMemoryVT();
2996     Alignment = LD->getAlignment();
2997   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2998     Ptr = ST->getBasePtr();
2999     VT  = ST->getMemoryVT();
3000     Alignment = ST->getAlignment();
3001     isLoad = false;
3002   } else
3003     return false;
3004 
3005   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
3006   // instructions because we can fold these into a more efficient instruction
3007   // instead, (such as LXSD).
3008   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
3009     return false;
3010   }
3011 
3012   // PowerPC doesn't have preinc load/store instructions for vectors
3013   if (VT.isVector())
3014     return false;
3015 
3016   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3017     // Common code will reject creating a pre-inc form if the base pointer
3018     // is a frame index, or if N is a store and the base pointer is either
3019     // the same as or a predecessor of the value being stored.  Check for
3020     // those situations here, and try with swapped Base/Offset instead.
3021     bool Swap = false;
3022 
3023     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3024       Swap = true;
3025     else if (!isLoad) {
3026       SDValue Val = cast<StoreSDNode>(N)->getValue();
3027       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3028         Swap = true;
3029     }
3030 
3031     if (Swap)
3032       std::swap(Base, Offset);
3033 
3034     AM = ISD::PRE_INC;
3035     return true;
3036   }
3037 
3038   // LDU/STU can only handle immediates that are a multiple of 4.
3039   if (VT != MVT::i64) {
3040     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
3041       return false;
3042   } else {
3043     // LDU/STU need an address with at least 4-byte alignment.
3044     if (Alignment < 4)
3045       return false;
3046 
3047     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3048       return false;
3049   }
3050 
3051   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3052     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3053     // sext i32 to i64 when addr mode is r+i.
3054     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3055         LD->getExtensionType() == ISD::SEXTLOAD &&
3056         isa<ConstantSDNode>(Offset))
3057       return false;
3058   }
3059 
3060   AM = ISD::PRE_INC;
3061   return true;
3062 }
3063 
3064 //===----------------------------------------------------------------------===//
3065 //  LowerOperation implementation
3066 //===----------------------------------------------------------------------===//
3067 
3068 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3069 /// and LoOpFlags to the target MO flags.
3070 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3071                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3072                                const GlobalValue *GV = nullptr) {
3073   HiOpFlags = PPCII::MO_HA;
3074   LoOpFlags = PPCII::MO_LO;
3075 
3076   // Don't use the pic base if not in PIC relocation model.
3077   if (IsPIC) {
3078     HiOpFlags |= PPCII::MO_PIC_FLAG;
3079     LoOpFlags |= PPCII::MO_PIC_FLAG;
3080   }
3081 }
3082 
3083 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3084                              SelectionDAG &DAG) {
3085   SDLoc DL(HiPart);
3086   EVT PtrVT = HiPart.getValueType();
3087   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3088 
3089   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3090   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3091 
3092   // With PIC, the first instruction is actually "GR+hi(&G)".
3093   if (isPIC)
3094     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3095                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3096 
3097   // Generate non-pic code that has direct accesses to the constant pool.
3098   // The address of the global is just (hi(&g)+lo(&g)).
3099   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3100 }
3101 
3102 static void setUsesTOCBasePtr(MachineFunction &MF) {
3103   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3104   FuncInfo->setUsesTOCBasePtr();
3105 }
3106 
3107 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3108   setUsesTOCBasePtr(DAG.getMachineFunction());
3109 }
3110 
3111 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3112                                        SDValue GA) const {
3113   const bool Is64Bit = Subtarget.isPPC64();
3114   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3115   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3116                         : Subtarget.isAIXABI()
3117                               ? DAG.getRegister(PPC::R2, VT)
3118                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3119   SDValue Ops[] = { GA, Reg };
3120   return DAG.getMemIntrinsicNode(
3121       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3122       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3123       MachineMemOperand::MOLoad);
3124 }
3125 
3126 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3127                                              SelectionDAG &DAG) const {
3128   EVT PtrVT = Op.getValueType();
3129   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3130   const Constant *C = CP->getConstVal();
3131 
3132   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3133   // The actual address of the GlobalValue is stored in the TOC.
3134   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3135     if (Subtarget.isUsingPCRelativeCalls()) {
3136       SDLoc DL(CP);
3137       EVT Ty = getPointerTy(DAG.getDataLayout());
3138       SDValue ConstPool = DAG.getTargetConstantPool(
3139           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3140       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3141     }
3142     setUsesTOCBasePtr(DAG);
3143     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3144     return getTOCEntry(DAG, SDLoc(CP), GA);
3145   }
3146 
3147   unsigned MOHiFlag, MOLoFlag;
3148   bool IsPIC = isPositionIndependent();
3149   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3150 
3151   if (IsPIC && Subtarget.isSVR4ABI()) {
3152     SDValue GA =
3153         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3154     return getTOCEntry(DAG, SDLoc(CP), GA);
3155   }
3156 
3157   SDValue CPIHi =
3158       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3159   SDValue CPILo =
3160       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3161   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3162 }
3163 
3164 // For 64-bit PowerPC, prefer the more compact relative encodings.
3165 // This trades 32 bits per jump table entry for one or two instructions
3166 // on the jump site.
3167 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3168   if (isJumpTableRelative())
3169     return MachineJumpTableInfo::EK_LabelDifference32;
3170 
3171   return TargetLowering::getJumpTableEncoding();
3172 }
3173 
3174 bool PPCTargetLowering::isJumpTableRelative() const {
3175   if (UseAbsoluteJumpTables)
3176     return false;
3177   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3178     return true;
3179   return TargetLowering::isJumpTableRelative();
3180 }
3181 
3182 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3183                                                     SelectionDAG &DAG) const {
3184   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3185     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3186 
3187   switch (getTargetMachine().getCodeModel()) {
3188   case CodeModel::Small:
3189   case CodeModel::Medium:
3190     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3191   default:
3192     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3193                        getPointerTy(DAG.getDataLayout()));
3194   }
3195 }
3196 
3197 const MCExpr *
3198 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3199                                                 unsigned JTI,
3200                                                 MCContext &Ctx) const {
3201   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3202     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3203 
3204   switch (getTargetMachine().getCodeModel()) {
3205   case CodeModel::Small:
3206   case CodeModel::Medium:
3207     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3208   default:
3209     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3210   }
3211 }
3212 
3213 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3214   EVT PtrVT = Op.getValueType();
3215   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3216 
3217   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3218   if (Subtarget.isUsingPCRelativeCalls()) {
3219     SDLoc DL(JT);
3220     EVT Ty = getPointerTy(DAG.getDataLayout());
3221     SDValue GA =
3222         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3223     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3224     return MatAddr;
3225   }
3226 
3227   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3228   // The actual address of the GlobalValue is stored in the TOC.
3229   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3230     setUsesTOCBasePtr(DAG);
3231     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3232     return getTOCEntry(DAG, SDLoc(JT), GA);
3233   }
3234 
3235   unsigned MOHiFlag, MOLoFlag;
3236   bool IsPIC = isPositionIndependent();
3237   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3238 
3239   if (IsPIC && Subtarget.isSVR4ABI()) {
3240     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3241                                         PPCII::MO_PIC_FLAG);
3242     return getTOCEntry(DAG, SDLoc(GA), GA);
3243   }
3244 
3245   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3246   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3247   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3248 }
3249 
3250 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3251                                              SelectionDAG &DAG) const {
3252   EVT PtrVT = Op.getValueType();
3253   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3254   const BlockAddress *BA = BASDN->getBlockAddress();
3255 
3256   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3257   if (Subtarget.isUsingPCRelativeCalls()) {
3258     SDLoc DL(BASDN);
3259     EVT Ty = getPointerTy(DAG.getDataLayout());
3260     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3261                                            PPCII::MO_PCREL_FLAG);
3262     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3263     return MatAddr;
3264   }
3265 
3266   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3267   // The actual BlockAddress is stored in the TOC.
3268   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3269     setUsesTOCBasePtr(DAG);
3270     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3271     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3272   }
3273 
3274   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3275   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3276     return getTOCEntry(
3277         DAG, SDLoc(BASDN),
3278         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3279 
3280   unsigned MOHiFlag, MOLoFlag;
3281   bool IsPIC = isPositionIndependent();
3282   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3283   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3284   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3285   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3286 }
3287 
3288 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3289                                               SelectionDAG &DAG) const {
3290   if (Subtarget.isAIXABI())
3291     return LowerGlobalTLSAddressAIX(Op, DAG);
3292 
3293   return LowerGlobalTLSAddressLinux(Op, DAG);
3294 }
3295 
3296 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3297                                                     SelectionDAG &DAG) const {
3298   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3299 
3300   if (DAG.getTarget().useEmulatedTLS())
3301     report_fatal_error("Emulated TLS is not yet supported on AIX");
3302 
3303   SDLoc dl(GA);
3304   const GlobalValue *GV = GA->getGlobal();
3305   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3306 
3307   // The general-dynamic model is the only access model supported for now, so
3308   // all the GlobalTLSAddress nodes are lowered with this model.
3309   // We need to generate two TOC entries, one for the variable offset, one for
3310   // the region handle. The global address for the TOC entry of the region
3311   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3312   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3313   SDValue VariableOffsetTGA =
3314       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3315   SDValue RegionHandleTGA =
3316       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3317   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3318   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3319   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3320                      RegionHandle);
3321 }
3322 
3323 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3324                                                       SelectionDAG &DAG) const {
3325   // FIXME: TLS addresses currently use medium model code sequences,
3326   // which is the most useful form.  Eventually support for small and
3327   // large models could be added if users need it, at the cost of
3328   // additional complexity.
3329   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3330   if (DAG.getTarget().useEmulatedTLS())
3331     return LowerToTLSEmulatedModel(GA, DAG);
3332 
3333   SDLoc dl(GA);
3334   const GlobalValue *GV = GA->getGlobal();
3335   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3336   bool is64bit = Subtarget.isPPC64();
3337   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3338   PICLevel::Level picLevel = M->getPICLevel();
3339 
3340   const TargetMachine &TM = getTargetMachine();
3341   TLSModel::Model Model = TM.getTLSModel(GV);
3342 
3343   if (Model == TLSModel::LocalExec) {
3344     if (Subtarget.isUsingPCRelativeCalls()) {
3345       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3346       SDValue TGA = DAG.getTargetGlobalAddress(
3347           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3348       SDValue MatAddr =
3349           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3350       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3351     }
3352 
3353     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3354                                                PPCII::MO_TPREL_HA);
3355     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3356                                                PPCII::MO_TPREL_LO);
3357     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3358                              : DAG.getRegister(PPC::R2, MVT::i32);
3359 
3360     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3361     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3362   }
3363 
3364   if (Model == TLSModel::InitialExec) {
3365     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3366     SDValue TGA = DAG.getTargetGlobalAddress(
3367         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3368     SDValue TGATLS = DAG.getTargetGlobalAddress(
3369         GV, dl, PtrVT, 0,
3370         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3371     SDValue TPOffset;
3372     if (IsPCRel) {
3373       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3374       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3375                              MachinePointerInfo());
3376     } else {
3377       SDValue GOTPtr;
3378       if (is64bit) {
3379         setUsesTOCBasePtr(DAG);
3380         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3381         GOTPtr =
3382             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3383       } else {
3384         if (!TM.isPositionIndependent())
3385           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3386         else if (picLevel == PICLevel::SmallPIC)
3387           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3388         else
3389           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3390       }
3391       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3392     }
3393     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3394   }
3395 
3396   if (Model == TLSModel::GeneralDynamic) {
3397     if (Subtarget.isUsingPCRelativeCalls()) {
3398       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3399                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3400       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3401     }
3402 
3403     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3404     SDValue GOTPtr;
3405     if (is64bit) {
3406       setUsesTOCBasePtr(DAG);
3407       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3408       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3409                                    GOTReg, TGA);
3410     } else {
3411       if (picLevel == PICLevel::SmallPIC)
3412         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3413       else
3414         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3415     }
3416     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3417                        GOTPtr, TGA, TGA);
3418   }
3419 
3420   if (Model == TLSModel::LocalDynamic) {
3421     if (Subtarget.isUsingPCRelativeCalls()) {
3422       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3423                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3424       SDValue MatPCRel =
3425           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3426       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3427     }
3428 
3429     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3430     SDValue GOTPtr;
3431     if (is64bit) {
3432       setUsesTOCBasePtr(DAG);
3433       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3434       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3435                            GOTReg, TGA);
3436     } else {
3437       if (picLevel == PICLevel::SmallPIC)
3438         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3439       else
3440         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3441     }
3442     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3443                                   PtrVT, GOTPtr, TGA, TGA);
3444     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3445                                       PtrVT, TLSAddr, TGA);
3446     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3447   }
3448 
3449   llvm_unreachable("Unknown TLS model!");
3450 }
3451 
3452 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3453                                               SelectionDAG &DAG) const {
3454   EVT PtrVT = Op.getValueType();
3455   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3456   SDLoc DL(GSDN);
3457   const GlobalValue *GV = GSDN->getGlobal();
3458 
3459   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3460   // The actual address of the GlobalValue is stored in the TOC.
3461   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3462     if (Subtarget.isUsingPCRelativeCalls()) {
3463       EVT Ty = getPointerTy(DAG.getDataLayout());
3464       if (isAccessedAsGotIndirect(Op)) {
3465         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3466                                                 PPCII::MO_PCREL_FLAG |
3467                                                     PPCII::MO_GOT_FLAG);
3468         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3469         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3470                                    MachinePointerInfo());
3471         return Load;
3472       } else {
3473         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3474                                                 PPCII::MO_PCREL_FLAG);
3475         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3476       }
3477     }
3478     setUsesTOCBasePtr(DAG);
3479     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3480     return getTOCEntry(DAG, DL, GA);
3481   }
3482 
3483   unsigned MOHiFlag, MOLoFlag;
3484   bool IsPIC = isPositionIndependent();
3485   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3486 
3487   if (IsPIC && Subtarget.isSVR4ABI()) {
3488     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3489                                             GSDN->getOffset(),
3490                                             PPCII::MO_PIC_FLAG);
3491     return getTOCEntry(DAG, DL, GA);
3492   }
3493 
3494   SDValue GAHi =
3495     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3496   SDValue GALo =
3497     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3498 
3499   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3500 }
3501 
3502 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3503   bool IsStrict = Op->isStrictFPOpcode();
3504   ISD::CondCode CC =
3505       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3506   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3507   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3508   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3509   EVT LHSVT = LHS.getValueType();
3510   SDLoc dl(Op);
3511 
3512   // Soften the setcc with libcall if it is fp128.
3513   if (LHSVT == MVT::f128) {
3514     assert(!Subtarget.hasP9Vector() &&
3515            "SETCC for f128 is already legal under Power9!");
3516     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3517                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3518     if (RHS.getNode())
3519       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3520                         DAG.getCondCode(CC));
3521     if (IsStrict)
3522       return DAG.getMergeValues({LHS, Chain}, dl);
3523     return LHS;
3524   }
3525 
3526   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3527 
3528   if (Op.getValueType() == MVT::v2i64) {
3529     // When the operands themselves are v2i64 values, we need to do something
3530     // special because VSX has no underlying comparison operations for these.
3531     if (LHS.getValueType() == MVT::v2i64) {
3532       // Equality can be handled by casting to the legal type for Altivec
3533       // comparisons, everything else needs to be expanded.
3534       if (CC != ISD::SETEQ && CC != ISD::SETNE)
3535         return SDValue();
3536       SDValue SetCC32 = DAG.getSetCC(
3537           dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3538           DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3539       int ShuffV[] = {1, 0, 3, 2};
3540       SDValue Shuff =
3541           DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3542       return DAG.getBitcast(MVT::v2i64,
3543                             DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3544                                         dl, MVT::v4i32, Shuff, SetCC32));
3545     }
3546 
3547     // We handle most of these in the usual way.
3548     return Op;
3549   }
3550 
3551   // If we're comparing for equality to zero, expose the fact that this is
3552   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3553   // fold the new nodes.
3554   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3555     return V;
3556 
3557   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3558     // Leave comparisons against 0 and -1 alone for now, since they're usually
3559     // optimized.  FIXME: revisit this when we can custom lower all setcc
3560     // optimizations.
3561     if (C->isAllOnes() || C->isZero())
3562       return SDValue();
3563   }
3564 
3565   // If we have an integer seteq/setne, turn it into a compare against zero
3566   // by xor'ing the rhs with the lhs, which is faster than setting a
3567   // condition register, reading it back out, and masking the correct bit.  The
3568   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3569   // the result to other bit-twiddling opportunities.
3570   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3571     EVT VT = Op.getValueType();
3572     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3573     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3574   }
3575   return SDValue();
3576 }
3577 
3578 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3579   SDNode *Node = Op.getNode();
3580   EVT VT = Node->getValueType(0);
3581   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3582   SDValue InChain = Node->getOperand(0);
3583   SDValue VAListPtr = Node->getOperand(1);
3584   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3585   SDLoc dl(Node);
3586 
3587   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3588 
3589   // gpr_index
3590   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3591                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3592   InChain = GprIndex.getValue(1);
3593 
3594   if (VT == MVT::i64) {
3595     // Check if GprIndex is even
3596     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3597                                  DAG.getConstant(1, dl, MVT::i32));
3598     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3599                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3600     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3601                                           DAG.getConstant(1, dl, MVT::i32));
3602     // Align GprIndex to be even if it isn't
3603     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3604                            GprIndex);
3605   }
3606 
3607   // fpr index is 1 byte after gpr
3608   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3609                                DAG.getConstant(1, dl, MVT::i32));
3610 
3611   // fpr
3612   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3613                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3614   InChain = FprIndex.getValue(1);
3615 
3616   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3617                                        DAG.getConstant(8, dl, MVT::i32));
3618 
3619   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3620                                         DAG.getConstant(4, dl, MVT::i32));
3621 
3622   // areas
3623   SDValue OverflowArea =
3624       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3625   InChain = OverflowArea.getValue(1);
3626 
3627   SDValue RegSaveArea =
3628       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3629   InChain = RegSaveArea.getValue(1);
3630 
3631   // select overflow_area if index > 8
3632   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3633                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3634 
3635   // adjustment constant gpr_index * 4/8
3636   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3637                                     VT.isInteger() ? GprIndex : FprIndex,
3638                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3639                                                     MVT::i32));
3640 
3641   // OurReg = RegSaveArea + RegConstant
3642   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3643                                RegConstant);
3644 
3645   // Floating types are 32 bytes into RegSaveArea
3646   if (VT.isFloatingPoint())
3647     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3648                          DAG.getConstant(32, dl, MVT::i32));
3649 
3650   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3651   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3652                                    VT.isInteger() ? GprIndex : FprIndex,
3653                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3654                                                    MVT::i32));
3655 
3656   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3657                               VT.isInteger() ? VAListPtr : FprPtr,
3658                               MachinePointerInfo(SV), MVT::i8);
3659 
3660   // determine if we should load from reg_save_area or overflow_area
3661   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3662 
3663   // increase overflow_area by 4/8 if gpr/fpr > 8
3664   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3665                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3666                                           dl, MVT::i32));
3667 
3668   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3669                              OverflowAreaPlusN);
3670 
3671   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3672                               MachinePointerInfo(), MVT::i32);
3673 
3674   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3675 }
3676 
3677 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3678   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3679 
3680   // We have to copy the entire va_list struct:
3681   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3682   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3683                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3684                        false, true, false, MachinePointerInfo(),
3685                        MachinePointerInfo());
3686 }
3687 
3688 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3689                                                   SelectionDAG &DAG) const {
3690   if (Subtarget.isAIXABI())
3691     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3692 
3693   return Op.getOperand(0);
3694 }
3695 
3696 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3697   MachineFunction &MF = DAG.getMachineFunction();
3698   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3699 
3700   assert((Op.getOpcode() == ISD::INLINEASM ||
3701           Op.getOpcode() == ISD::INLINEASM_BR) &&
3702          "Expecting Inline ASM node.");
3703 
3704   // If an LR store is already known to be required then there is not point in
3705   // checking this ASM as well.
3706   if (MFI.isLRStoreRequired())
3707     return Op;
3708 
3709   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3710   // type MVT::Glue. We want to ignore this last operand if that is the case.
3711   unsigned NumOps = Op.getNumOperands();
3712   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3713     --NumOps;
3714 
3715   // Check all operands that may contain the LR.
3716   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3717     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3718     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3719     ++i; // Skip the ID value.
3720 
3721     switch (InlineAsm::getKind(Flags)) {
3722     default:
3723       llvm_unreachable("Bad flags!");
3724     case InlineAsm::Kind_RegUse:
3725     case InlineAsm::Kind_Imm:
3726     case InlineAsm::Kind_Mem:
3727       i += NumVals;
3728       break;
3729     case InlineAsm::Kind_Clobber:
3730     case InlineAsm::Kind_RegDef:
3731     case InlineAsm::Kind_RegDefEarlyClobber: {
3732       for (; NumVals; --NumVals, ++i) {
3733         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3734         if (Reg != PPC::LR && Reg != PPC::LR8)
3735           continue;
3736         MFI.setLRStoreRequired();
3737         return Op;
3738       }
3739       break;
3740     }
3741     }
3742   }
3743 
3744   return Op;
3745 }
3746 
3747 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3748                                                 SelectionDAG &DAG) const {
3749   if (Subtarget.isAIXABI())
3750     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3751 
3752   SDValue Chain = Op.getOperand(0);
3753   SDValue Trmp = Op.getOperand(1); // trampoline
3754   SDValue FPtr = Op.getOperand(2); // nested function
3755   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3756   SDLoc dl(Op);
3757 
3758   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3759   bool isPPC64 = (PtrVT == MVT::i64);
3760   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3761 
3762   TargetLowering::ArgListTy Args;
3763   TargetLowering::ArgListEntry Entry;
3764 
3765   Entry.Ty = IntPtrTy;
3766   Entry.Node = Trmp; Args.push_back(Entry);
3767 
3768   // TrampSize == (isPPC64 ? 48 : 40);
3769   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3770                                isPPC64 ? MVT::i64 : MVT::i32);
3771   Args.push_back(Entry);
3772 
3773   Entry.Node = FPtr; Args.push_back(Entry);
3774   Entry.Node = Nest; Args.push_back(Entry);
3775 
3776   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3777   TargetLowering::CallLoweringInfo CLI(DAG);
3778   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3779       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3780       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3781 
3782   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3783   return CallResult.second;
3784 }
3785 
3786 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3787   MachineFunction &MF = DAG.getMachineFunction();
3788   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3789   EVT PtrVT = getPointerTy(MF.getDataLayout());
3790 
3791   SDLoc dl(Op);
3792 
3793   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3794     // vastart just stores the address of the VarArgsFrameIndex slot into the
3795     // memory location argument.
3796     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3797     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3798     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3799                         MachinePointerInfo(SV));
3800   }
3801 
3802   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3803   // We suppose the given va_list is already allocated.
3804   //
3805   // typedef struct {
3806   //  char gpr;     /* index into the array of 8 GPRs
3807   //                 * stored in the register save area
3808   //                 * gpr=0 corresponds to r3,
3809   //                 * gpr=1 to r4, etc.
3810   //                 */
3811   //  char fpr;     /* index into the array of 8 FPRs
3812   //                 * stored in the register save area
3813   //                 * fpr=0 corresponds to f1,
3814   //                 * fpr=1 to f2, etc.
3815   //                 */
3816   //  char *overflow_arg_area;
3817   //                /* location on stack that holds
3818   //                 * the next overflow argument
3819   //                 */
3820   //  char *reg_save_area;
3821   //               /* where r3:r10 and f1:f8 (if saved)
3822   //                * are stored
3823   //                */
3824   // } va_list[1];
3825 
3826   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3827   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3828   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3829                                             PtrVT);
3830   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3831                                  PtrVT);
3832 
3833   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3834   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3835 
3836   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3837   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3838 
3839   uint64_t FPROffset = 1;
3840   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3841 
3842   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3843 
3844   // Store first byte : number of int regs
3845   SDValue firstStore =
3846       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3847                         MachinePointerInfo(SV), MVT::i8);
3848   uint64_t nextOffset = FPROffset;
3849   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3850                                   ConstFPROffset);
3851 
3852   // Store second byte : number of float regs
3853   SDValue secondStore =
3854       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3855                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3856   nextOffset += StackOffset;
3857   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3858 
3859   // Store second word : arguments given on stack
3860   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3861                                     MachinePointerInfo(SV, nextOffset));
3862   nextOffset += FrameOffset;
3863   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3864 
3865   // Store third word : arguments given in registers
3866   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3867                       MachinePointerInfo(SV, nextOffset));
3868 }
3869 
3870 /// FPR - The set of FP registers that should be allocated for arguments
3871 /// on Darwin and AIX.
3872 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3873                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3874                                 PPC::F11, PPC::F12, PPC::F13};
3875 
3876 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3877 /// the stack.
3878 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3879                                        unsigned PtrByteSize) {
3880   unsigned ArgSize = ArgVT.getStoreSize();
3881   if (Flags.isByVal())
3882     ArgSize = Flags.getByValSize();
3883 
3884   // Round up to multiples of the pointer size, except for array members,
3885   // which are always packed.
3886   if (!Flags.isInConsecutiveRegs())
3887     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3888 
3889   return ArgSize;
3890 }
3891 
3892 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3893 /// on the stack.
3894 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3895                                          ISD::ArgFlagsTy Flags,
3896                                          unsigned PtrByteSize) {
3897   Align Alignment(PtrByteSize);
3898 
3899   // Altivec parameters are padded to a 16 byte boundary.
3900   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3901       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3902       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3903       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3904     Alignment = Align(16);
3905 
3906   // ByVal parameters are aligned as requested.
3907   if (Flags.isByVal()) {
3908     auto BVAlign = Flags.getNonZeroByValAlign();
3909     if (BVAlign > PtrByteSize) {
3910       if (BVAlign.value() % PtrByteSize != 0)
3911         llvm_unreachable(
3912             "ByVal alignment is not a multiple of the pointer size");
3913 
3914       Alignment = BVAlign;
3915     }
3916   }
3917 
3918   // Array members are always packed to their original alignment.
3919   if (Flags.isInConsecutiveRegs()) {
3920     // If the array member was split into multiple registers, the first
3921     // needs to be aligned to the size of the full type.  (Except for
3922     // ppcf128, which is only aligned as its f64 components.)
3923     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3924       Alignment = Align(OrigVT.getStoreSize());
3925     else
3926       Alignment = Align(ArgVT.getStoreSize());
3927   }
3928 
3929   return Alignment;
3930 }
3931 
3932 /// CalculateStackSlotUsed - Return whether this argument will use its
3933 /// stack slot (instead of being passed in registers).  ArgOffset,
3934 /// AvailableFPRs, and AvailableVRs must hold the current argument
3935 /// position, and will be updated to account for this argument.
3936 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3937                                    unsigned PtrByteSize, unsigned LinkageSize,
3938                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3939                                    unsigned &AvailableFPRs,
3940                                    unsigned &AvailableVRs) {
3941   bool UseMemory = false;
3942 
3943   // Respect alignment of argument on the stack.
3944   Align Alignment =
3945       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3946   ArgOffset = alignTo(ArgOffset, Alignment);
3947   // If there's no space left in the argument save area, we must
3948   // use memory (this check also catches zero-sized arguments).
3949   if (ArgOffset >= LinkageSize + ParamAreaSize)
3950     UseMemory = true;
3951 
3952   // Allocate argument on the stack.
3953   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3954   if (Flags.isInConsecutiveRegsLast())
3955     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3956   // If we overran the argument save area, we must use memory
3957   // (this check catches arguments passed partially in memory)
3958   if (ArgOffset > LinkageSize + ParamAreaSize)
3959     UseMemory = true;
3960 
3961   // However, if the argument is actually passed in an FPR or a VR,
3962   // we don't use memory after all.
3963   if (!Flags.isByVal()) {
3964     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3965       if (AvailableFPRs > 0) {
3966         --AvailableFPRs;
3967         return false;
3968       }
3969     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3970         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3971         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3972         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3973       if (AvailableVRs > 0) {
3974         --AvailableVRs;
3975         return false;
3976       }
3977   }
3978 
3979   return UseMemory;
3980 }
3981 
3982 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3983 /// ensure minimum alignment required for target.
3984 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3985                                      unsigned NumBytes) {
3986   return alignTo(NumBytes, Lowering->getStackAlign());
3987 }
3988 
3989 SDValue PPCTargetLowering::LowerFormalArguments(
3990     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3991     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3992     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3993   if (Subtarget.isAIXABI())
3994     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3995                                     InVals);
3996   if (Subtarget.is64BitELFABI())
3997     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3998                                        InVals);
3999   assert(Subtarget.is32BitELFABI());
4000   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
4001                                      InVals);
4002 }
4003 
4004 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
4005     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4006     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4007     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4008 
4009   // 32-bit SVR4 ABI Stack Frame Layout:
4010   //              +-----------------------------------+
4011   //        +-->  |            Back chain             |
4012   //        |     +-----------------------------------+
4013   //        |     | Floating-point register save area |
4014   //        |     +-----------------------------------+
4015   //        |     |    General register save area     |
4016   //        |     +-----------------------------------+
4017   //        |     |          CR save word             |
4018   //        |     +-----------------------------------+
4019   //        |     |         VRSAVE save word          |
4020   //        |     +-----------------------------------+
4021   //        |     |         Alignment padding         |
4022   //        |     +-----------------------------------+
4023   //        |     |     Vector register save area     |
4024   //        |     +-----------------------------------+
4025   //        |     |       Local variable space        |
4026   //        |     +-----------------------------------+
4027   //        |     |        Parameter list area        |
4028   //        |     +-----------------------------------+
4029   //        |     |           LR save word            |
4030   //        |     +-----------------------------------+
4031   // SP-->  +---  |            Back chain             |
4032   //              +-----------------------------------+
4033   //
4034   // Specifications:
4035   //   System V Application Binary Interface PowerPC Processor Supplement
4036   //   AltiVec Technology Programming Interface Manual
4037 
4038   MachineFunction &MF = DAG.getMachineFunction();
4039   MachineFrameInfo &MFI = MF.getFrameInfo();
4040   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4041 
4042   EVT PtrVT = getPointerTy(MF.getDataLayout());
4043   // Potential tail calls could cause overwriting of argument stack slots.
4044   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4045                        (CallConv == CallingConv::Fast));
4046   const Align PtrAlign(4);
4047 
4048   // Assign locations to all of the incoming arguments.
4049   SmallVector<CCValAssign, 16> ArgLocs;
4050   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4051                  *DAG.getContext());
4052 
4053   // Reserve space for the linkage area on the stack.
4054   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4055   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4056   if (useSoftFloat())
4057     CCInfo.PreAnalyzeFormalArguments(Ins);
4058 
4059   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4060   CCInfo.clearWasPPCF128();
4061 
4062   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4063     CCValAssign &VA = ArgLocs[i];
4064 
4065     // Arguments stored in registers.
4066     if (VA.isRegLoc()) {
4067       const TargetRegisterClass *RC;
4068       EVT ValVT = VA.getValVT();
4069 
4070       switch (ValVT.getSimpleVT().SimpleTy) {
4071         default:
4072           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4073         case MVT::i1:
4074         case MVT::i32:
4075           RC = &PPC::GPRCRegClass;
4076           break;
4077         case MVT::f32:
4078           if (Subtarget.hasP8Vector())
4079             RC = &PPC::VSSRCRegClass;
4080           else if (Subtarget.hasSPE())
4081             RC = &PPC::GPRCRegClass;
4082           else
4083             RC = &PPC::F4RCRegClass;
4084           break;
4085         case MVT::f64:
4086           if (Subtarget.hasVSX())
4087             RC = &PPC::VSFRCRegClass;
4088           else if (Subtarget.hasSPE())
4089             // SPE passes doubles in GPR pairs.
4090             RC = &PPC::GPRCRegClass;
4091           else
4092             RC = &PPC::F8RCRegClass;
4093           break;
4094         case MVT::v16i8:
4095         case MVT::v8i16:
4096         case MVT::v4i32:
4097           RC = &PPC::VRRCRegClass;
4098           break;
4099         case MVT::v4f32:
4100           RC = &PPC::VRRCRegClass;
4101           break;
4102         case MVT::v2f64:
4103         case MVT::v2i64:
4104           RC = &PPC::VRRCRegClass;
4105           break;
4106       }
4107 
4108       SDValue ArgValue;
4109       // Transform the arguments stored in physical registers into
4110       // virtual ones.
4111       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4112         assert(i + 1 < e && "No second half of double precision argument");
4113         Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4114         Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4115         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4116         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4117         if (!Subtarget.isLittleEndian())
4118           std::swap (ArgValueLo, ArgValueHi);
4119         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4120                                ArgValueHi);
4121       } else {
4122         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4123         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4124                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4125         if (ValVT == MVT::i1)
4126           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4127       }
4128 
4129       InVals.push_back(ArgValue);
4130     } else {
4131       // Argument stored in memory.
4132       assert(VA.isMemLoc());
4133 
4134       // Get the extended size of the argument type in stack
4135       unsigned ArgSize = VA.getLocVT().getStoreSize();
4136       // Get the actual size of the argument type
4137       unsigned ObjSize = VA.getValVT().getStoreSize();
4138       unsigned ArgOffset = VA.getLocMemOffset();
4139       // Stack objects in PPC32 are right justified.
4140       ArgOffset += ArgSize - ObjSize;
4141       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4142 
4143       // Create load nodes to retrieve arguments from the stack.
4144       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4145       InVals.push_back(
4146           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4147     }
4148   }
4149 
4150   // Assign locations to all of the incoming aggregate by value arguments.
4151   // Aggregates passed by value are stored in the local variable space of the
4152   // caller's stack frame, right above the parameter list area.
4153   SmallVector<CCValAssign, 16> ByValArgLocs;
4154   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4155                       ByValArgLocs, *DAG.getContext());
4156 
4157   // Reserve stack space for the allocations in CCInfo.
4158   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4159 
4160   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4161 
4162   // Area that is at least reserved in the caller of this function.
4163   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4164   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4165 
4166   // Set the size that is at least reserved in caller of this function.  Tail
4167   // call optimized function's reserved stack space needs to be aligned so that
4168   // taking the difference between two stack areas will result in an aligned
4169   // stack.
4170   MinReservedArea =
4171       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4172   FuncInfo->setMinReservedArea(MinReservedArea);
4173 
4174   SmallVector<SDValue, 8> MemOps;
4175 
4176   // If the function takes variable number of arguments, make a frame index for
4177   // the start of the first vararg value... for expansion of llvm.va_start.
4178   if (isVarArg) {
4179     static const MCPhysReg GPArgRegs[] = {
4180       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4181       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4182     };
4183     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4184 
4185     static const MCPhysReg FPArgRegs[] = {
4186       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4187       PPC::F8
4188     };
4189     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4190 
4191     if (useSoftFloat() || hasSPE())
4192        NumFPArgRegs = 0;
4193 
4194     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4195     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4196 
4197     // Make room for NumGPArgRegs and NumFPArgRegs.
4198     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4199                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4200 
4201     FuncInfo->setVarArgsStackOffset(
4202       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4203                             CCInfo.getNextStackOffset(), true));
4204 
4205     FuncInfo->setVarArgsFrameIndex(
4206         MFI.CreateStackObject(Depth, Align(8), false));
4207     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4208 
4209     // The fixed integer arguments of a variadic function are stored to the
4210     // VarArgsFrameIndex on the stack so that they may be loaded by
4211     // dereferencing the result of va_next.
4212     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4213       // Get an existing live-in vreg, or add a new one.
4214       Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4215       if (!VReg)
4216         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4217 
4218       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4219       SDValue Store =
4220           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4221       MemOps.push_back(Store);
4222       // Increment the address by four for the next argument to store
4223       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4224       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4225     }
4226 
4227     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4228     // is set.
4229     // The double arguments are stored to the VarArgsFrameIndex
4230     // on the stack.
4231     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4232       // Get an existing live-in vreg, or add a new one.
4233       Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4234       if (!VReg)
4235         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4236 
4237       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4238       SDValue Store =
4239           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4240       MemOps.push_back(Store);
4241       // Increment the address by eight for the next argument to store
4242       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4243                                          PtrVT);
4244       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4245     }
4246   }
4247 
4248   if (!MemOps.empty())
4249     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4250 
4251   return Chain;
4252 }
4253 
4254 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4255 // value to MVT::i64 and then truncate to the correct register size.
4256 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4257                                              EVT ObjectVT, SelectionDAG &DAG,
4258                                              SDValue ArgVal,
4259                                              const SDLoc &dl) const {
4260   if (Flags.isSExt())
4261     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4262                          DAG.getValueType(ObjectVT));
4263   else if (Flags.isZExt())
4264     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4265                          DAG.getValueType(ObjectVT));
4266 
4267   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4268 }
4269 
4270 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4271     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4272     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4273     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4274   // TODO: add description of PPC stack frame format, or at least some docs.
4275   //
4276   bool isELFv2ABI = Subtarget.isELFv2ABI();
4277   bool isLittleEndian = Subtarget.isLittleEndian();
4278   MachineFunction &MF = DAG.getMachineFunction();
4279   MachineFrameInfo &MFI = MF.getFrameInfo();
4280   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4281 
4282   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4283          "fastcc not supported on varargs functions");
4284 
4285   EVT PtrVT = getPointerTy(MF.getDataLayout());
4286   // Potential tail calls could cause overwriting of argument stack slots.
4287   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4288                        (CallConv == CallingConv::Fast));
4289   unsigned PtrByteSize = 8;
4290   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4291 
4292   static const MCPhysReg GPR[] = {
4293     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4294     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4295   };
4296   static const MCPhysReg VR[] = {
4297     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4298     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4299   };
4300 
4301   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4302   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4303   const unsigned Num_VR_Regs  = array_lengthof(VR);
4304 
4305   // Do a first pass over the arguments to determine whether the ABI
4306   // guarantees that our caller has allocated the parameter save area
4307   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4308   // in the ELFv2 ABI, it is true if this is a vararg function or if
4309   // any parameter is located in a stack slot.
4310 
4311   bool HasParameterArea = !isELFv2ABI || isVarArg;
4312   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4313   unsigned NumBytes = LinkageSize;
4314   unsigned AvailableFPRs = Num_FPR_Regs;
4315   unsigned AvailableVRs = Num_VR_Regs;
4316   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4317     if (Ins[i].Flags.isNest())
4318       continue;
4319 
4320     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4321                                PtrByteSize, LinkageSize, ParamAreaSize,
4322                                NumBytes, AvailableFPRs, AvailableVRs))
4323       HasParameterArea = true;
4324   }
4325 
4326   // Add DAG nodes to load the arguments or copy them out of registers.  On
4327   // entry to a function on PPC, the arguments start after the linkage area,
4328   // although the first ones are often in registers.
4329 
4330   unsigned ArgOffset = LinkageSize;
4331   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4332   SmallVector<SDValue, 8> MemOps;
4333   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4334   unsigned CurArgIdx = 0;
4335   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4336     SDValue ArgVal;
4337     bool needsLoad = false;
4338     EVT ObjectVT = Ins[ArgNo].VT;
4339     EVT OrigVT = Ins[ArgNo].ArgVT;
4340     unsigned ObjSize = ObjectVT.getStoreSize();
4341     unsigned ArgSize = ObjSize;
4342     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4343     if (Ins[ArgNo].isOrigArg()) {
4344       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4345       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4346     }
4347     // We re-align the argument offset for each argument, except when using the
4348     // fast calling convention, when we need to make sure we do that only when
4349     // we'll actually use a stack slot.
4350     unsigned CurArgOffset;
4351     Align Alignment;
4352     auto ComputeArgOffset = [&]() {
4353       /* Respect alignment of argument on the stack.  */
4354       Alignment =
4355           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4356       ArgOffset = alignTo(ArgOffset, Alignment);
4357       CurArgOffset = ArgOffset;
4358     };
4359 
4360     if (CallConv != CallingConv::Fast) {
4361       ComputeArgOffset();
4362 
4363       /* Compute GPR index associated with argument offset.  */
4364       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4365       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4366     }
4367 
4368     // FIXME the codegen can be much improved in some cases.
4369     // We do not have to keep everything in memory.
4370     if (Flags.isByVal()) {
4371       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4372 
4373       if (CallConv == CallingConv::Fast)
4374         ComputeArgOffset();
4375 
4376       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4377       ObjSize = Flags.getByValSize();
4378       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4379       // Empty aggregate parameters do not take up registers.  Examples:
4380       //   struct { } a;
4381       //   union  { } b;
4382       //   int c[0];
4383       // etc.  However, we have to provide a place-holder in InVals, so
4384       // pretend we have an 8-byte item at the current address for that
4385       // purpose.
4386       if (!ObjSize) {
4387         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4388         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4389         InVals.push_back(FIN);
4390         continue;
4391       }
4392 
4393       // Create a stack object covering all stack doublewords occupied
4394       // by the argument.  If the argument is (fully or partially) on
4395       // the stack, or if the argument is fully in registers but the
4396       // caller has allocated the parameter save anyway, we can refer
4397       // directly to the caller's stack frame.  Otherwise, create a
4398       // local copy in our own frame.
4399       int FI;
4400       if (HasParameterArea ||
4401           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4402         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4403       else
4404         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4405       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4406 
4407       // Handle aggregates smaller than 8 bytes.
4408       if (ObjSize < PtrByteSize) {
4409         // The value of the object is its address, which differs from the
4410         // address of the enclosing doubleword on big-endian systems.
4411         SDValue Arg = FIN;
4412         if (!isLittleEndian) {
4413           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4414           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4415         }
4416         InVals.push_back(Arg);
4417 
4418         if (GPR_idx != Num_GPR_Regs) {
4419           Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4420           FuncInfo->addLiveInAttr(VReg, Flags);
4421           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4422           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4423           SDValue Store =
4424               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4425                                 MachinePointerInfo(&*FuncArg), ObjType);
4426           MemOps.push_back(Store);
4427         }
4428         // Whether we copied from a register or not, advance the offset
4429         // into the parameter save area by a full doubleword.
4430         ArgOffset += PtrByteSize;
4431         continue;
4432       }
4433 
4434       // The value of the object is its address, which is the address of
4435       // its first stack doubleword.
4436       InVals.push_back(FIN);
4437 
4438       // Store whatever pieces of the object are in registers to memory.
4439       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4440         if (GPR_idx == Num_GPR_Regs)
4441           break;
4442 
4443         Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4444         FuncInfo->addLiveInAttr(VReg, Flags);
4445         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4446         SDValue Addr = FIN;
4447         if (j) {
4448           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4449           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4450         }
4451         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4452                                      MachinePointerInfo(&*FuncArg, j));
4453         MemOps.push_back(Store);
4454         ++GPR_idx;
4455       }
4456       ArgOffset += ArgSize;
4457       continue;
4458     }
4459 
4460     switch (ObjectVT.getSimpleVT().SimpleTy) {
4461     default: llvm_unreachable("Unhandled argument type!");
4462     case MVT::i1:
4463     case MVT::i32:
4464     case MVT::i64:
4465       if (Flags.isNest()) {
4466         // The 'nest' parameter, if any, is passed in R11.
4467         Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4468         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4469 
4470         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4471           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4472 
4473         break;
4474       }
4475 
4476       // These can be scalar arguments or elements of an integer array type
4477       // passed directly.  Clang may use those instead of "byval" aggregate
4478       // types to avoid forcing arguments to memory unnecessarily.
4479       if (GPR_idx != Num_GPR_Regs) {
4480         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4481         FuncInfo->addLiveInAttr(VReg, Flags);
4482         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4483 
4484         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4485           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4486           // value to MVT::i64 and then truncate to the correct register size.
4487           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4488       } else {
4489         if (CallConv == CallingConv::Fast)
4490           ComputeArgOffset();
4491 
4492         needsLoad = true;
4493         ArgSize = PtrByteSize;
4494       }
4495       if (CallConv != CallingConv::Fast || needsLoad)
4496         ArgOffset += 8;
4497       break;
4498 
4499     case MVT::f32:
4500     case MVT::f64:
4501       // These can be scalar arguments or elements of a float array type
4502       // passed directly.  The latter are used to implement ELFv2 homogenous
4503       // float aggregates.
4504       if (FPR_idx != Num_FPR_Regs) {
4505         unsigned VReg;
4506 
4507         if (ObjectVT == MVT::f32)
4508           VReg = MF.addLiveIn(FPR[FPR_idx],
4509                               Subtarget.hasP8Vector()
4510                                   ? &PPC::VSSRCRegClass
4511                                   : &PPC::F4RCRegClass);
4512         else
4513           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4514                                                 ? &PPC::VSFRCRegClass
4515                                                 : &PPC::F8RCRegClass);
4516 
4517         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4518         ++FPR_idx;
4519       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4520         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4521         // once we support fp <-> gpr moves.
4522 
4523         // This can only ever happen in the presence of f32 array types,
4524         // since otherwise we never run out of FPRs before running out
4525         // of GPRs.
4526         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4527         FuncInfo->addLiveInAttr(VReg, Flags);
4528         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4529 
4530         if (ObjectVT == MVT::f32) {
4531           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4532             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4533                                  DAG.getConstant(32, dl, MVT::i32));
4534           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4535         }
4536 
4537         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4538       } else {
4539         if (CallConv == CallingConv::Fast)
4540           ComputeArgOffset();
4541 
4542         needsLoad = true;
4543       }
4544 
4545       // When passing an array of floats, the array occupies consecutive
4546       // space in the argument area; only round up to the next doubleword
4547       // at the end of the array.  Otherwise, each float takes 8 bytes.
4548       if (CallConv != CallingConv::Fast || needsLoad) {
4549         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4550         ArgOffset += ArgSize;
4551         if (Flags.isInConsecutiveRegsLast())
4552           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4553       }
4554       break;
4555     case MVT::v4f32:
4556     case MVT::v4i32:
4557     case MVT::v8i16:
4558     case MVT::v16i8:
4559     case MVT::v2f64:
4560     case MVT::v2i64:
4561     case MVT::v1i128:
4562     case MVT::f128:
4563       // These can be scalar arguments or elements of a vector array type
4564       // passed directly.  The latter are used to implement ELFv2 homogenous
4565       // vector aggregates.
4566       if (VR_idx != Num_VR_Regs) {
4567         Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4568         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4569         ++VR_idx;
4570       } else {
4571         if (CallConv == CallingConv::Fast)
4572           ComputeArgOffset();
4573         needsLoad = true;
4574       }
4575       if (CallConv != CallingConv::Fast || needsLoad)
4576         ArgOffset += 16;
4577       break;
4578     }
4579 
4580     // We need to load the argument to a virtual register if we determined
4581     // above that we ran out of physical registers of the appropriate type.
4582     if (needsLoad) {
4583       if (ObjSize < ArgSize && !isLittleEndian)
4584         CurArgOffset += ArgSize - ObjSize;
4585       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4586       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4587       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4588     }
4589 
4590     InVals.push_back(ArgVal);
4591   }
4592 
4593   // Area that is at least reserved in the caller of this function.
4594   unsigned MinReservedArea;
4595   if (HasParameterArea)
4596     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4597   else
4598     MinReservedArea = LinkageSize;
4599 
4600   // Set the size that is at least reserved in caller of this function.  Tail
4601   // call optimized functions' reserved stack space needs to be aligned so that
4602   // taking the difference between two stack areas will result in an aligned
4603   // stack.
4604   MinReservedArea =
4605       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4606   FuncInfo->setMinReservedArea(MinReservedArea);
4607 
4608   // If the function takes variable number of arguments, make a frame index for
4609   // the start of the first vararg value... for expansion of llvm.va_start.
4610   // On ELFv2ABI spec, it writes:
4611   // C programs that are intended to be *portable* across different compilers
4612   // and architectures must use the header file <stdarg.h> to deal with variable
4613   // argument lists.
4614   if (isVarArg && MFI.hasVAStart()) {
4615     int Depth = ArgOffset;
4616 
4617     FuncInfo->setVarArgsFrameIndex(
4618       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4619     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4620 
4621     // If this function is vararg, store any remaining integer argument regs
4622     // to their spots on the stack so that they may be loaded by dereferencing
4623     // the result of va_next.
4624     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4625          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4626       Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4627       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4628       SDValue Store =
4629           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4630       MemOps.push_back(Store);
4631       // Increment the address by four for the next argument to store
4632       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4633       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4634     }
4635   }
4636 
4637   if (!MemOps.empty())
4638     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4639 
4640   return Chain;
4641 }
4642 
4643 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4644 /// adjusted to accommodate the arguments for the tailcall.
4645 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4646                                    unsigned ParamSize) {
4647 
4648   if (!isTailCall) return 0;
4649 
4650   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4651   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4652   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4653   // Remember only if the new adjustment is bigger.
4654   if (SPDiff < FI->getTailCallSPDelta())
4655     FI->setTailCallSPDelta(SPDiff);
4656 
4657   return SPDiff;
4658 }
4659 
4660 static bool isFunctionGlobalAddress(SDValue Callee);
4661 
4662 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4663                               const TargetMachine &TM) {
4664   // It does not make sense to call callsShareTOCBase() with a caller that
4665   // is PC Relative since PC Relative callers do not have a TOC.
4666 #ifndef NDEBUG
4667   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4668   assert(!STICaller->isUsingPCRelativeCalls() &&
4669          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4670 #endif
4671 
4672   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4673   // don't have enough information to determine if the caller and callee share
4674   // the same  TOC base, so we have to pessimistically assume they don't for
4675   // correctness.
4676   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4677   if (!G)
4678     return false;
4679 
4680   const GlobalValue *GV = G->getGlobal();
4681 
4682   // If the callee is preemptable, then the static linker will use a plt-stub
4683   // which saves the toc to the stack, and needs a nop after the call
4684   // instruction to convert to a toc-restore.
4685   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4686     return false;
4687 
4688   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4689   // We may need a TOC restore in the situation where the caller requires a
4690   // valid TOC but the callee is PC Relative and does not.
4691   const Function *F = dyn_cast<Function>(GV);
4692   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4693 
4694   // If we have an Alias we can try to get the function from there.
4695   if (Alias) {
4696     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4697     F = dyn_cast<Function>(GlobalObj);
4698   }
4699 
4700   // If we still have no valid function pointer we do not have enough
4701   // information to determine if the callee uses PC Relative calls so we must
4702   // assume that it does.
4703   if (!F)
4704     return false;
4705 
4706   // If the callee uses PC Relative we cannot guarantee that the callee won't
4707   // clobber the TOC of the caller and so we must assume that the two
4708   // functions do not share a TOC base.
4709   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4710   if (STICallee->isUsingPCRelativeCalls())
4711     return false;
4712 
4713   // If the GV is not a strong definition then we need to assume it can be
4714   // replaced by another function at link time. The function that replaces
4715   // it may not share the same TOC as the caller since the callee may be
4716   // replaced by a PC Relative version of the same function.
4717   if (!GV->isStrongDefinitionForLinker())
4718     return false;
4719 
4720   // The medium and large code models are expected to provide a sufficiently
4721   // large TOC to provide all data addressing needs of a module with a
4722   // single TOC.
4723   if (CodeModel::Medium == TM.getCodeModel() ||
4724       CodeModel::Large == TM.getCodeModel())
4725     return true;
4726 
4727   // Any explicitly-specified sections and section prefixes must also match.
4728   // Also, if we're using -ffunction-sections, then each function is always in
4729   // a different section (the same is true for COMDAT functions).
4730   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4731       GV->getSection() != Caller->getSection())
4732     return false;
4733   if (const auto *F = dyn_cast<Function>(GV)) {
4734     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4735       return false;
4736   }
4737 
4738   return true;
4739 }
4740 
4741 static bool
4742 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4743                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4744   assert(Subtarget.is64BitELFABI());
4745 
4746   const unsigned PtrByteSize = 8;
4747   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4748 
4749   static const MCPhysReg GPR[] = {
4750     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4751     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4752   };
4753   static const MCPhysReg VR[] = {
4754     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4755     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4756   };
4757 
4758   const unsigned NumGPRs = array_lengthof(GPR);
4759   const unsigned NumFPRs = 13;
4760   const unsigned NumVRs = array_lengthof(VR);
4761   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4762 
4763   unsigned NumBytes = LinkageSize;
4764   unsigned AvailableFPRs = NumFPRs;
4765   unsigned AvailableVRs = NumVRs;
4766 
4767   for (const ISD::OutputArg& Param : Outs) {
4768     if (Param.Flags.isNest()) continue;
4769 
4770     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4771                                LinkageSize, ParamAreaSize, NumBytes,
4772                                AvailableFPRs, AvailableVRs))
4773       return true;
4774   }
4775   return false;
4776 }
4777 
4778 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4779   if (CB.arg_size() != CallerFn->arg_size())
4780     return false;
4781 
4782   auto CalleeArgIter = CB.arg_begin();
4783   auto CalleeArgEnd = CB.arg_end();
4784   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4785 
4786   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4787     const Value* CalleeArg = *CalleeArgIter;
4788     const Value* CallerArg = &(*CallerArgIter);
4789     if (CalleeArg == CallerArg)
4790       continue;
4791 
4792     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4793     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4794     //      }
4795     // 1st argument of callee is undef and has the same type as caller.
4796     if (CalleeArg->getType() == CallerArg->getType() &&
4797         isa<UndefValue>(CalleeArg))
4798       continue;
4799 
4800     return false;
4801   }
4802 
4803   return true;
4804 }
4805 
4806 // Returns true if TCO is possible between the callers and callees
4807 // calling conventions.
4808 static bool
4809 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4810                                     CallingConv::ID CalleeCC) {
4811   // Tail calls are possible with fastcc and ccc.
4812   auto isTailCallableCC  = [] (CallingConv::ID CC){
4813       return  CC == CallingConv::C || CC == CallingConv::Fast;
4814   };
4815   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4816     return false;
4817 
4818   // We can safely tail call both fastcc and ccc callees from a c calling
4819   // convention caller. If the caller is fastcc, we may have less stack space
4820   // than a non-fastcc caller with the same signature so disable tail-calls in
4821   // that case.
4822   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4823 }
4824 
4825 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4826     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4827     const SmallVectorImpl<ISD::OutputArg> &Outs,
4828     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4829   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4830 
4831   if (DisableSCO && !TailCallOpt) return false;
4832 
4833   // Variadic argument functions are not supported.
4834   if (isVarArg) return false;
4835 
4836   auto &Caller = DAG.getMachineFunction().getFunction();
4837   // Check that the calling conventions are compatible for tco.
4838   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4839     return false;
4840 
4841   // Caller contains any byval parameter is not supported.
4842   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4843     return false;
4844 
4845   // Callee contains any byval parameter is not supported, too.
4846   // Note: This is a quick work around, because in some cases, e.g.
4847   // caller's stack size > callee's stack size, we are still able to apply
4848   // sibling call optimization. For example, gcc is able to do SCO for caller1
4849   // in the following example, but not for caller2.
4850   //   struct test {
4851   //     long int a;
4852   //     char ary[56];
4853   //   } gTest;
4854   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4855   //     b->a = v.a;
4856   //     return 0;
4857   //   }
4858   //   void caller1(struct test a, struct test c, struct test *b) {
4859   //     callee(gTest, b); }
4860   //   void caller2(struct test *b) { callee(gTest, b); }
4861   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4862     return false;
4863 
4864   // If callee and caller use different calling conventions, we cannot pass
4865   // parameters on stack since offsets for the parameter area may be different.
4866   if (Caller.getCallingConv() != CalleeCC &&
4867       needStackSlotPassParameters(Subtarget, Outs))
4868     return false;
4869 
4870   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4871   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4872   // callee potentially have different TOC bases then we cannot tail call since
4873   // we need to restore the TOC pointer after the call.
4874   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4875   // We cannot guarantee this for indirect calls or calls to external functions.
4876   // When PC-Relative addressing is used, the concept of the TOC is no longer
4877   // applicable so this check is not required.
4878   // Check first for indirect calls.
4879   if (!Subtarget.isUsingPCRelativeCalls() &&
4880       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4881     return false;
4882 
4883   // Check if we share the TOC base.
4884   if (!Subtarget.isUsingPCRelativeCalls() &&
4885       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4886     return false;
4887 
4888   // TCO allows altering callee ABI, so we don't have to check further.
4889   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4890     return true;
4891 
4892   if (DisableSCO) return false;
4893 
4894   // If callee use the same argument list that caller is using, then we can
4895   // apply SCO on this case. If it is not, then we need to check if callee needs
4896   // stack for passing arguments.
4897   // PC Relative tail calls may not have a CallBase.
4898   // If there is no CallBase we cannot verify if we have the same argument
4899   // list so assume that we don't have the same argument list.
4900   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4901       needStackSlotPassParameters(Subtarget, Outs))
4902     return false;
4903   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4904     return false;
4905 
4906   return true;
4907 }
4908 
4909 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4910 /// for tail call optimization. Targets which want to do tail call
4911 /// optimization should implement this function.
4912 bool
4913 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4914                                                      CallingConv::ID CalleeCC,
4915                                                      bool isVarArg,
4916                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4917                                                      SelectionDAG& DAG) const {
4918   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4919     return false;
4920 
4921   // Variable argument functions are not supported.
4922   if (isVarArg)
4923     return false;
4924 
4925   MachineFunction &MF = DAG.getMachineFunction();
4926   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4927   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4928     // Functions containing by val parameters are not supported.
4929     for (unsigned i = 0; i != Ins.size(); i++) {
4930        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4931        if (Flags.isByVal()) return false;
4932     }
4933 
4934     // Non-PIC/GOT tail calls are supported.
4935     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4936       return true;
4937 
4938     // At the moment we can only do local tail calls (in same module, hidden
4939     // or protected) if we are generating PIC.
4940     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4941       return G->getGlobal()->hasHiddenVisibility()
4942           || G->getGlobal()->hasProtectedVisibility();
4943   }
4944 
4945   return false;
4946 }
4947 
4948 /// isCallCompatibleAddress - Return the immediate to use if the specified
4949 /// 32-bit value is representable in the immediate field of a BxA instruction.
4950 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4951   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4952   if (!C) return nullptr;
4953 
4954   int Addr = C->getZExtValue();
4955   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4956       SignExtend32<26>(Addr) != Addr)
4957     return nullptr;  // Top 6 bits have to be sext of immediate.
4958 
4959   return DAG
4960       .getConstant(
4961           (int)C->getZExtValue() >> 2, SDLoc(Op),
4962           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4963       .getNode();
4964 }
4965 
4966 namespace {
4967 
4968 struct TailCallArgumentInfo {
4969   SDValue Arg;
4970   SDValue FrameIdxOp;
4971   int FrameIdx = 0;
4972 
4973   TailCallArgumentInfo() = default;
4974 };
4975 
4976 } // end anonymous namespace
4977 
4978 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4979 static void StoreTailCallArgumentsToStackSlot(
4980     SelectionDAG &DAG, SDValue Chain,
4981     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4982     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4983   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4984     SDValue Arg = TailCallArgs[i].Arg;
4985     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4986     int FI = TailCallArgs[i].FrameIdx;
4987     // Store relative to framepointer.
4988     MemOpChains.push_back(DAG.getStore(
4989         Chain, dl, Arg, FIN,
4990         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4991   }
4992 }
4993 
4994 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4995 /// the appropriate stack slot for the tail call optimized function call.
4996 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4997                                              SDValue OldRetAddr, SDValue OldFP,
4998                                              int SPDiff, const SDLoc &dl) {
4999   if (SPDiff) {
5000     // Calculate the new stack slot for the return address.
5001     MachineFunction &MF = DAG.getMachineFunction();
5002     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5003     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5004     bool isPPC64 = Subtarget.isPPC64();
5005     int SlotSize = isPPC64 ? 8 : 4;
5006     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5007     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5008                                                          NewRetAddrLoc, true);
5009     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5010     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5011     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5012                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5013   }
5014   return Chain;
5015 }
5016 
5017 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5018 /// the position of the argument.
5019 static void
5020 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5021                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5022                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5023   int Offset = ArgOffset + SPDiff;
5024   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5025   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5026   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5027   SDValue FIN = DAG.getFrameIndex(FI, VT);
5028   TailCallArgumentInfo Info;
5029   Info.Arg = Arg;
5030   Info.FrameIdxOp = FIN;
5031   Info.FrameIdx = FI;
5032   TailCallArguments.push_back(Info);
5033 }
5034 
5035 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5036 /// stack slot. Returns the chain as result and the loaded frame pointers in
5037 /// LROpOut/FPOpout. Used when tail calling.
5038 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5039     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5040     SDValue &FPOpOut, const SDLoc &dl) const {
5041   if (SPDiff) {
5042     // Load the LR and FP stack slot for later adjusting.
5043     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5044     LROpOut = getReturnAddrFrameIndex(DAG);
5045     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5046     Chain = SDValue(LROpOut.getNode(), 1);
5047   }
5048   return Chain;
5049 }
5050 
5051 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5052 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5053 /// specified by the specific parameter attribute. The copy will be passed as
5054 /// a byval function parameter.
5055 /// Sometimes what we are copying is the end of a larger object, the part that
5056 /// does not fit in registers.
5057 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5058                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5059                                          SelectionDAG &DAG, const SDLoc &dl) {
5060   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5061   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5062                        Flags.getNonZeroByValAlign(), false, false, false,
5063                        MachinePointerInfo(), MachinePointerInfo());
5064 }
5065 
5066 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5067 /// tail calls.
5068 static void LowerMemOpCallTo(
5069     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5070     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5071     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5072     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5073   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5074   if (!isTailCall) {
5075     if (isVector) {
5076       SDValue StackPtr;
5077       if (isPPC64)
5078         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5079       else
5080         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5081       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5082                            DAG.getConstant(ArgOffset, dl, PtrVT));
5083     }
5084     MemOpChains.push_back(
5085         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5086     // Calculate and remember argument location.
5087   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5088                                   TailCallArguments);
5089 }
5090 
5091 static void
5092 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5093                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5094                 SDValue FPOp,
5095                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5096   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5097   // might overwrite each other in case of tail call optimization.
5098   SmallVector<SDValue, 8> MemOpChains2;
5099   // Do not flag preceding copytoreg stuff together with the following stuff.
5100   InFlag = SDValue();
5101   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5102                                     MemOpChains2, dl);
5103   if (!MemOpChains2.empty())
5104     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5105 
5106   // Store the return address to the appropriate stack slot.
5107   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5108 
5109   // Emit callseq_end just before tailcall node.
5110   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5111                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5112   InFlag = Chain.getValue(1);
5113 }
5114 
5115 // Is this global address that of a function that can be called by name? (as
5116 // opposed to something that must hold a descriptor for an indirect call).
5117 static bool isFunctionGlobalAddress(SDValue Callee) {
5118   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5119     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5120         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5121       return false;
5122 
5123     return G->getGlobal()->getValueType()->isFunctionTy();
5124   }
5125 
5126   return false;
5127 }
5128 
5129 SDValue PPCTargetLowering::LowerCallResult(
5130     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5131     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5132     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5133   SmallVector<CCValAssign, 16> RVLocs;
5134   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5135                     *DAG.getContext());
5136 
5137   CCRetInfo.AnalyzeCallResult(
5138       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5139                ? RetCC_PPC_Cold
5140                : RetCC_PPC);
5141 
5142   // Copy all of the result registers out of their specified physreg.
5143   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5144     CCValAssign &VA = RVLocs[i];
5145     assert(VA.isRegLoc() && "Can only return in registers!");
5146 
5147     SDValue Val;
5148 
5149     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5150       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5151                                       InFlag);
5152       Chain = Lo.getValue(1);
5153       InFlag = Lo.getValue(2);
5154       VA = RVLocs[++i]; // skip ahead to next loc
5155       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5156                                       InFlag);
5157       Chain = Hi.getValue(1);
5158       InFlag = Hi.getValue(2);
5159       if (!Subtarget.isLittleEndian())
5160         std::swap (Lo, Hi);
5161       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5162     } else {
5163       Val = DAG.getCopyFromReg(Chain, dl,
5164                                VA.getLocReg(), VA.getLocVT(), InFlag);
5165       Chain = Val.getValue(1);
5166       InFlag = Val.getValue(2);
5167     }
5168 
5169     switch (VA.getLocInfo()) {
5170     default: llvm_unreachable("Unknown loc info!");
5171     case CCValAssign::Full: break;
5172     case CCValAssign::AExt:
5173       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5174       break;
5175     case CCValAssign::ZExt:
5176       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5177                         DAG.getValueType(VA.getValVT()));
5178       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5179       break;
5180     case CCValAssign::SExt:
5181       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5182                         DAG.getValueType(VA.getValVT()));
5183       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5184       break;
5185     }
5186 
5187     InVals.push_back(Val);
5188   }
5189 
5190   return Chain;
5191 }
5192 
5193 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5194                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5195   // PatchPoint calls are not indirect.
5196   if (isPatchPoint)
5197     return false;
5198 
5199   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5200     return false;
5201 
5202   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5203   // becuase the immediate function pointer points to a descriptor instead of
5204   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5205   // pointer immediate points to the global entry point, while the BLA would
5206   // need to jump to the local entry point (see rL211174).
5207   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5208       isBLACompatibleAddress(Callee, DAG))
5209     return false;
5210 
5211   return true;
5212 }
5213 
5214 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5215 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5216   return Subtarget.isAIXABI() ||
5217          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5218 }
5219 
5220 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5221                               const Function &Caller, const SDValue &Callee,
5222                               const PPCSubtarget &Subtarget,
5223                               const TargetMachine &TM,
5224                               bool IsStrictFPCall = false) {
5225   if (CFlags.IsTailCall)
5226     return PPCISD::TC_RETURN;
5227 
5228   unsigned RetOpc = 0;
5229   // This is a call through a function pointer.
5230   if (CFlags.IsIndirect) {
5231     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5232     // indirect calls. The save of the caller's TOC pointer to the stack will be
5233     // inserted into the DAG as part of call lowering. The restore of the TOC
5234     // pointer is modeled by using a pseudo instruction for the call opcode that
5235     // represents the 2 instruction sequence of an indirect branch and link,
5236     // immediately followed by a load of the TOC pointer from the the stack save
5237     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5238     // as it is not saved or used.
5239     RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5240                                                  : PPCISD::BCTRL;
5241   } else if (Subtarget.isUsingPCRelativeCalls()) {
5242     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5243     RetOpc = PPCISD::CALL_NOTOC;
5244   } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5245     // The ABIs that maintain a TOC pointer accross calls need to have a nop
5246     // immediately following the call instruction if the caller and callee may
5247     // have different TOC bases. At link time if the linker determines the calls
5248     // may not share a TOC base, the call is redirected to a trampoline inserted
5249     // by the linker. The trampoline will (among other things) save the callers
5250     // TOC pointer at an ABI designated offset in the linkage area and the
5251     // linker will rewrite the nop to be a load of the TOC pointer from the
5252     // linkage area into gpr2.
5253     RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5254                                                     : PPCISD::CALL_NOP;
5255   else
5256     RetOpc = PPCISD::CALL;
5257   if (IsStrictFPCall) {
5258     switch (RetOpc) {
5259     default:
5260       llvm_unreachable("Unknown call opcode");
5261     case PPCISD::BCTRL_LOAD_TOC:
5262       RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5263       break;
5264     case PPCISD::BCTRL:
5265       RetOpc = PPCISD::BCTRL_RM;
5266       break;
5267     case PPCISD::CALL_NOTOC:
5268       RetOpc = PPCISD::CALL_NOTOC_RM;
5269       break;
5270     case PPCISD::CALL:
5271       RetOpc = PPCISD::CALL_RM;
5272       break;
5273     case PPCISD::CALL_NOP:
5274       RetOpc = PPCISD::CALL_NOP_RM;
5275       break;
5276     }
5277   }
5278   return RetOpc;
5279 }
5280 
5281 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5282                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5283   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5284     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5285       return SDValue(Dest, 0);
5286 
5287   // Returns true if the callee is local, and false otherwise.
5288   auto isLocalCallee = [&]() {
5289     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5290     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5291     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5292 
5293     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5294            !isa_and_nonnull<GlobalIFunc>(GV);
5295   };
5296 
5297   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5298   // a static relocation model causes some versions of GNU LD (2.17.50, at
5299   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5300   // built with secure-PLT.
5301   bool UsePlt =
5302       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5303       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5304 
5305   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5306     const TargetMachine &TM = Subtarget.getTargetMachine();
5307     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5308     MCSymbolXCOFF *S =
5309         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5310 
5311     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5312     return DAG.getMCSymbol(S, PtrVT);
5313   };
5314 
5315   if (isFunctionGlobalAddress(Callee)) {
5316     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5317 
5318     if (Subtarget.isAIXABI()) {
5319       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5320       return getAIXFuncEntryPointSymbolSDNode(GV);
5321     }
5322     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5323                                       UsePlt ? PPCII::MO_PLT : 0);
5324   }
5325 
5326   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5327     const char *SymName = S->getSymbol();
5328     if (Subtarget.isAIXABI()) {
5329       // If there exists a user-declared function whose name is the same as the
5330       // ExternalSymbol's, then we pick up the user-declared version.
5331       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5332       if (const Function *F =
5333               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5334         return getAIXFuncEntryPointSymbolSDNode(F);
5335 
5336       // On AIX, direct function calls reference the symbol for the function's
5337       // entry point, which is named by prepending a "." before the function's
5338       // C-linkage name. A Qualname is returned here because an external
5339       // function entry point is a csect with XTY_ER property.
5340       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5341         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5342         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5343             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5344             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5345         return Sec->getQualNameSymbol();
5346       };
5347 
5348       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5349     }
5350     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5351                                        UsePlt ? PPCII::MO_PLT : 0);
5352   }
5353 
5354   // No transformation needed.
5355   assert(Callee.getNode() && "What no callee?");
5356   return Callee;
5357 }
5358 
5359 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5360   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5361          "Expected a CALLSEQ_STARTSDNode.");
5362 
5363   // The last operand is the chain, except when the node has glue. If the node
5364   // has glue, then the last operand is the glue, and the chain is the second
5365   // last operand.
5366   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5367   if (LastValue.getValueType() != MVT::Glue)
5368     return LastValue;
5369 
5370   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5371 }
5372 
5373 // Creates the node that moves a functions address into the count register
5374 // to prepare for an indirect call instruction.
5375 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5376                                 SDValue &Glue, SDValue &Chain,
5377                                 const SDLoc &dl) {
5378   SDValue MTCTROps[] = {Chain, Callee, Glue};
5379   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5380   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5381                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5382   // The glue is the second value produced.
5383   Glue = Chain.getValue(1);
5384 }
5385 
5386 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5387                                           SDValue &Glue, SDValue &Chain,
5388                                           SDValue CallSeqStart,
5389                                           const CallBase *CB, const SDLoc &dl,
5390                                           bool hasNest,
5391                                           const PPCSubtarget &Subtarget) {
5392   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5393   // entry point, but to the function descriptor (the function entry point
5394   // address is part of the function descriptor though).
5395   // The function descriptor is a three doubleword structure with the
5396   // following fields: function entry point, TOC base address and
5397   // environment pointer.
5398   // Thus for a call through a function pointer, the following actions need
5399   // to be performed:
5400   //   1. Save the TOC of the caller in the TOC save area of its stack
5401   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5402   //   2. Load the address of the function entry point from the function
5403   //      descriptor.
5404   //   3. Load the TOC of the callee from the function descriptor into r2.
5405   //   4. Load the environment pointer from the function descriptor into
5406   //      r11.
5407   //   5. Branch to the function entry point address.
5408   //   6. On return of the callee, the TOC of the caller needs to be
5409   //      restored (this is done in FinishCall()).
5410   //
5411   // The loads are scheduled at the beginning of the call sequence, and the
5412   // register copies are flagged together to ensure that no other
5413   // operations can be scheduled in between. E.g. without flagging the
5414   // copies together, a TOC access in the caller could be scheduled between
5415   // the assignment of the callee TOC and the branch to the callee, which leads
5416   // to incorrect code.
5417 
5418   // Start by loading the function address from the descriptor.
5419   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5420   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5421                       ? (MachineMemOperand::MODereferenceable |
5422                          MachineMemOperand::MOInvariant)
5423                       : MachineMemOperand::MONone;
5424 
5425   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5426 
5427   // Registers used in building the DAG.
5428   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5429   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5430 
5431   // Offsets of descriptor members.
5432   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5433   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5434 
5435   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5436   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5437 
5438   // One load for the functions entry point address.
5439   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5440                                     Alignment, MMOFlags);
5441 
5442   // One for loading the TOC anchor for the module that contains the called
5443   // function.
5444   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5445   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5446   SDValue TOCPtr =
5447       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5448                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5449 
5450   // One for loading the environment pointer.
5451   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5452   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5453   SDValue LoadEnvPtr =
5454       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5455                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5456 
5457 
5458   // Then copy the newly loaded TOC anchor to the TOC pointer.
5459   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5460   Chain = TOCVal.getValue(0);
5461   Glue = TOCVal.getValue(1);
5462 
5463   // If the function call has an explicit 'nest' parameter, it takes the
5464   // place of the environment pointer.
5465   assert((!hasNest || !Subtarget.isAIXABI()) &&
5466          "Nest parameter is not supported on AIX.");
5467   if (!hasNest) {
5468     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5469     Chain = EnvVal.getValue(0);
5470     Glue = EnvVal.getValue(1);
5471   }
5472 
5473   // The rest of the indirect call sequence is the same as the non-descriptor
5474   // DAG.
5475   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5476 }
5477 
5478 static void
5479 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5480                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5481                   SelectionDAG &DAG,
5482                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5483                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5484                   const PPCSubtarget &Subtarget) {
5485   const bool IsPPC64 = Subtarget.isPPC64();
5486   // MVT for a general purpose register.
5487   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5488 
5489   // First operand is always the chain.
5490   Ops.push_back(Chain);
5491 
5492   // If it's a direct call pass the callee as the second operand.
5493   if (!CFlags.IsIndirect)
5494     Ops.push_back(Callee);
5495   else {
5496     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5497 
5498     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5499     // on the stack (this would have been done in `LowerCall_64SVR4` or
5500     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5501     // represents both the indirect branch and a load that restores the TOC
5502     // pointer from the linkage area. The operand for the TOC restore is an add
5503     // of the TOC save offset to the stack pointer. This must be the second
5504     // operand: after the chain input but before any other variadic arguments.
5505     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5506     // saved or used.
5507     if (isTOCSaveRestoreRequired(Subtarget)) {
5508       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5509 
5510       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5511       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5512       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5513       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5514       Ops.push_back(AddTOC);
5515     }
5516 
5517     // Add the register used for the environment pointer.
5518     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5519       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5520                                     RegVT));
5521 
5522 
5523     // Add CTR register as callee so a bctr can be emitted later.
5524     if (CFlags.IsTailCall)
5525       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5526   }
5527 
5528   // If this is a tail call add stack pointer delta.
5529   if (CFlags.IsTailCall)
5530     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5531 
5532   // Add argument registers to the end of the list so that they are known live
5533   // into the call.
5534   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5535     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5536                                   RegsToPass[i].second.getValueType()));
5537 
5538   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5539   // no way to mark dependencies as implicit here.
5540   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5541   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5542        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5543     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5544 
5545   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5546   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5547     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5548 
5549   // Add a register mask operand representing the call-preserved registers.
5550   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5551   const uint32_t *Mask =
5552       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5553   assert(Mask && "Missing call preserved mask for calling convention");
5554   Ops.push_back(DAG.getRegisterMask(Mask));
5555 
5556   // If the glue is valid, it is the last operand.
5557   if (Glue.getNode())
5558     Ops.push_back(Glue);
5559 }
5560 
5561 SDValue PPCTargetLowering::FinishCall(
5562     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5563     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5564     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5565     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5566     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5567 
5568   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5569       Subtarget.isAIXABI())
5570     setUsesTOCBasePtr(DAG);
5571 
5572   unsigned CallOpc =
5573       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5574                     Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5575 
5576   if (!CFlags.IsIndirect)
5577     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5578   else if (Subtarget.usesFunctionDescriptors())
5579     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5580                                   dl, CFlags.HasNest, Subtarget);
5581   else
5582     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5583 
5584   // Build the operand list for the call instruction.
5585   SmallVector<SDValue, 8> Ops;
5586   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5587                     SPDiff, Subtarget);
5588 
5589   // Emit tail call.
5590   if (CFlags.IsTailCall) {
5591     // Indirect tail call when using PC Relative calls do not have the same
5592     // constraints.
5593     assert(((Callee.getOpcode() == ISD::Register &&
5594              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5595             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5596             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5597             isa<ConstantSDNode>(Callee) ||
5598             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5599            "Expecting a global address, external symbol, absolute value, "
5600            "register or an indirect tail call when PC Relative calls are "
5601            "used.");
5602     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5603     assert(CallOpc == PPCISD::TC_RETURN &&
5604            "Unexpected call opcode for a tail call.");
5605     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5606     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5607   }
5608 
5609   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5610   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5611   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5612   Glue = Chain.getValue(1);
5613 
5614   // When performing tail call optimization the callee pops its arguments off
5615   // the stack. Account for this here so these bytes can be pushed back on in
5616   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5617   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5618                          getTargetMachine().Options.GuaranteedTailCallOpt)
5619                             ? NumBytes
5620                             : 0;
5621 
5622   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5623                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5624                              Glue, dl);
5625   Glue = Chain.getValue(1);
5626 
5627   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5628                          DAG, InVals);
5629 }
5630 
5631 SDValue
5632 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5633                              SmallVectorImpl<SDValue> &InVals) const {
5634   SelectionDAG &DAG                     = CLI.DAG;
5635   SDLoc &dl                             = CLI.DL;
5636   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5637   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5638   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5639   SDValue Chain                         = CLI.Chain;
5640   SDValue Callee                        = CLI.Callee;
5641   bool &isTailCall                      = CLI.IsTailCall;
5642   CallingConv::ID CallConv              = CLI.CallConv;
5643   bool isVarArg                         = CLI.IsVarArg;
5644   bool isPatchPoint                     = CLI.IsPatchPoint;
5645   const CallBase *CB                    = CLI.CB;
5646 
5647   if (isTailCall) {
5648     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5649       isTailCall = false;
5650     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5651       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5652           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5653     else
5654       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5655                                                      Ins, DAG);
5656     if (isTailCall) {
5657       ++NumTailCalls;
5658       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5659         ++NumSiblingCalls;
5660 
5661       // PC Relative calls no longer guarantee that the callee is a Global
5662       // Address Node. The callee could be an indirect tail call in which
5663       // case the SDValue for the callee could be a load (to load the address
5664       // of a function pointer) or it may be a register copy (to move the
5665       // address of the callee from a function parameter into a virtual
5666       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5667       assert((Subtarget.isUsingPCRelativeCalls() ||
5668               isa<GlobalAddressSDNode>(Callee)) &&
5669              "Callee should be an llvm::Function object.");
5670 
5671       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5672                         << "\nTCO callee: ");
5673       LLVM_DEBUG(Callee.dump());
5674     }
5675   }
5676 
5677   if (!isTailCall && CB && CB->isMustTailCall())
5678     report_fatal_error("failed to perform tail call elimination on a call "
5679                        "site marked musttail");
5680 
5681   // When long calls (i.e. indirect calls) are always used, calls are always
5682   // made via function pointer. If we have a function name, first translate it
5683   // into a pointer.
5684   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5685       !isTailCall)
5686     Callee = LowerGlobalAddress(Callee, DAG);
5687 
5688   CallFlags CFlags(
5689       CallConv, isTailCall, isVarArg, isPatchPoint,
5690       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5691       // hasNest
5692       Subtarget.is64BitELFABI() &&
5693           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5694       CLI.NoMerge);
5695 
5696   if (Subtarget.isAIXABI())
5697     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5698                          InVals, CB);
5699 
5700   assert(Subtarget.isSVR4ABI());
5701   if (Subtarget.isPPC64())
5702     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5703                             InVals, CB);
5704   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5705                           InVals, CB);
5706 }
5707 
5708 SDValue PPCTargetLowering::LowerCall_32SVR4(
5709     SDValue Chain, SDValue Callee, CallFlags CFlags,
5710     const SmallVectorImpl<ISD::OutputArg> &Outs,
5711     const SmallVectorImpl<SDValue> &OutVals,
5712     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5713     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5714     const CallBase *CB) const {
5715   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5716   // of the 32-bit SVR4 ABI stack frame layout.
5717 
5718   const CallingConv::ID CallConv = CFlags.CallConv;
5719   const bool IsVarArg = CFlags.IsVarArg;
5720   const bool IsTailCall = CFlags.IsTailCall;
5721 
5722   assert((CallConv == CallingConv::C ||
5723           CallConv == CallingConv::Cold ||
5724           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5725 
5726   const Align PtrAlign(4);
5727 
5728   MachineFunction &MF = DAG.getMachineFunction();
5729 
5730   // Mark this function as potentially containing a function that contains a
5731   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5732   // and restoring the callers stack pointer in this functions epilog. This is
5733   // done because by tail calling the called function might overwrite the value
5734   // in this function's (MF) stack pointer stack slot 0(SP).
5735   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5736       CallConv == CallingConv::Fast)
5737     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5738 
5739   // Count how many bytes are to be pushed on the stack, including the linkage
5740   // area, parameter list area and the part of the local variable space which
5741   // contains copies of aggregates which are passed by value.
5742 
5743   // Assign locations to all of the outgoing arguments.
5744   SmallVector<CCValAssign, 16> ArgLocs;
5745   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5746 
5747   // Reserve space for the linkage area on the stack.
5748   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5749                        PtrAlign);
5750   if (useSoftFloat())
5751     CCInfo.PreAnalyzeCallOperands(Outs);
5752 
5753   if (IsVarArg) {
5754     // Handle fixed and variable vector arguments differently.
5755     // Fixed vector arguments go into registers as long as registers are
5756     // available. Variable vector arguments always go into memory.
5757     unsigned NumArgs = Outs.size();
5758 
5759     for (unsigned i = 0; i != NumArgs; ++i) {
5760       MVT ArgVT = Outs[i].VT;
5761       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5762       bool Result;
5763 
5764       if (Outs[i].IsFixed) {
5765         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5766                                CCInfo);
5767       } else {
5768         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5769                                       ArgFlags, CCInfo);
5770       }
5771 
5772       if (Result) {
5773 #ifndef NDEBUG
5774         errs() << "Call operand #" << i << " has unhandled type "
5775              << EVT(ArgVT).getEVTString() << "\n";
5776 #endif
5777         llvm_unreachable(nullptr);
5778       }
5779     }
5780   } else {
5781     // All arguments are treated the same.
5782     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5783   }
5784   CCInfo.clearWasPPCF128();
5785 
5786   // Assign locations to all of the outgoing aggregate by value arguments.
5787   SmallVector<CCValAssign, 16> ByValArgLocs;
5788   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5789 
5790   // Reserve stack space for the allocations in CCInfo.
5791   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5792 
5793   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5794 
5795   // Size of the linkage area, parameter list area and the part of the local
5796   // space variable where copies of aggregates which are passed by value are
5797   // stored.
5798   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5799 
5800   // Calculate by how many bytes the stack has to be adjusted in case of tail
5801   // call optimization.
5802   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5803 
5804   // Adjust the stack pointer for the new arguments...
5805   // These operations are automatically eliminated by the prolog/epilog pass
5806   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5807   SDValue CallSeqStart = Chain;
5808 
5809   // Load the return address and frame pointer so it can be moved somewhere else
5810   // later.
5811   SDValue LROp, FPOp;
5812   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5813 
5814   // Set up a copy of the stack pointer for use loading and storing any
5815   // arguments that may not fit in the registers available for argument
5816   // passing.
5817   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5818 
5819   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5820   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5821   SmallVector<SDValue, 8> MemOpChains;
5822 
5823   bool seenFloatArg = false;
5824   // Walk the register/memloc assignments, inserting copies/loads.
5825   // i - Tracks the index into the list of registers allocated for the call
5826   // RealArgIdx - Tracks the index into the list of actual function arguments
5827   // j - Tracks the index into the list of byval arguments
5828   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5829        i != e;
5830        ++i, ++RealArgIdx) {
5831     CCValAssign &VA = ArgLocs[i];
5832     SDValue Arg = OutVals[RealArgIdx];
5833     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5834 
5835     if (Flags.isByVal()) {
5836       // Argument is an aggregate which is passed by value, thus we need to
5837       // create a copy of it in the local variable space of the current stack
5838       // frame (which is the stack frame of the caller) and pass the address of
5839       // this copy to the callee.
5840       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5841       CCValAssign &ByValVA = ByValArgLocs[j++];
5842       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5843 
5844       // Memory reserved in the local variable space of the callers stack frame.
5845       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5846 
5847       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5848       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5849                            StackPtr, PtrOff);
5850 
5851       // Create a copy of the argument in the local area of the current
5852       // stack frame.
5853       SDValue MemcpyCall =
5854         CreateCopyOfByValArgument(Arg, PtrOff,
5855                                   CallSeqStart.getNode()->getOperand(0),
5856                                   Flags, DAG, dl);
5857 
5858       // This must go outside the CALLSEQ_START..END.
5859       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5860                                                      SDLoc(MemcpyCall));
5861       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5862                              NewCallSeqStart.getNode());
5863       Chain = CallSeqStart = NewCallSeqStart;
5864 
5865       // Pass the address of the aggregate copy on the stack either in a
5866       // physical register or in the parameter list area of the current stack
5867       // frame to the callee.
5868       Arg = PtrOff;
5869     }
5870 
5871     // When useCRBits() is true, there can be i1 arguments.
5872     // It is because getRegisterType(MVT::i1) => MVT::i1,
5873     // and for other integer types getRegisterType() => MVT::i32.
5874     // Extend i1 and ensure callee will get i32.
5875     if (Arg.getValueType() == MVT::i1)
5876       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5877                         dl, MVT::i32, Arg);
5878 
5879     if (VA.isRegLoc()) {
5880       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5881       // Put argument in a physical register.
5882       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5883         bool IsLE = Subtarget.isLittleEndian();
5884         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5885                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5886         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5887         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5888                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5889         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5890                              SVal.getValue(0)));
5891       } else
5892         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5893     } else {
5894       // Put argument in the parameter list area of the current stack frame.
5895       assert(VA.isMemLoc());
5896       unsigned LocMemOffset = VA.getLocMemOffset();
5897 
5898       if (!IsTailCall) {
5899         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5900         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5901                              StackPtr, PtrOff);
5902 
5903         MemOpChains.push_back(
5904             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5905       } else {
5906         // Calculate and remember argument location.
5907         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5908                                  TailCallArguments);
5909       }
5910     }
5911   }
5912 
5913   if (!MemOpChains.empty())
5914     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5915 
5916   // Build a sequence of copy-to-reg nodes chained together with token chain
5917   // and flag operands which copy the outgoing args into the appropriate regs.
5918   SDValue InFlag;
5919   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5920     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5921                              RegsToPass[i].second, InFlag);
5922     InFlag = Chain.getValue(1);
5923   }
5924 
5925   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5926   // registers.
5927   if (IsVarArg) {
5928     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5929     SDValue Ops[] = { Chain, InFlag };
5930 
5931     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5932                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5933 
5934     InFlag = Chain.getValue(1);
5935   }
5936 
5937   if (IsTailCall)
5938     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5939                     TailCallArguments);
5940 
5941   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5942                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5943 }
5944 
5945 // Copy an argument into memory, being careful to do this outside the
5946 // call sequence for the call to which the argument belongs.
5947 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5948     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5949     SelectionDAG &DAG, const SDLoc &dl) const {
5950   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5951                         CallSeqStart.getNode()->getOperand(0),
5952                         Flags, DAG, dl);
5953   // The MEMCPY must go outside the CALLSEQ_START..END.
5954   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5955   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5956                                                  SDLoc(MemcpyCall));
5957   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5958                          NewCallSeqStart.getNode());
5959   return NewCallSeqStart;
5960 }
5961 
5962 SDValue PPCTargetLowering::LowerCall_64SVR4(
5963     SDValue Chain, SDValue Callee, CallFlags CFlags,
5964     const SmallVectorImpl<ISD::OutputArg> &Outs,
5965     const SmallVectorImpl<SDValue> &OutVals,
5966     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5967     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5968     const CallBase *CB) const {
5969   bool isELFv2ABI = Subtarget.isELFv2ABI();
5970   bool isLittleEndian = Subtarget.isLittleEndian();
5971   unsigned NumOps = Outs.size();
5972   bool IsSibCall = false;
5973   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5974 
5975   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5976   unsigned PtrByteSize = 8;
5977 
5978   MachineFunction &MF = DAG.getMachineFunction();
5979 
5980   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5981     IsSibCall = true;
5982 
5983   // Mark this function as potentially containing a function that contains a
5984   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5985   // and restoring the callers stack pointer in this functions epilog. This is
5986   // done because by tail calling the called function might overwrite the value
5987   // in this function's (MF) stack pointer stack slot 0(SP).
5988   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5989     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5990 
5991   assert(!(IsFastCall && CFlags.IsVarArg) &&
5992          "fastcc not supported on varargs functions");
5993 
5994   // Count how many bytes are to be pushed on the stack, including the linkage
5995   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5996   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5997   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5998   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5999   unsigned NumBytes = LinkageSize;
6000   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6001 
6002   static const MCPhysReg GPR[] = {
6003     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6004     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6005   };
6006   static const MCPhysReg VR[] = {
6007     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6008     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6009   };
6010 
6011   const unsigned NumGPRs = array_lengthof(GPR);
6012   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6013   const unsigned NumVRs  = array_lengthof(VR);
6014 
6015   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6016   // can be passed to the callee in registers.
6017   // For the fast calling convention, there is another check below.
6018   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6019   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6020   if (!HasParameterArea) {
6021     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6022     unsigned AvailableFPRs = NumFPRs;
6023     unsigned AvailableVRs = NumVRs;
6024     unsigned NumBytesTmp = NumBytes;
6025     for (unsigned i = 0; i != NumOps; ++i) {
6026       if (Outs[i].Flags.isNest()) continue;
6027       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6028                                  PtrByteSize, LinkageSize, ParamAreaSize,
6029                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6030         HasParameterArea = true;
6031     }
6032   }
6033 
6034   // When using the fast calling convention, we don't provide backing for
6035   // arguments that will be in registers.
6036   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6037 
6038   // Avoid allocating parameter area for fastcc functions if all the arguments
6039   // can be passed in the registers.
6040   if (IsFastCall)
6041     HasParameterArea = false;
6042 
6043   // Add up all the space actually used.
6044   for (unsigned i = 0; i != NumOps; ++i) {
6045     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6046     EVT ArgVT = Outs[i].VT;
6047     EVT OrigVT = Outs[i].ArgVT;
6048 
6049     if (Flags.isNest())
6050       continue;
6051 
6052     if (IsFastCall) {
6053       if (Flags.isByVal()) {
6054         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6055         if (NumGPRsUsed > NumGPRs)
6056           HasParameterArea = true;
6057       } else {
6058         switch (ArgVT.getSimpleVT().SimpleTy) {
6059         default: llvm_unreachable("Unexpected ValueType for argument!");
6060         case MVT::i1:
6061         case MVT::i32:
6062         case MVT::i64:
6063           if (++NumGPRsUsed <= NumGPRs)
6064             continue;
6065           break;
6066         case MVT::v4i32:
6067         case MVT::v8i16:
6068         case MVT::v16i8:
6069         case MVT::v2f64:
6070         case MVT::v2i64:
6071         case MVT::v1i128:
6072         case MVT::f128:
6073           if (++NumVRsUsed <= NumVRs)
6074             continue;
6075           break;
6076         case MVT::v4f32:
6077           if (++NumVRsUsed <= NumVRs)
6078             continue;
6079           break;
6080         case MVT::f32:
6081         case MVT::f64:
6082           if (++NumFPRsUsed <= NumFPRs)
6083             continue;
6084           break;
6085         }
6086         HasParameterArea = true;
6087       }
6088     }
6089 
6090     /* Respect alignment of argument on the stack.  */
6091     auto Alignement =
6092         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6093     NumBytes = alignTo(NumBytes, Alignement);
6094 
6095     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6096     if (Flags.isInConsecutiveRegsLast())
6097       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6098   }
6099 
6100   unsigned NumBytesActuallyUsed = NumBytes;
6101 
6102   // In the old ELFv1 ABI,
6103   // the prolog code of the callee may store up to 8 GPR argument registers to
6104   // the stack, allowing va_start to index over them in memory if its varargs.
6105   // Because we cannot tell if this is needed on the caller side, we have to
6106   // conservatively assume that it is needed.  As such, make sure we have at
6107   // least enough stack space for the caller to store the 8 GPRs.
6108   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6109   // really requires memory operands, e.g. a vararg function.
6110   if (HasParameterArea)
6111     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6112   else
6113     NumBytes = LinkageSize;
6114 
6115   // Tail call needs the stack to be aligned.
6116   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6117     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6118 
6119   int SPDiff = 0;
6120 
6121   // Calculate by how many bytes the stack has to be adjusted in case of tail
6122   // call optimization.
6123   if (!IsSibCall)
6124     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6125 
6126   // To protect arguments on the stack from being clobbered in a tail call,
6127   // force all the loads to happen before doing any other lowering.
6128   if (CFlags.IsTailCall)
6129     Chain = DAG.getStackArgumentTokenFactor(Chain);
6130 
6131   // Adjust the stack pointer for the new arguments...
6132   // These operations are automatically eliminated by the prolog/epilog pass
6133   if (!IsSibCall)
6134     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6135   SDValue CallSeqStart = Chain;
6136 
6137   // Load the return address and frame pointer so it can be move somewhere else
6138   // later.
6139   SDValue LROp, FPOp;
6140   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6141 
6142   // Set up a copy of the stack pointer for use loading and storing any
6143   // arguments that may not fit in the registers available for argument
6144   // passing.
6145   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6146 
6147   // Figure out which arguments are going to go in registers, and which in
6148   // memory.  Also, if this is a vararg function, floating point operations
6149   // must be stored to our stack, and loaded into integer regs as well, if
6150   // any integer regs are available for argument passing.
6151   unsigned ArgOffset = LinkageSize;
6152 
6153   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6154   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6155 
6156   SmallVector<SDValue, 8> MemOpChains;
6157   for (unsigned i = 0; i != NumOps; ++i) {
6158     SDValue Arg = OutVals[i];
6159     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6160     EVT ArgVT = Outs[i].VT;
6161     EVT OrigVT = Outs[i].ArgVT;
6162 
6163     // PtrOff will be used to store the current argument to the stack if a
6164     // register cannot be found for it.
6165     SDValue PtrOff;
6166 
6167     // We re-align the argument offset for each argument, except when using the
6168     // fast calling convention, when we need to make sure we do that only when
6169     // we'll actually use a stack slot.
6170     auto ComputePtrOff = [&]() {
6171       /* Respect alignment of argument on the stack.  */
6172       auto Alignment =
6173           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6174       ArgOffset = alignTo(ArgOffset, Alignment);
6175 
6176       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6177 
6178       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6179     };
6180 
6181     if (!IsFastCall) {
6182       ComputePtrOff();
6183 
6184       /* Compute GPR index associated with argument offset.  */
6185       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6186       GPR_idx = std::min(GPR_idx, NumGPRs);
6187     }
6188 
6189     // Promote integers to 64-bit values.
6190     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6191       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6192       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6193       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6194     }
6195 
6196     // FIXME memcpy is used way more than necessary.  Correctness first.
6197     // Note: "by value" is code for passing a structure by value, not
6198     // basic types.
6199     if (Flags.isByVal()) {
6200       // Note: Size includes alignment padding, so
6201       //   struct x { short a; char b; }
6202       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6203       // These are the proper values we need for right-justifying the
6204       // aggregate in a parameter register.
6205       unsigned Size = Flags.getByValSize();
6206 
6207       // An empty aggregate parameter takes up no storage and no
6208       // registers.
6209       if (Size == 0)
6210         continue;
6211 
6212       if (IsFastCall)
6213         ComputePtrOff();
6214 
6215       // All aggregates smaller than 8 bytes must be passed right-justified.
6216       if (Size==1 || Size==2 || Size==4) {
6217         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6218         if (GPR_idx != NumGPRs) {
6219           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6220                                         MachinePointerInfo(), VT);
6221           MemOpChains.push_back(Load.getValue(1));
6222           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6223 
6224           ArgOffset += PtrByteSize;
6225           continue;
6226         }
6227       }
6228 
6229       if (GPR_idx == NumGPRs && Size < 8) {
6230         SDValue AddPtr = PtrOff;
6231         if (!isLittleEndian) {
6232           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6233                                           PtrOff.getValueType());
6234           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6235         }
6236         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6237                                                           CallSeqStart,
6238                                                           Flags, DAG, dl);
6239         ArgOffset += PtrByteSize;
6240         continue;
6241       }
6242       // Copy the object to parameter save area if it can not be entirely passed
6243       // by registers.
6244       // FIXME: we only need to copy the parts which need to be passed in
6245       // parameter save area. For the parts passed by registers, we don't need
6246       // to copy them to the stack although we need to allocate space for them
6247       // in parameter save area.
6248       if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6249         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6250                                                           CallSeqStart,
6251                                                           Flags, DAG, dl);
6252 
6253       // When a register is available, pass a small aggregate right-justified.
6254       if (Size < 8 && GPR_idx != NumGPRs) {
6255         // The easiest way to get this right-justified in a register
6256         // is to copy the structure into the rightmost portion of a
6257         // local variable slot, then load the whole slot into the
6258         // register.
6259         // FIXME: The memcpy seems to produce pretty awful code for
6260         // small aggregates, particularly for packed ones.
6261         // FIXME: It would be preferable to use the slot in the
6262         // parameter save area instead of a new local variable.
6263         SDValue AddPtr = PtrOff;
6264         if (!isLittleEndian) {
6265           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6266           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6267         }
6268         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6269                                                           CallSeqStart,
6270                                                           Flags, DAG, dl);
6271 
6272         // Load the slot into the register.
6273         SDValue Load =
6274             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6275         MemOpChains.push_back(Load.getValue(1));
6276         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6277 
6278         // Done with this argument.
6279         ArgOffset += PtrByteSize;
6280         continue;
6281       }
6282 
6283       // For aggregates larger than PtrByteSize, copy the pieces of the
6284       // object that fit into registers from the parameter save area.
6285       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6286         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6287         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6288         if (GPR_idx != NumGPRs) {
6289           SDValue Load =
6290               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6291           MemOpChains.push_back(Load.getValue(1));
6292           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6293           ArgOffset += PtrByteSize;
6294         } else {
6295           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6296           break;
6297         }
6298       }
6299       continue;
6300     }
6301 
6302     switch (Arg.getSimpleValueType().SimpleTy) {
6303     default: llvm_unreachable("Unexpected ValueType for argument!");
6304     case MVT::i1:
6305     case MVT::i32:
6306     case MVT::i64:
6307       if (Flags.isNest()) {
6308         // The 'nest' parameter, if any, is passed in R11.
6309         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6310         break;
6311       }
6312 
6313       // These can be scalar arguments or elements of an integer array type
6314       // passed directly.  Clang may use those instead of "byval" aggregate
6315       // types to avoid forcing arguments to memory unnecessarily.
6316       if (GPR_idx != NumGPRs) {
6317         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6318       } else {
6319         if (IsFastCall)
6320           ComputePtrOff();
6321 
6322         assert(HasParameterArea &&
6323                "Parameter area must exist to pass an argument in memory.");
6324         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6325                          true, CFlags.IsTailCall, false, MemOpChains,
6326                          TailCallArguments, dl);
6327         if (IsFastCall)
6328           ArgOffset += PtrByteSize;
6329       }
6330       if (!IsFastCall)
6331         ArgOffset += PtrByteSize;
6332       break;
6333     case MVT::f32:
6334     case MVT::f64: {
6335       // These can be scalar arguments or elements of a float array type
6336       // passed directly.  The latter are used to implement ELFv2 homogenous
6337       // float aggregates.
6338 
6339       // Named arguments go into FPRs first, and once they overflow, the
6340       // remaining arguments go into GPRs and then the parameter save area.
6341       // Unnamed arguments for vararg functions always go to GPRs and
6342       // then the parameter save area.  For now, put all arguments to vararg
6343       // routines always in both locations (FPR *and* GPR or stack slot).
6344       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6345       bool NeededLoad = false;
6346 
6347       // First load the argument into the next available FPR.
6348       if (FPR_idx != NumFPRs)
6349         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6350 
6351       // Next, load the argument into GPR or stack slot if needed.
6352       if (!NeedGPROrStack)
6353         ;
6354       else if (GPR_idx != NumGPRs && !IsFastCall) {
6355         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6356         // once we support fp <-> gpr moves.
6357 
6358         // In the non-vararg case, this can only ever happen in the
6359         // presence of f32 array types, since otherwise we never run
6360         // out of FPRs before running out of GPRs.
6361         SDValue ArgVal;
6362 
6363         // Double values are always passed in a single GPR.
6364         if (Arg.getValueType() != MVT::f32) {
6365           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6366 
6367         // Non-array float values are extended and passed in a GPR.
6368         } else if (!Flags.isInConsecutiveRegs()) {
6369           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6370           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6371 
6372         // If we have an array of floats, we collect every odd element
6373         // together with its predecessor into one GPR.
6374         } else if (ArgOffset % PtrByteSize != 0) {
6375           SDValue Lo, Hi;
6376           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6377           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6378           if (!isLittleEndian)
6379             std::swap(Lo, Hi);
6380           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6381 
6382         // The final element, if even, goes into the first half of a GPR.
6383         } else if (Flags.isInConsecutiveRegsLast()) {
6384           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6385           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6386           if (!isLittleEndian)
6387             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6388                                  DAG.getConstant(32, dl, MVT::i32));
6389 
6390         // Non-final even elements are skipped; they will be handled
6391         // together the with subsequent argument on the next go-around.
6392         } else
6393           ArgVal = SDValue();
6394 
6395         if (ArgVal.getNode())
6396           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6397       } else {
6398         if (IsFastCall)
6399           ComputePtrOff();
6400 
6401         // Single-precision floating-point values are mapped to the
6402         // second (rightmost) word of the stack doubleword.
6403         if (Arg.getValueType() == MVT::f32 &&
6404             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6405           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6406           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6407         }
6408 
6409         assert(HasParameterArea &&
6410                "Parameter area must exist to pass an argument in memory.");
6411         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6412                          true, CFlags.IsTailCall, false, MemOpChains,
6413                          TailCallArguments, dl);
6414 
6415         NeededLoad = true;
6416       }
6417       // When passing an array of floats, the array occupies consecutive
6418       // space in the argument area; only round up to the next doubleword
6419       // at the end of the array.  Otherwise, each float takes 8 bytes.
6420       if (!IsFastCall || NeededLoad) {
6421         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6422                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6423         if (Flags.isInConsecutiveRegsLast())
6424           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6425       }
6426       break;
6427     }
6428     case MVT::v4f32:
6429     case MVT::v4i32:
6430     case MVT::v8i16:
6431     case MVT::v16i8:
6432     case MVT::v2f64:
6433     case MVT::v2i64:
6434     case MVT::v1i128:
6435     case MVT::f128:
6436       // These can be scalar arguments or elements of a vector array type
6437       // passed directly.  The latter are used to implement ELFv2 homogenous
6438       // vector aggregates.
6439 
6440       // For a varargs call, named arguments go into VRs or on the stack as
6441       // usual; unnamed arguments always go to the stack or the corresponding
6442       // GPRs when within range.  For now, we always put the value in both
6443       // locations (or even all three).
6444       if (CFlags.IsVarArg) {
6445         assert(HasParameterArea &&
6446                "Parameter area must exist if we have a varargs call.");
6447         // We could elide this store in the case where the object fits
6448         // entirely in R registers.  Maybe later.
6449         SDValue Store =
6450             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6451         MemOpChains.push_back(Store);
6452         if (VR_idx != NumVRs) {
6453           SDValue Load =
6454               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6455           MemOpChains.push_back(Load.getValue(1));
6456           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6457         }
6458         ArgOffset += 16;
6459         for (unsigned i=0; i<16; i+=PtrByteSize) {
6460           if (GPR_idx == NumGPRs)
6461             break;
6462           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6463                                    DAG.getConstant(i, dl, PtrVT));
6464           SDValue Load =
6465               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6466           MemOpChains.push_back(Load.getValue(1));
6467           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6468         }
6469         break;
6470       }
6471 
6472       // Non-varargs Altivec params go into VRs or on the stack.
6473       if (VR_idx != NumVRs) {
6474         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6475       } else {
6476         if (IsFastCall)
6477           ComputePtrOff();
6478 
6479         assert(HasParameterArea &&
6480                "Parameter area must exist to pass an argument in memory.");
6481         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6482                          true, CFlags.IsTailCall, true, MemOpChains,
6483                          TailCallArguments, dl);
6484         if (IsFastCall)
6485           ArgOffset += 16;
6486       }
6487 
6488       if (!IsFastCall)
6489         ArgOffset += 16;
6490       break;
6491     }
6492   }
6493 
6494   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6495          "mismatch in size of parameter area");
6496   (void)NumBytesActuallyUsed;
6497 
6498   if (!MemOpChains.empty())
6499     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6500 
6501   // Check if this is an indirect call (MTCTR/BCTRL).
6502   // See prepareDescriptorIndirectCall and buildCallOperands for more
6503   // information about calls through function pointers in the 64-bit SVR4 ABI.
6504   if (CFlags.IsIndirect) {
6505     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6506     // caller in the TOC save area.
6507     if (isTOCSaveRestoreRequired(Subtarget)) {
6508       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6509       // Load r2 into a virtual register and store it to the TOC save area.
6510       setUsesTOCBasePtr(DAG);
6511       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6512       // TOC save area offset.
6513       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6514       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6515       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6516       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6517                            MachinePointerInfo::getStack(
6518                                DAG.getMachineFunction(), TOCSaveOffset));
6519     }
6520     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6521     // This does not mean the MTCTR instruction must use R12; it's easier
6522     // to model this as an extra parameter, so do that.
6523     if (isELFv2ABI && !CFlags.IsPatchPoint)
6524       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6525   }
6526 
6527   // Build a sequence of copy-to-reg nodes chained together with token chain
6528   // and flag operands which copy the outgoing args into the appropriate regs.
6529   SDValue InFlag;
6530   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6531     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6532                              RegsToPass[i].second, InFlag);
6533     InFlag = Chain.getValue(1);
6534   }
6535 
6536   if (CFlags.IsTailCall && !IsSibCall)
6537     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6538                     TailCallArguments);
6539 
6540   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6541                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6542 }
6543 
6544 // Returns true when the shadow of a general purpose argument register
6545 // in the parameter save area is aligned to at least 'RequiredAlign'.
6546 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6547   assert(RequiredAlign.value() <= 16 &&
6548          "Required alignment greater than stack alignment.");
6549   switch (Reg) {
6550   default:
6551     report_fatal_error("called on invalid register.");
6552   case PPC::R5:
6553   case PPC::R9:
6554   case PPC::X3:
6555   case PPC::X5:
6556   case PPC::X7:
6557   case PPC::X9:
6558     // These registers are 16 byte aligned which is the most strict aligment
6559     // we can support.
6560     return true;
6561   case PPC::R3:
6562   case PPC::R7:
6563   case PPC::X4:
6564   case PPC::X6:
6565   case PPC::X8:
6566   case PPC::X10:
6567     // The shadow of these registers in the PSA is 8 byte aligned.
6568     return RequiredAlign <= 8;
6569   case PPC::R4:
6570   case PPC::R6:
6571   case PPC::R8:
6572   case PPC::R10:
6573     return RequiredAlign <= 4;
6574   }
6575 }
6576 
6577 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6578                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6579                    CCState &S) {
6580   AIXCCState &State = static_cast<AIXCCState &>(S);
6581   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6582       State.getMachineFunction().getSubtarget());
6583   const bool IsPPC64 = Subtarget.isPPC64();
6584   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6585   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6586 
6587   if (ValVT == MVT::f128)
6588     report_fatal_error("f128 is unimplemented on AIX.");
6589 
6590   if (ArgFlags.isNest())
6591     report_fatal_error("Nest arguments are unimplemented.");
6592 
6593   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6594                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6595                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6596   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6597                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6598                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6599 
6600   static const MCPhysReg VR[] = {// Vector registers.
6601                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6602                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6603                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6604 
6605   if (ArgFlags.isByVal()) {
6606     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6607       report_fatal_error("Pass-by-value arguments with alignment greater than "
6608                          "register width are not supported.");
6609 
6610     const unsigned ByValSize = ArgFlags.getByValSize();
6611 
6612     // An empty aggregate parameter takes up no storage and no registers,
6613     // but needs a MemLoc for a stack slot for the formal arguments side.
6614     if (ByValSize == 0) {
6615       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6616                                        State.getNextStackOffset(), RegVT,
6617                                        LocInfo));
6618       return false;
6619     }
6620 
6621     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6622     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6623     for (const unsigned E = Offset + StackSize; Offset < E;
6624          Offset += PtrAlign.value()) {
6625       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6626         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6627       else {
6628         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6629                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6630                                          LocInfo));
6631         break;
6632       }
6633     }
6634     return false;
6635   }
6636 
6637   // Arguments always reserve parameter save area.
6638   switch (ValVT.SimpleTy) {
6639   default:
6640     report_fatal_error("Unhandled value type for argument.");
6641   case MVT::i64:
6642     // i64 arguments should have been split to i32 for PPC32.
6643     assert(IsPPC64 && "PPC32 should have split i64 values.");
6644     LLVM_FALLTHROUGH;
6645   case MVT::i1:
6646   case MVT::i32: {
6647     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6648     // AIX integer arguments are always passed in register width.
6649     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6650       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6651                                   : CCValAssign::LocInfo::ZExt;
6652     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6653       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6654     else
6655       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6656 
6657     return false;
6658   }
6659   case MVT::f32:
6660   case MVT::f64: {
6661     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6662     const unsigned StoreSize = LocVT.getStoreSize();
6663     // Floats are always 4-byte aligned in the PSA on AIX.
6664     // This includes f64 in 64-bit mode for ABI compatibility.
6665     const unsigned Offset =
6666         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6667     unsigned FReg = State.AllocateReg(FPR);
6668     if (FReg)
6669       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6670 
6671     // Reserve and initialize GPRs or initialize the PSA as required.
6672     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6673       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6674         assert(FReg && "An FPR should be available when a GPR is reserved.");
6675         if (State.isVarArg()) {
6676           // Successfully reserved GPRs are only initialized for vararg calls.
6677           // Custom handling is required for:
6678           //   f64 in PPC32 needs to be split into 2 GPRs.
6679           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6680           State.addLoc(
6681               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6682         }
6683       } else {
6684         // If there are insufficient GPRs, the PSA needs to be initialized.
6685         // Initialization occurs even if an FPR was initialized for
6686         // compatibility with the AIX XL compiler. The full memory for the
6687         // argument will be initialized even if a prior word is saved in GPR.
6688         // A custom memLoc is used when the argument also passes in FPR so
6689         // that the callee handling can skip over it easily.
6690         State.addLoc(
6691             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6692                                              LocInfo)
6693                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6694         break;
6695       }
6696     }
6697 
6698     return false;
6699   }
6700   case MVT::v4f32:
6701   case MVT::v4i32:
6702   case MVT::v8i16:
6703   case MVT::v16i8:
6704   case MVT::v2i64:
6705   case MVT::v2f64:
6706   case MVT::v1i128: {
6707     const unsigned VecSize = 16;
6708     const Align VecAlign(VecSize);
6709 
6710     if (!State.isVarArg()) {
6711       // If there are vector registers remaining we don't consume any stack
6712       // space.
6713       if (unsigned VReg = State.AllocateReg(VR)) {
6714         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6715         return false;
6716       }
6717       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6718       // might be allocated in the portion of the PSA that is shadowed by the
6719       // GPRs.
6720       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6721       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6722       return false;
6723     }
6724 
6725     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6726     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6727 
6728     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6729     // Burn any underaligned registers and their shadowed stack space until
6730     // we reach the required alignment.
6731     while (NextRegIndex != GPRs.size() &&
6732            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6733       // Shadow allocate register and its stack shadow.
6734       unsigned Reg = State.AllocateReg(GPRs);
6735       State.AllocateStack(PtrSize, PtrAlign);
6736       assert(Reg && "Allocating register unexpectedly failed.");
6737       (void)Reg;
6738       NextRegIndex = State.getFirstUnallocated(GPRs);
6739     }
6740 
6741     // Vectors that are passed as fixed arguments are handled differently.
6742     // They are passed in VRs if any are available (unlike arguments passed
6743     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6744     // functions)
6745     if (State.isFixed(ValNo)) {
6746       if (unsigned VReg = State.AllocateReg(VR)) {
6747         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6748         // Shadow allocate GPRs and stack space even though we pass in a VR.
6749         for (unsigned I = 0; I != VecSize; I += PtrSize)
6750           State.AllocateReg(GPRs);
6751         State.AllocateStack(VecSize, VecAlign);
6752         return false;
6753       }
6754       // No vector registers remain so pass on the stack.
6755       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6756       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6757       return false;
6758     }
6759 
6760     // If all GPRS are consumed then we pass the argument fully on the stack.
6761     if (NextRegIndex == GPRs.size()) {
6762       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6763       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6764       return false;
6765     }
6766 
6767     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6768     // half of the argument, and then need to pass the remaining half on the
6769     // stack.
6770     if (GPRs[NextRegIndex] == PPC::R9) {
6771       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6772       State.addLoc(
6773           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6774 
6775       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6776       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6777       assert(FirstReg && SecondReg &&
6778              "Allocating R9 or R10 unexpectedly failed.");
6779       State.addLoc(
6780           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6781       State.addLoc(
6782           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6783       return false;
6784     }
6785 
6786     // We have enough GPRs to fully pass the vector argument, and we have
6787     // already consumed any underaligned registers. Start with the custom
6788     // MemLoc and then the custom RegLocs.
6789     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6790     State.addLoc(
6791         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6792     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6793       const unsigned Reg = State.AllocateReg(GPRs);
6794       assert(Reg && "Failed to allocated register for vararg vector argument");
6795       State.addLoc(
6796           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6797     }
6798     return false;
6799   }
6800   }
6801   return true;
6802 }
6803 
6804 // So far, this function is only used by LowerFormalArguments_AIX()
6805 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6806                                                     bool IsPPC64,
6807                                                     bool HasP8Vector,
6808                                                     bool HasVSX) {
6809   assert((IsPPC64 || SVT != MVT::i64) &&
6810          "i64 should have been split for 32-bit codegen.");
6811 
6812   switch (SVT) {
6813   default:
6814     report_fatal_error("Unexpected value type for formal argument");
6815   case MVT::i1:
6816   case MVT::i32:
6817   case MVT::i64:
6818     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6819   case MVT::f32:
6820     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6821   case MVT::f64:
6822     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6823   case MVT::v4f32:
6824   case MVT::v4i32:
6825   case MVT::v8i16:
6826   case MVT::v16i8:
6827   case MVT::v2i64:
6828   case MVT::v2f64:
6829   case MVT::v1i128:
6830     return &PPC::VRRCRegClass;
6831   }
6832 }
6833 
6834 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6835                                         SelectionDAG &DAG, SDValue ArgValue,
6836                                         MVT LocVT, const SDLoc &dl) {
6837   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6838   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6839 
6840   if (Flags.isSExt())
6841     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6842                            DAG.getValueType(ValVT));
6843   else if (Flags.isZExt())
6844     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6845                            DAG.getValueType(ValVT));
6846 
6847   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6848 }
6849 
6850 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6851   const unsigned LASize = FL->getLinkageSize();
6852 
6853   if (PPC::GPRCRegClass.contains(Reg)) {
6854     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6855            "Reg must be a valid argument register!");
6856     return LASize + 4 * (Reg - PPC::R3);
6857   }
6858 
6859   if (PPC::G8RCRegClass.contains(Reg)) {
6860     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6861            "Reg must be a valid argument register!");
6862     return LASize + 8 * (Reg - PPC::X3);
6863   }
6864 
6865   llvm_unreachable("Only general purpose registers expected.");
6866 }
6867 
6868 //   AIX ABI Stack Frame Layout:
6869 //
6870 //   Low Memory +--------------------------------------------+
6871 //   SP   +---> | Back chain                                 | ---+
6872 //        |     +--------------------------------------------+    |
6873 //        |     | Saved Condition Register                   |    |
6874 //        |     +--------------------------------------------+    |
6875 //        |     | Saved Linkage Register                     |    |
6876 //        |     +--------------------------------------------+    | Linkage Area
6877 //        |     | Reserved for compilers                     |    |
6878 //        |     +--------------------------------------------+    |
6879 //        |     | Reserved for binders                       |    |
6880 //        |     +--------------------------------------------+    |
6881 //        |     | Saved TOC pointer                          | ---+
6882 //        |     +--------------------------------------------+
6883 //        |     | Parameter save area                        |
6884 //        |     +--------------------------------------------+
6885 //        |     | Alloca space                               |
6886 //        |     +--------------------------------------------+
6887 //        |     | Local variable space                       |
6888 //        |     +--------------------------------------------+
6889 //        |     | Float/int conversion temporary             |
6890 //        |     +--------------------------------------------+
6891 //        |     | Save area for AltiVec registers            |
6892 //        |     +--------------------------------------------+
6893 //        |     | AltiVec alignment padding                  |
6894 //        |     +--------------------------------------------+
6895 //        |     | Save area for VRSAVE register              |
6896 //        |     +--------------------------------------------+
6897 //        |     | Save area for General Purpose registers    |
6898 //        |     +--------------------------------------------+
6899 //        |     | Save area for Floating Point registers     |
6900 //        |     +--------------------------------------------+
6901 //        +---- | Back chain                                 |
6902 // High Memory  +--------------------------------------------+
6903 //
6904 //  Specifications:
6905 //  AIX 7.2 Assembler Language Reference
6906 //  Subroutine linkage convention
6907 
6908 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6909     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6910     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6911     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6912 
6913   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6914           CallConv == CallingConv::Fast) &&
6915          "Unexpected calling convention!");
6916 
6917   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6918     report_fatal_error("Tail call support is unimplemented on AIX.");
6919 
6920   if (useSoftFloat())
6921     report_fatal_error("Soft float support is unimplemented on AIX.");
6922 
6923   const PPCSubtarget &Subtarget =
6924       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6925 
6926   const bool IsPPC64 = Subtarget.isPPC64();
6927   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6928 
6929   // Assign locations to all of the incoming arguments.
6930   SmallVector<CCValAssign, 16> ArgLocs;
6931   MachineFunction &MF = DAG.getMachineFunction();
6932   MachineFrameInfo &MFI = MF.getFrameInfo();
6933   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6934   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6935 
6936   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6937   // Reserve space for the linkage area on the stack.
6938   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6939   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6940   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6941 
6942   SmallVector<SDValue, 8> MemOps;
6943 
6944   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6945     CCValAssign &VA = ArgLocs[I++];
6946     MVT LocVT = VA.getLocVT();
6947     MVT ValVT = VA.getValVT();
6948     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6949     // For compatibility with the AIX XL compiler, the float args in the
6950     // parameter save area are initialized even if the argument is available
6951     // in register.  The caller is required to initialize both the register
6952     // and memory, however, the callee can choose to expect it in either.
6953     // The memloc is dismissed here because the argument is retrieved from
6954     // the register.
6955     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6956       continue;
6957 
6958     auto HandleMemLoc = [&]() {
6959       const unsigned LocSize = LocVT.getStoreSize();
6960       const unsigned ValSize = ValVT.getStoreSize();
6961       assert((ValSize <= LocSize) &&
6962              "Object size is larger than size of MemLoc");
6963       int CurArgOffset = VA.getLocMemOffset();
6964       // Objects are right-justified because AIX is big-endian.
6965       if (LocSize > ValSize)
6966         CurArgOffset += LocSize - ValSize;
6967       // Potential tail calls could cause overwriting of argument stack slots.
6968       const bool IsImmutable =
6969           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6970             (CallConv == CallingConv::Fast));
6971       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6972       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6973       SDValue ArgValue =
6974           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6975       InVals.push_back(ArgValue);
6976     };
6977 
6978     // Vector arguments to VaArg functions are passed both on the stack, and
6979     // in any available GPRs. Load the value from the stack and add the GPRs
6980     // as live ins.
6981     if (VA.isMemLoc() && VA.needsCustom()) {
6982       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6983       assert(isVarArg && "Only use custom memloc for vararg.");
6984       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6985       // matching custom RegLocs.
6986       const unsigned OriginalValNo = VA.getValNo();
6987       (void)OriginalValNo;
6988 
6989       auto HandleCustomVecRegLoc = [&]() {
6990         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6991                "Missing custom RegLoc.");
6992         VA = ArgLocs[I++];
6993         assert(VA.getValVT().isVector() &&
6994                "Unexpected Val type for custom RegLoc.");
6995         assert(VA.getValNo() == OriginalValNo &&
6996                "ValNo mismatch between custom MemLoc and RegLoc.");
6997         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6998         MF.addLiveIn(VA.getLocReg(),
6999                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7000                                        Subtarget.hasVSX()));
7001       };
7002 
7003       HandleMemLoc();
7004       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7005       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7006       // R10.
7007       HandleCustomVecRegLoc();
7008       HandleCustomVecRegLoc();
7009 
7010       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7011       // we passed the vector in R5, R6, R7 and R8.
7012       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7013         assert(!IsPPC64 &&
7014                "Only 2 custom RegLocs expected for 64-bit codegen.");
7015         HandleCustomVecRegLoc();
7016         HandleCustomVecRegLoc();
7017       }
7018 
7019       continue;
7020     }
7021 
7022     if (VA.isRegLoc()) {
7023       if (VA.getValVT().isScalarInteger())
7024         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7025       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7026         switch (VA.getValVT().SimpleTy) {
7027         default:
7028           report_fatal_error("Unhandled value type for argument.");
7029         case MVT::f32:
7030           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7031           break;
7032         case MVT::f64:
7033           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7034           break;
7035         }
7036       } else if (VA.getValVT().isVector()) {
7037         switch (VA.getValVT().SimpleTy) {
7038         default:
7039           report_fatal_error("Unhandled value type for argument.");
7040         case MVT::v16i8:
7041           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7042           break;
7043         case MVT::v8i16:
7044           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7045           break;
7046         case MVT::v4i32:
7047         case MVT::v2i64:
7048         case MVT::v1i128:
7049           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7050           break;
7051         case MVT::v4f32:
7052         case MVT::v2f64:
7053           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7054           break;
7055         }
7056       }
7057     }
7058 
7059     if (Flags.isByVal() && VA.isMemLoc()) {
7060       const unsigned Size =
7061           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7062                   PtrByteSize);
7063       const int FI = MF.getFrameInfo().CreateFixedObject(
7064           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7065           /* IsAliased */ true);
7066       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7067       InVals.push_back(FIN);
7068 
7069       continue;
7070     }
7071 
7072     if (Flags.isByVal()) {
7073       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7074 
7075       const MCPhysReg ArgReg = VA.getLocReg();
7076       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7077 
7078       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7079         report_fatal_error("Over aligned byvals not supported yet.");
7080 
7081       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7082       const int FI = MF.getFrameInfo().CreateFixedObject(
7083           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7084           /* IsAliased */ true);
7085       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7086       InVals.push_back(FIN);
7087 
7088       // Add live ins for all the RegLocs for the same ByVal.
7089       const TargetRegisterClass *RegClass =
7090           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7091 
7092       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7093                                                unsigned Offset) {
7094         const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7095         // Since the callers side has left justified the aggregate in the
7096         // register, we can simply store the entire register into the stack
7097         // slot.
7098         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7099         // The store to the fixedstack object is needed becuase accessing a
7100         // field of the ByVal will use a gep and load. Ideally we will optimize
7101         // to extracting the value from the register directly, and elide the
7102         // stores when the arguments address is not taken, but that will need to
7103         // be future work.
7104         SDValue Store = DAG.getStore(
7105             CopyFrom.getValue(1), dl, CopyFrom,
7106             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7107             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7108 
7109         MemOps.push_back(Store);
7110       };
7111 
7112       unsigned Offset = 0;
7113       HandleRegLoc(VA.getLocReg(), Offset);
7114       Offset += PtrByteSize;
7115       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7116            Offset += PtrByteSize) {
7117         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7118                "RegLocs should be for ByVal argument.");
7119 
7120         const CCValAssign RL = ArgLocs[I++];
7121         HandleRegLoc(RL.getLocReg(), Offset);
7122         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7123       }
7124 
7125       if (Offset != StackSize) {
7126         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7127                "Expected MemLoc for remaining bytes.");
7128         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7129         // Consume the MemLoc.The InVal has already been emitted, so nothing
7130         // more needs to be done.
7131         ++I;
7132       }
7133 
7134       continue;
7135     }
7136 
7137     if (VA.isRegLoc() && !VA.needsCustom()) {
7138       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7139       Register VReg =
7140           MF.addLiveIn(VA.getLocReg(),
7141                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7142                                          Subtarget.hasVSX()));
7143       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7144       if (ValVT.isScalarInteger() &&
7145           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7146         ArgValue =
7147             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7148       }
7149       InVals.push_back(ArgValue);
7150       continue;
7151     }
7152     if (VA.isMemLoc()) {
7153       HandleMemLoc();
7154       continue;
7155     }
7156   }
7157 
7158   // On AIX a minimum of 8 words is saved to the parameter save area.
7159   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7160   // Area that is at least reserved in the caller of this function.
7161   unsigned CallerReservedArea =
7162       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7163 
7164   // Set the size that is at least reserved in caller of this function. Tail
7165   // call optimized function's reserved stack space needs to be aligned so
7166   // that taking the difference between two stack areas will result in an
7167   // aligned stack.
7168   CallerReservedArea =
7169       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7170   FuncInfo->setMinReservedArea(CallerReservedArea);
7171 
7172   if (isVarArg) {
7173     FuncInfo->setVarArgsFrameIndex(
7174         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7175     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7176 
7177     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7178                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7179 
7180     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7181                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7182     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7183 
7184     // The fixed integer arguments of a variadic function are stored to the
7185     // VarArgsFrameIndex on the stack so that they may be loaded by
7186     // dereferencing the result of va_next.
7187     for (unsigned GPRIndex =
7188              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7189          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7190 
7191       const Register VReg =
7192           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7193                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7194 
7195       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7196       SDValue Store =
7197           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7198       MemOps.push_back(Store);
7199       // Increment the address for the next argument to store.
7200       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7201       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7202     }
7203   }
7204 
7205   if (!MemOps.empty())
7206     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7207 
7208   return Chain;
7209 }
7210 
7211 SDValue PPCTargetLowering::LowerCall_AIX(
7212     SDValue Chain, SDValue Callee, CallFlags CFlags,
7213     const SmallVectorImpl<ISD::OutputArg> &Outs,
7214     const SmallVectorImpl<SDValue> &OutVals,
7215     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7216     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7217     const CallBase *CB) const {
7218   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7219   // AIX ABI stack frame layout.
7220 
7221   assert((CFlags.CallConv == CallingConv::C ||
7222           CFlags.CallConv == CallingConv::Cold ||
7223           CFlags.CallConv == CallingConv::Fast) &&
7224          "Unexpected calling convention!");
7225 
7226   if (CFlags.IsPatchPoint)
7227     report_fatal_error("This call type is unimplemented on AIX.");
7228 
7229   const PPCSubtarget& Subtarget =
7230       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7231 
7232   MachineFunction &MF = DAG.getMachineFunction();
7233   SmallVector<CCValAssign, 16> ArgLocs;
7234   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7235                     *DAG.getContext());
7236 
7237   // Reserve space for the linkage save area (LSA) on the stack.
7238   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7239   //   [SP][CR][LR][2 x reserved][TOC].
7240   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7241   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7242   const bool IsPPC64 = Subtarget.isPPC64();
7243   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7244   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7245   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7246   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7247 
7248   // The prolog code of the callee may store up to 8 GPR argument registers to
7249   // the stack, allowing va_start to index over them in memory if the callee
7250   // is variadic.
7251   // Because we cannot tell if this is needed on the caller side, we have to
7252   // conservatively assume that it is needed.  As such, make sure we have at
7253   // least enough stack space for the caller to store the 8 GPRs.
7254   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7255   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7256                                      CCInfo.getNextStackOffset());
7257 
7258   // Adjust the stack pointer for the new arguments...
7259   // These operations are automatically eliminated by the prolog/epilog pass.
7260   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7261   SDValue CallSeqStart = Chain;
7262 
7263   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7264   SmallVector<SDValue, 8> MemOpChains;
7265 
7266   // Set up a copy of the stack pointer for loading and storing any
7267   // arguments that may not fit in the registers available for argument
7268   // passing.
7269   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7270                                    : DAG.getRegister(PPC::R1, MVT::i32);
7271 
7272   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7273     const unsigned ValNo = ArgLocs[I].getValNo();
7274     SDValue Arg = OutVals[ValNo];
7275     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7276 
7277     if (Flags.isByVal()) {
7278       const unsigned ByValSize = Flags.getByValSize();
7279 
7280       // Nothing to do for zero-sized ByVals on the caller side.
7281       if (!ByValSize) {
7282         ++I;
7283         continue;
7284       }
7285 
7286       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7287         return DAG.getExtLoad(
7288             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7289             (LoadOffset != 0)
7290                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7291                 : Arg,
7292             MachinePointerInfo(), VT);
7293       };
7294 
7295       unsigned LoadOffset = 0;
7296 
7297       // Initialize registers, which are fully occupied by the by-val argument.
7298       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7299         SDValue Load = GetLoad(PtrVT, LoadOffset);
7300         MemOpChains.push_back(Load.getValue(1));
7301         LoadOffset += PtrByteSize;
7302         const CCValAssign &ByValVA = ArgLocs[I++];
7303         assert(ByValVA.getValNo() == ValNo &&
7304                "Unexpected location for pass-by-value argument.");
7305         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7306       }
7307 
7308       if (LoadOffset == ByValSize)
7309         continue;
7310 
7311       // There must be one more loc to handle the remainder.
7312       assert(ArgLocs[I].getValNo() == ValNo &&
7313              "Expected additional location for by-value argument.");
7314 
7315       if (ArgLocs[I].isMemLoc()) {
7316         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7317         const CCValAssign &ByValVA = ArgLocs[I++];
7318         ISD::ArgFlagsTy MemcpyFlags = Flags;
7319         // Only memcpy the bytes that don't pass in register.
7320         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7321         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7322             (LoadOffset != 0)
7323                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7324                 : Arg,
7325             DAG.getObjectPtrOffset(dl, StackPtr,
7326                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7327             CallSeqStart, MemcpyFlags, DAG, dl);
7328         continue;
7329       }
7330 
7331       // Initialize the final register residue.
7332       // Any residue that occupies the final by-val arg register must be
7333       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7334       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7335       // 2 and 1 byte loads.
7336       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7337       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7338              "Unexpected register residue for by-value argument.");
7339       SDValue ResidueVal;
7340       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7341         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7342         const MVT VT =
7343             N == 1 ? MVT::i8
7344                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7345         SDValue Load = GetLoad(VT, LoadOffset);
7346         MemOpChains.push_back(Load.getValue(1));
7347         LoadOffset += N;
7348         Bytes += N;
7349 
7350         // By-val arguments are passed left-justfied in register.
7351         // Every load here needs to be shifted, otherwise a full register load
7352         // should have been used.
7353         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7354                "Unexpected load emitted during handling of pass-by-value "
7355                "argument.");
7356         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7357         EVT ShiftAmountTy =
7358             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7359         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7360         SDValue ShiftedLoad =
7361             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7362         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7363                                               ShiftedLoad)
7364                                 : ShiftedLoad;
7365       }
7366 
7367       const CCValAssign &ByValVA = ArgLocs[I++];
7368       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7369       continue;
7370     }
7371 
7372     CCValAssign &VA = ArgLocs[I++];
7373     const MVT LocVT = VA.getLocVT();
7374     const MVT ValVT = VA.getValVT();
7375 
7376     switch (VA.getLocInfo()) {
7377     default:
7378       report_fatal_error("Unexpected argument extension type.");
7379     case CCValAssign::Full:
7380       break;
7381     case CCValAssign::ZExt:
7382       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7383       break;
7384     case CCValAssign::SExt:
7385       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7386       break;
7387     }
7388 
7389     if (VA.isRegLoc() && !VA.needsCustom()) {
7390       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7391       continue;
7392     }
7393 
7394     // Vector arguments passed to VarArg functions need custom handling when
7395     // they are passed (at least partially) in GPRs.
7396     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7397       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7398       // Store value to its stack slot.
7399       SDValue PtrOff =
7400           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7401       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7402       SDValue Store =
7403           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7404       MemOpChains.push_back(Store);
7405       const unsigned OriginalValNo = VA.getValNo();
7406       // Then load the GPRs from the stack
7407       unsigned LoadOffset = 0;
7408       auto HandleCustomVecRegLoc = [&]() {
7409         assert(I != E && "Unexpected end of CCvalAssigns.");
7410         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7411                "Expected custom RegLoc.");
7412         CCValAssign RegVA = ArgLocs[I++];
7413         assert(RegVA.getValNo() == OriginalValNo &&
7414                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7415         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7416                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7417         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7418         MemOpChains.push_back(Load.getValue(1));
7419         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7420         LoadOffset += PtrByteSize;
7421       };
7422 
7423       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7424       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7425       // R10.
7426       HandleCustomVecRegLoc();
7427       HandleCustomVecRegLoc();
7428 
7429       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7430           ArgLocs[I].getValNo() == OriginalValNo) {
7431         assert(!IsPPC64 &&
7432                "Only 2 custom RegLocs expected for 64-bit codegen.");
7433         HandleCustomVecRegLoc();
7434         HandleCustomVecRegLoc();
7435       }
7436 
7437       continue;
7438     }
7439 
7440     if (VA.isMemLoc()) {
7441       SDValue PtrOff =
7442           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7443       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7444       MemOpChains.push_back(
7445           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7446 
7447       continue;
7448     }
7449 
7450     if (!ValVT.isFloatingPoint())
7451       report_fatal_error(
7452           "Unexpected register handling for calling convention.");
7453 
7454     // Custom handling is used for GPR initializations for vararg float
7455     // arguments.
7456     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7457            LocVT.isInteger() &&
7458            "Custom register handling only expected for VarArg.");
7459 
7460     SDValue ArgAsInt =
7461         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7462 
7463     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7464       // f32 in 32-bit GPR
7465       // f64 in 64-bit GPR
7466       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7467     else if (Arg.getValueType().getFixedSizeInBits() <
7468              LocVT.getFixedSizeInBits())
7469       // f32 in 64-bit GPR.
7470       RegsToPass.push_back(std::make_pair(
7471           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7472     else {
7473       // f64 in two 32-bit GPRs
7474       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7475       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7476              "Unexpected custom register for argument!");
7477       CCValAssign &GPR1 = VA;
7478       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7479                                      DAG.getConstant(32, dl, MVT::i8));
7480       RegsToPass.push_back(std::make_pair(
7481           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7482 
7483       if (I != E) {
7484         // If only 1 GPR was available, there will only be one custom GPR and
7485         // the argument will also pass in memory.
7486         CCValAssign &PeekArg = ArgLocs[I];
7487         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7488           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7489           CCValAssign &GPR2 = ArgLocs[I++];
7490           RegsToPass.push_back(std::make_pair(
7491               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7492         }
7493       }
7494     }
7495   }
7496 
7497   if (!MemOpChains.empty())
7498     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7499 
7500   // For indirect calls, we need to save the TOC base to the stack for
7501   // restoration after the call.
7502   if (CFlags.IsIndirect) {
7503     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7504     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7505     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7506     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7507     const unsigned TOCSaveOffset =
7508         Subtarget.getFrameLowering()->getTOCSaveOffset();
7509 
7510     setUsesTOCBasePtr(DAG);
7511     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7512     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7513     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7514     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7515     Chain = DAG.getStore(
7516         Val.getValue(1), dl, Val, AddPtr,
7517         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7518   }
7519 
7520   // Build a sequence of copy-to-reg nodes chained together with token chain
7521   // and flag operands which copy the outgoing args into the appropriate regs.
7522   SDValue InFlag;
7523   for (auto Reg : RegsToPass) {
7524     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7525     InFlag = Chain.getValue(1);
7526   }
7527 
7528   const int SPDiff = 0;
7529   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7530                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7531 }
7532 
7533 bool
7534 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7535                                   MachineFunction &MF, bool isVarArg,
7536                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7537                                   LLVMContext &Context) const {
7538   SmallVector<CCValAssign, 16> RVLocs;
7539   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7540   return CCInfo.CheckReturn(
7541       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7542                 ? RetCC_PPC_Cold
7543                 : RetCC_PPC);
7544 }
7545 
7546 SDValue
7547 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7548                                bool isVarArg,
7549                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7550                                const SmallVectorImpl<SDValue> &OutVals,
7551                                const SDLoc &dl, SelectionDAG &DAG) const {
7552   SmallVector<CCValAssign, 16> RVLocs;
7553   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7554                  *DAG.getContext());
7555   CCInfo.AnalyzeReturn(Outs,
7556                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7557                            ? RetCC_PPC_Cold
7558                            : RetCC_PPC);
7559 
7560   SDValue Flag;
7561   SmallVector<SDValue, 4> RetOps(1, Chain);
7562 
7563   // Copy the result values into the output registers.
7564   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7565     CCValAssign &VA = RVLocs[i];
7566     assert(VA.isRegLoc() && "Can only return in registers!");
7567 
7568     SDValue Arg = OutVals[RealResIdx];
7569 
7570     switch (VA.getLocInfo()) {
7571     default: llvm_unreachable("Unknown loc info!");
7572     case CCValAssign::Full: break;
7573     case CCValAssign::AExt:
7574       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7575       break;
7576     case CCValAssign::ZExt:
7577       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7578       break;
7579     case CCValAssign::SExt:
7580       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7581       break;
7582     }
7583     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7584       bool isLittleEndian = Subtarget.isLittleEndian();
7585       // Legalize ret f64 -> ret 2 x i32.
7586       SDValue SVal =
7587           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7588                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7589       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7590       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7591       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7592                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7593       Flag = Chain.getValue(1);
7594       VA = RVLocs[++i]; // skip ahead to next loc
7595       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7596     } else
7597       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7598     Flag = Chain.getValue(1);
7599     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7600   }
7601 
7602   RetOps[0] = Chain;  // Update chain.
7603 
7604   // Add the flag if we have it.
7605   if (Flag.getNode())
7606     RetOps.push_back(Flag);
7607 
7608   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7609 }
7610 
7611 SDValue
7612 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7613                                                 SelectionDAG &DAG) const {
7614   SDLoc dl(Op);
7615 
7616   // Get the correct type for integers.
7617   EVT IntVT = Op.getValueType();
7618 
7619   // Get the inputs.
7620   SDValue Chain = Op.getOperand(0);
7621   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7622   // Build a DYNAREAOFFSET node.
7623   SDValue Ops[2] = {Chain, FPSIdx};
7624   SDVTList VTs = DAG.getVTList(IntVT);
7625   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7626 }
7627 
7628 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7629                                              SelectionDAG &DAG) const {
7630   // When we pop the dynamic allocation we need to restore the SP link.
7631   SDLoc dl(Op);
7632 
7633   // Get the correct type for pointers.
7634   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7635 
7636   // Construct the stack pointer operand.
7637   bool isPPC64 = Subtarget.isPPC64();
7638   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7639   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7640 
7641   // Get the operands for the STACKRESTORE.
7642   SDValue Chain = Op.getOperand(0);
7643   SDValue SaveSP = Op.getOperand(1);
7644 
7645   // Load the old link SP.
7646   SDValue LoadLinkSP =
7647       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7648 
7649   // Restore the stack pointer.
7650   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7651 
7652   // Store the old link SP.
7653   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7654 }
7655 
7656 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7657   MachineFunction &MF = DAG.getMachineFunction();
7658   bool isPPC64 = Subtarget.isPPC64();
7659   EVT PtrVT = getPointerTy(MF.getDataLayout());
7660 
7661   // Get current frame pointer save index.  The users of this index will be
7662   // primarily DYNALLOC instructions.
7663   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7664   int RASI = FI->getReturnAddrSaveIndex();
7665 
7666   // If the frame pointer save index hasn't been defined yet.
7667   if (!RASI) {
7668     // Find out what the fix offset of the frame pointer save area.
7669     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7670     // Allocate the frame index for frame pointer save area.
7671     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7672     // Save the result.
7673     FI->setReturnAddrSaveIndex(RASI);
7674   }
7675   return DAG.getFrameIndex(RASI, PtrVT);
7676 }
7677 
7678 SDValue
7679 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7680   MachineFunction &MF = DAG.getMachineFunction();
7681   bool isPPC64 = Subtarget.isPPC64();
7682   EVT PtrVT = getPointerTy(MF.getDataLayout());
7683 
7684   // Get current frame pointer save index.  The users of this index will be
7685   // primarily DYNALLOC instructions.
7686   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7687   int FPSI = FI->getFramePointerSaveIndex();
7688 
7689   // If the frame pointer save index hasn't been defined yet.
7690   if (!FPSI) {
7691     // Find out what the fix offset of the frame pointer save area.
7692     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7693     // Allocate the frame index for frame pointer save area.
7694     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7695     // Save the result.
7696     FI->setFramePointerSaveIndex(FPSI);
7697   }
7698   return DAG.getFrameIndex(FPSI, PtrVT);
7699 }
7700 
7701 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7702                                                    SelectionDAG &DAG) const {
7703   MachineFunction &MF = DAG.getMachineFunction();
7704   // Get the inputs.
7705   SDValue Chain = Op.getOperand(0);
7706   SDValue Size  = Op.getOperand(1);
7707   SDLoc dl(Op);
7708 
7709   // Get the correct type for pointers.
7710   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7711   // Negate the size.
7712   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7713                                 DAG.getConstant(0, dl, PtrVT), Size);
7714   // Construct a node for the frame pointer save index.
7715   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7716   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7717   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7718   if (hasInlineStackProbe(MF))
7719     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7720   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7721 }
7722 
7723 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7724                                                      SelectionDAG &DAG) const {
7725   MachineFunction &MF = DAG.getMachineFunction();
7726 
7727   bool isPPC64 = Subtarget.isPPC64();
7728   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7729 
7730   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7731   return DAG.getFrameIndex(FI, PtrVT);
7732 }
7733 
7734 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7735                                                SelectionDAG &DAG) const {
7736   SDLoc DL(Op);
7737   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7738                      DAG.getVTList(MVT::i32, MVT::Other),
7739                      Op.getOperand(0), Op.getOperand(1));
7740 }
7741 
7742 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7743                                                 SelectionDAG &DAG) const {
7744   SDLoc DL(Op);
7745   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7746                      Op.getOperand(0), Op.getOperand(1));
7747 }
7748 
7749 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7750   if (Op.getValueType().isVector())
7751     return LowerVectorLoad(Op, DAG);
7752 
7753   assert(Op.getValueType() == MVT::i1 &&
7754          "Custom lowering only for i1 loads");
7755 
7756   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7757 
7758   SDLoc dl(Op);
7759   LoadSDNode *LD = cast<LoadSDNode>(Op);
7760 
7761   SDValue Chain = LD->getChain();
7762   SDValue BasePtr = LD->getBasePtr();
7763   MachineMemOperand *MMO = LD->getMemOperand();
7764 
7765   SDValue NewLD =
7766       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7767                      BasePtr, MVT::i8, MMO);
7768   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7769 
7770   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7771   return DAG.getMergeValues(Ops, dl);
7772 }
7773 
7774 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7775   if (Op.getOperand(1).getValueType().isVector())
7776     return LowerVectorStore(Op, DAG);
7777 
7778   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7779          "Custom lowering only for i1 stores");
7780 
7781   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7782 
7783   SDLoc dl(Op);
7784   StoreSDNode *ST = cast<StoreSDNode>(Op);
7785 
7786   SDValue Chain = ST->getChain();
7787   SDValue BasePtr = ST->getBasePtr();
7788   SDValue Value = ST->getValue();
7789   MachineMemOperand *MMO = ST->getMemOperand();
7790 
7791   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7792                       Value);
7793   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7794 }
7795 
7796 // FIXME: Remove this once the ANDI glue bug is fixed:
7797 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7798   assert(Op.getValueType() == MVT::i1 &&
7799          "Custom lowering only for i1 results");
7800 
7801   SDLoc DL(Op);
7802   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7803 }
7804 
7805 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7806                                                SelectionDAG &DAG) const {
7807 
7808   // Implements a vector truncate that fits in a vector register as a shuffle.
7809   // We want to legalize vector truncates down to where the source fits in
7810   // a vector register (and target is therefore smaller than vector register
7811   // size).  At that point legalization will try to custom lower the sub-legal
7812   // result and get here - where we can contain the truncate as a single target
7813   // operation.
7814 
7815   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7816   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7817   //
7818   // We will implement it for big-endian ordering as this (where x denotes
7819   // undefined):
7820   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7821   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7822   //
7823   // The same operation in little-endian ordering will be:
7824   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7825   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7826 
7827   EVT TrgVT = Op.getValueType();
7828   assert(TrgVT.isVector() && "Vector type expected.");
7829   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7830   EVT EltVT = TrgVT.getVectorElementType();
7831   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7832       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7833       !isPowerOf2_32(EltVT.getSizeInBits()))
7834     return SDValue();
7835 
7836   SDValue N1 = Op.getOperand(0);
7837   EVT SrcVT = N1.getValueType();
7838   unsigned SrcSize = SrcVT.getSizeInBits();
7839   if (SrcSize > 256 ||
7840       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7841       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7842     return SDValue();
7843   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7844     return SDValue();
7845 
7846   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7847   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7848 
7849   SDLoc DL(Op);
7850   SDValue Op1, Op2;
7851   if (SrcSize == 256) {
7852     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7853     EVT SplitVT =
7854         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7855     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7856     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7857                       DAG.getConstant(0, DL, VecIdxTy));
7858     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7859                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7860   }
7861   else {
7862     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7863     Op2 = DAG.getUNDEF(WideVT);
7864   }
7865 
7866   // First list the elements we want to keep.
7867   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7868   SmallVector<int, 16> ShuffV;
7869   if (Subtarget.isLittleEndian())
7870     for (unsigned i = 0; i < TrgNumElts; ++i)
7871       ShuffV.push_back(i * SizeMult);
7872   else
7873     for (unsigned i = 1; i <= TrgNumElts; ++i)
7874       ShuffV.push_back(i * SizeMult - 1);
7875 
7876   // Populate the remaining elements with undefs.
7877   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7878     // ShuffV.push_back(i + WideNumElts);
7879     ShuffV.push_back(WideNumElts + 1);
7880 
7881   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7882   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7883   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7884 }
7885 
7886 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7887 /// possible.
7888 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7889   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7890   EVT ResVT = Op.getValueType();
7891   EVT CmpVT = Op.getOperand(0).getValueType();
7892   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7893   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7894   SDLoc dl(Op);
7895 
7896   // Without power9-vector, we don't have native instruction for f128 comparison.
7897   // Following transformation to libcall is needed for setcc:
7898   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7899   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7900     SDValue Z = DAG.getSetCC(
7901         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7902         LHS, RHS, CC);
7903     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7904     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7905   }
7906 
7907   // Not FP, or using SPE? Not a fsel.
7908   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7909       Subtarget.hasSPE())
7910     return Op;
7911 
7912   SDNodeFlags Flags = Op.getNode()->getFlags();
7913 
7914   // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
7915   // presence of infinities.
7916   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7917     switch (CC) {
7918     default:
7919       break;
7920     case ISD::SETOGT:
7921     case ISD::SETGT:
7922       return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
7923     case ISD::SETOLT:
7924     case ISD::SETLT:
7925       return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
7926     }
7927   }
7928 
7929   // We might be able to do better than this under some circumstances, but in
7930   // general, fsel-based lowering of select is a finite-math-only optimization.
7931   // For more information, see section F.3 of the 2.06 ISA specification.
7932   // With ISA 3.0
7933   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7934       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7935     return Op;
7936 
7937   // If the RHS of the comparison is a 0.0, we don't need to do the
7938   // subtraction at all.
7939   SDValue Sel1;
7940   if (isFloatingPointZero(RHS))
7941     switch (CC) {
7942     default: break;       // SETUO etc aren't handled by fsel.
7943     case ISD::SETNE:
7944       std::swap(TV, FV);
7945       LLVM_FALLTHROUGH;
7946     case ISD::SETEQ:
7947       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7948         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7949       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7950       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7951         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7952       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7953                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7954     case ISD::SETULT:
7955     case ISD::SETLT:
7956       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7957       LLVM_FALLTHROUGH;
7958     case ISD::SETOGE:
7959     case ISD::SETGE:
7960       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7961         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7962       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7963     case ISD::SETUGT:
7964     case ISD::SETGT:
7965       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7966       LLVM_FALLTHROUGH;
7967     case ISD::SETOLE:
7968     case ISD::SETLE:
7969       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7970         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7971       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7972                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7973     }
7974 
7975   SDValue Cmp;
7976   switch (CC) {
7977   default: break;       // SETUO etc aren't handled by fsel.
7978   case ISD::SETNE:
7979     std::swap(TV, FV);
7980     LLVM_FALLTHROUGH;
7981   case ISD::SETEQ:
7982     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7983     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7984       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7985     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7986     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7987       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7988     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7989                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7990   case ISD::SETULT:
7991   case ISD::SETLT:
7992     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7993     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7994       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7995     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7996   case ISD::SETOGE:
7997   case ISD::SETGE:
7998     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7999     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8000       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8001     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8002   case ISD::SETUGT:
8003   case ISD::SETGT:
8004     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8005     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8006       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8007     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8008   case ISD::SETOLE:
8009   case ISD::SETLE:
8010     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8011     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8012       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8013     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8014   }
8015   return Op;
8016 }
8017 
8018 static unsigned getPPCStrictOpcode(unsigned Opc) {
8019   switch (Opc) {
8020   default:
8021     llvm_unreachable("No strict version of this opcode!");
8022   case PPCISD::FCTIDZ:
8023     return PPCISD::STRICT_FCTIDZ;
8024   case PPCISD::FCTIWZ:
8025     return PPCISD::STRICT_FCTIWZ;
8026   case PPCISD::FCTIDUZ:
8027     return PPCISD::STRICT_FCTIDUZ;
8028   case PPCISD::FCTIWUZ:
8029     return PPCISD::STRICT_FCTIWUZ;
8030   case PPCISD::FCFID:
8031     return PPCISD::STRICT_FCFID;
8032   case PPCISD::FCFIDU:
8033     return PPCISD::STRICT_FCFIDU;
8034   case PPCISD::FCFIDS:
8035     return PPCISD::STRICT_FCFIDS;
8036   case PPCISD::FCFIDUS:
8037     return PPCISD::STRICT_FCFIDUS;
8038   }
8039 }
8040 
8041 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8042                               const PPCSubtarget &Subtarget) {
8043   SDLoc dl(Op);
8044   bool IsStrict = Op->isStrictFPOpcode();
8045   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8046                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8047 
8048   // TODO: Any other flags to propagate?
8049   SDNodeFlags Flags;
8050   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8051 
8052   // For strict nodes, source is the second operand.
8053   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8054   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8055   assert(Src.getValueType().isFloatingPoint());
8056   if (Src.getValueType() == MVT::f32) {
8057     if (IsStrict) {
8058       Src =
8059           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8060                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8061       Chain = Src.getValue(1);
8062     } else
8063       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8064   }
8065   SDValue Conv;
8066   unsigned Opc = ISD::DELETED_NODE;
8067   switch (Op.getSimpleValueType().SimpleTy) {
8068   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8069   case MVT::i32:
8070     Opc = IsSigned ? PPCISD::FCTIWZ
8071                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8072     break;
8073   case MVT::i64:
8074     assert((IsSigned || Subtarget.hasFPCVT()) &&
8075            "i64 FP_TO_UINT is supported only with FPCVT");
8076     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8077   }
8078   if (IsStrict) {
8079     Opc = getPPCStrictOpcode(Opc);
8080     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8081                        {Chain, Src}, Flags);
8082   } else {
8083     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8084   }
8085   return Conv;
8086 }
8087 
8088 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8089                                                SelectionDAG &DAG,
8090                                                const SDLoc &dl) const {
8091   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8092   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8093                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8094   bool IsStrict = Op->isStrictFPOpcode();
8095 
8096   // Convert the FP value to an int value through memory.
8097   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8098                   (IsSigned || Subtarget.hasFPCVT());
8099   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8100   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8101   MachinePointerInfo MPI =
8102       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8103 
8104   // Emit a store to the stack slot.
8105   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8106   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8107   if (i32Stack) {
8108     MachineFunction &MF = DAG.getMachineFunction();
8109     Alignment = Align(4);
8110     MachineMemOperand *MMO =
8111         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8112     SDValue Ops[] = { Chain, Tmp, FIPtr };
8113     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8114               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8115   } else
8116     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8117 
8118   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8119   // add in a bias on big endian.
8120   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8121     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8122                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8123     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8124   }
8125 
8126   RLI.Chain = Chain;
8127   RLI.Ptr = FIPtr;
8128   RLI.MPI = MPI;
8129   RLI.Alignment = Alignment;
8130 }
8131 
8132 /// Custom lowers floating point to integer conversions to use
8133 /// the direct move instructions available in ISA 2.07 to avoid the
8134 /// need for load/store combinations.
8135 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8136                                                     SelectionDAG &DAG,
8137                                                     const SDLoc &dl) const {
8138   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8139   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8140   if (Op->isStrictFPOpcode())
8141     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8142   else
8143     return Mov;
8144 }
8145 
8146 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8147                                           const SDLoc &dl) const {
8148   bool IsStrict = Op->isStrictFPOpcode();
8149   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8150                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8151   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8152   EVT SrcVT = Src.getValueType();
8153   EVT DstVT = Op.getValueType();
8154 
8155   // FP to INT conversions are legal for f128.
8156   if (SrcVT == MVT::f128)
8157     return Subtarget.hasP9Vector() ? Op : SDValue();
8158 
8159   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8160   // PPC (the libcall is not available).
8161   if (SrcVT == MVT::ppcf128) {
8162     if (DstVT == MVT::i32) {
8163       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8164       // set other fast-math flags to FP operations in both strict and
8165       // non-strict cases. (FP_TO_SINT, FSUB)
8166       SDNodeFlags Flags;
8167       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8168 
8169       if (IsSigned) {
8170         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8171                                  DAG.getIntPtrConstant(0, dl));
8172         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8173                                  DAG.getIntPtrConstant(1, dl));
8174 
8175         // Add the two halves of the long double in round-to-zero mode, and use
8176         // a smaller FP_TO_SINT.
8177         if (IsStrict) {
8178           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8179                                     DAG.getVTList(MVT::f64, MVT::Other),
8180                                     {Op.getOperand(0), Lo, Hi}, Flags);
8181           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8182                              DAG.getVTList(MVT::i32, MVT::Other),
8183                              {Res.getValue(1), Res}, Flags);
8184         } else {
8185           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8186           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8187         }
8188       } else {
8189         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8190         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8191         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8192         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8193         if (IsStrict) {
8194           // Sel = Src < 0x80000000
8195           // FltOfs = select Sel, 0.0, 0x80000000
8196           // IntOfs = select Sel, 0, 0x80000000
8197           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8198           SDValue Chain = Op.getOperand(0);
8199           EVT SetCCVT =
8200               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8201           EVT DstSetCCVT =
8202               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8203           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8204                                      Chain, true);
8205           Chain = Sel.getValue(1);
8206 
8207           SDValue FltOfs = DAG.getSelect(
8208               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8209           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8210 
8211           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8212                                     DAG.getVTList(SrcVT, MVT::Other),
8213                                     {Chain, Src, FltOfs}, Flags);
8214           Chain = Val.getValue(1);
8215           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8216                                      DAG.getVTList(DstVT, MVT::Other),
8217                                      {Chain, Val}, Flags);
8218           Chain = SInt.getValue(1);
8219           SDValue IntOfs = DAG.getSelect(
8220               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8221           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8222           return DAG.getMergeValues({Result, Chain}, dl);
8223         } else {
8224           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8225           // FIXME: generated code sucks.
8226           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8227           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8228           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8229           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8230           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8231         }
8232       }
8233     }
8234 
8235     return SDValue();
8236   }
8237 
8238   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8239     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8240 
8241   ReuseLoadInfo RLI;
8242   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8243 
8244   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8245                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8246 }
8247 
8248 // We're trying to insert a regular store, S, and then a load, L. If the
8249 // incoming value, O, is a load, we might just be able to have our load use the
8250 // address used by O. However, we don't know if anything else will store to
8251 // that address before we can load from it. To prevent this situation, we need
8252 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8253 // the same chain operand as O, we create a token factor from the chain results
8254 // of O and L, and we replace all uses of O's chain result with that token
8255 // factor (see spliceIntoChain below for this last part).
8256 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8257                                             ReuseLoadInfo &RLI,
8258                                             SelectionDAG &DAG,
8259                                             ISD::LoadExtType ET) const {
8260   // Conservatively skip reusing for constrained FP nodes.
8261   if (Op->isStrictFPOpcode())
8262     return false;
8263 
8264   SDLoc dl(Op);
8265   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8266                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8267   if (ET == ISD::NON_EXTLOAD &&
8268       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8269       isOperationLegalOrCustom(Op.getOpcode(),
8270                                Op.getOperand(0).getValueType())) {
8271 
8272     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8273     return true;
8274   }
8275 
8276   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8277   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8278       LD->isNonTemporal())
8279     return false;
8280   if (LD->getMemoryVT() != MemVT)
8281     return false;
8282 
8283   // If the result of the load is an illegal type, then we can't build a
8284   // valid chain for reuse since the legalised loads and token factor node that
8285   // ties the legalised loads together uses a different output chain then the
8286   // illegal load.
8287   if (!isTypeLegal(LD->getValueType(0)))
8288     return false;
8289 
8290   RLI.Ptr = LD->getBasePtr();
8291   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8292     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8293            "Non-pre-inc AM on PPC?");
8294     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8295                           LD->getOffset());
8296   }
8297 
8298   RLI.Chain = LD->getChain();
8299   RLI.MPI = LD->getPointerInfo();
8300   RLI.IsDereferenceable = LD->isDereferenceable();
8301   RLI.IsInvariant = LD->isInvariant();
8302   RLI.Alignment = LD->getAlign();
8303   RLI.AAInfo = LD->getAAInfo();
8304   RLI.Ranges = LD->getRanges();
8305 
8306   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8307   return true;
8308 }
8309 
8310 // Given the head of the old chain, ResChain, insert a token factor containing
8311 // it and NewResChain, and make users of ResChain now be users of that token
8312 // factor.
8313 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8314 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8315                                         SDValue NewResChain,
8316                                         SelectionDAG &DAG) const {
8317   if (!ResChain)
8318     return;
8319 
8320   SDLoc dl(NewResChain);
8321 
8322   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8323                            NewResChain, DAG.getUNDEF(MVT::Other));
8324   assert(TF.getNode() != NewResChain.getNode() &&
8325          "A new TF really is required here");
8326 
8327   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8328   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8329 }
8330 
8331 /// Analyze profitability of direct move
8332 /// prefer float load to int load plus direct move
8333 /// when there is no integer use of int load
8334 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8335   SDNode *Origin = Op.getOperand(0).getNode();
8336   if (Origin->getOpcode() != ISD::LOAD)
8337     return true;
8338 
8339   // If there is no LXSIBZX/LXSIHZX, like Power8,
8340   // prefer direct move if the memory size is 1 or 2 bytes.
8341   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8342   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8343     return true;
8344 
8345   for (SDNode::use_iterator UI = Origin->use_begin(),
8346                             UE = Origin->use_end();
8347        UI != UE; ++UI) {
8348 
8349     // Only look at the users of the loaded value.
8350     if (UI.getUse().get().getResNo() != 0)
8351       continue;
8352 
8353     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8354         UI->getOpcode() != ISD::UINT_TO_FP &&
8355         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8356         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8357       return true;
8358   }
8359 
8360   return false;
8361 }
8362 
8363 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8364                               const PPCSubtarget &Subtarget,
8365                               SDValue Chain = SDValue()) {
8366   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8367                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8368   SDLoc dl(Op);
8369 
8370   // TODO: Any other flags to propagate?
8371   SDNodeFlags Flags;
8372   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8373 
8374   // If we have FCFIDS, then use it when converting to single-precision.
8375   // Otherwise, convert to double-precision and then round.
8376   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8377   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8378                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8379   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8380   if (Op->isStrictFPOpcode()) {
8381     if (!Chain)
8382       Chain = Op.getOperand(0);
8383     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8384                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8385   } else
8386     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8387 }
8388 
8389 /// Custom lowers integer to floating point conversions to use
8390 /// the direct move instructions available in ISA 2.07 to avoid the
8391 /// need for load/store combinations.
8392 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8393                                                     SelectionDAG &DAG,
8394                                                     const SDLoc &dl) const {
8395   assert((Op.getValueType() == MVT::f32 ||
8396           Op.getValueType() == MVT::f64) &&
8397          "Invalid floating point type as target of conversion");
8398   assert(Subtarget.hasFPCVT() &&
8399          "Int to FP conversions with direct moves require FPCVT");
8400   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8401   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8402   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8403                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8404   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8405   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8406   return convertIntToFP(Op, Mov, DAG, Subtarget);
8407 }
8408 
8409 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8410 
8411   EVT VecVT = Vec.getValueType();
8412   assert(VecVT.isVector() && "Expected a vector type.");
8413   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8414 
8415   EVT EltVT = VecVT.getVectorElementType();
8416   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8417   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8418 
8419   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8420   SmallVector<SDValue, 16> Ops(NumConcat);
8421   Ops[0] = Vec;
8422   SDValue UndefVec = DAG.getUNDEF(VecVT);
8423   for (unsigned i = 1; i < NumConcat; ++i)
8424     Ops[i] = UndefVec;
8425 
8426   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8427 }
8428 
8429 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8430                                                 const SDLoc &dl) const {
8431   bool IsStrict = Op->isStrictFPOpcode();
8432   unsigned Opc = Op.getOpcode();
8433   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8434   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8435           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8436          "Unexpected conversion type");
8437   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8438          "Supports conversions to v2f64/v4f32 only.");
8439 
8440   // TODO: Any other flags to propagate?
8441   SDNodeFlags Flags;
8442   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8443 
8444   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8445   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8446 
8447   SDValue Wide = widenVec(DAG, Src, dl);
8448   EVT WideVT = Wide.getValueType();
8449   unsigned WideNumElts = WideVT.getVectorNumElements();
8450   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8451 
8452   SmallVector<int, 16> ShuffV;
8453   for (unsigned i = 0; i < WideNumElts; ++i)
8454     ShuffV.push_back(i + WideNumElts);
8455 
8456   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8457   int SaveElts = FourEltRes ? 4 : 2;
8458   if (Subtarget.isLittleEndian())
8459     for (int i = 0; i < SaveElts; i++)
8460       ShuffV[i * Stride] = i;
8461   else
8462     for (int i = 1; i <= SaveElts; i++)
8463       ShuffV[i * Stride - 1] = i - 1;
8464 
8465   SDValue ShuffleSrc2 =
8466       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8467   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8468 
8469   SDValue Extend;
8470   if (SignedConv) {
8471     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8472     EVT ExtVT = Src.getValueType();
8473     if (Subtarget.hasP9Altivec())
8474       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8475                                IntermediateVT.getVectorNumElements());
8476 
8477     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8478                          DAG.getValueType(ExtVT));
8479   } else
8480     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8481 
8482   if (IsStrict)
8483     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8484                        {Op.getOperand(0), Extend}, Flags);
8485 
8486   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8487 }
8488 
8489 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8490                                           SelectionDAG &DAG) const {
8491   SDLoc dl(Op);
8492   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8493                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8494   bool IsStrict = Op->isStrictFPOpcode();
8495   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8496   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8497 
8498   // TODO: Any other flags to propagate?
8499   SDNodeFlags Flags;
8500   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8501 
8502   EVT InVT = Src.getValueType();
8503   EVT OutVT = Op.getValueType();
8504   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8505       isOperationCustom(Op.getOpcode(), InVT))
8506     return LowerINT_TO_FPVector(Op, DAG, dl);
8507 
8508   // Conversions to f128 are legal.
8509   if (Op.getValueType() == MVT::f128)
8510     return Subtarget.hasP9Vector() ? Op : SDValue();
8511 
8512   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8513   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8514     return SDValue();
8515 
8516   if (Src.getValueType() == MVT::i1) {
8517     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8518                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8519                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8520     if (IsStrict)
8521       return DAG.getMergeValues({Sel, Chain}, dl);
8522     else
8523       return Sel;
8524   }
8525 
8526   // If we have direct moves, we can do all the conversion, skip the store/load
8527   // however, without FPCVT we can't do most conversions.
8528   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8529       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8530     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8531 
8532   assert((IsSigned || Subtarget.hasFPCVT()) &&
8533          "UINT_TO_FP is supported only with FPCVT");
8534 
8535   if (Src.getValueType() == MVT::i64) {
8536     SDValue SINT = Src;
8537     // When converting to single-precision, we actually need to convert
8538     // to double-precision first and then round to single-precision.
8539     // To avoid double-rounding effects during that operation, we have
8540     // to prepare the input operand.  Bits that might be truncated when
8541     // converting to double-precision are replaced by a bit that won't
8542     // be lost at this stage, but is below the single-precision rounding
8543     // position.
8544     //
8545     // However, if -enable-unsafe-fp-math is in effect, accept double
8546     // rounding to avoid the extra overhead.
8547     if (Op.getValueType() == MVT::f32 &&
8548         !Subtarget.hasFPCVT() &&
8549         !DAG.getTarget().Options.UnsafeFPMath) {
8550 
8551       // Twiddle input to make sure the low 11 bits are zero.  (If this
8552       // is the case, we are guaranteed the value will fit into the 53 bit
8553       // mantissa of an IEEE double-precision value without rounding.)
8554       // If any of those low 11 bits were not zero originally, make sure
8555       // bit 12 (value 2048) is set instead, so that the final rounding
8556       // to single-precision gets the correct result.
8557       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8558                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8559       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8560                           Round, DAG.getConstant(2047, dl, MVT::i64));
8561       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8562       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8563                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8564 
8565       // However, we cannot use that value unconditionally: if the magnitude
8566       // of the input value is small, the bit-twiddling we did above might
8567       // end up visibly changing the output.  Fortunately, in that case, we
8568       // don't need to twiddle bits since the original input will convert
8569       // exactly to double-precision floating-point already.  Therefore,
8570       // construct a conditional to use the original value if the top 11
8571       // bits are all sign-bit copies, and use the rounded value computed
8572       // above otherwise.
8573       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8574                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8575       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8576                          Cond, DAG.getConstant(1, dl, MVT::i64));
8577       Cond = DAG.getSetCC(
8578           dl,
8579           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8580           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8581 
8582       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8583     }
8584 
8585     ReuseLoadInfo RLI;
8586     SDValue Bits;
8587 
8588     MachineFunction &MF = DAG.getMachineFunction();
8589     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8590       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8591                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8592       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8593     } else if (Subtarget.hasLFIWAX() &&
8594                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8595       MachineMemOperand *MMO =
8596         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8597                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8598       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8599       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8600                                      DAG.getVTList(MVT::f64, MVT::Other),
8601                                      Ops, MVT::i32, MMO);
8602       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8603     } else if (Subtarget.hasFPCVT() &&
8604                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8605       MachineMemOperand *MMO =
8606         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8607                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8608       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8609       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8610                                      DAG.getVTList(MVT::f64, MVT::Other),
8611                                      Ops, MVT::i32, MMO);
8612       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8613     } else if (((Subtarget.hasLFIWAX() &&
8614                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8615                 (Subtarget.hasFPCVT() &&
8616                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8617                SINT.getOperand(0).getValueType() == MVT::i32) {
8618       MachineFrameInfo &MFI = MF.getFrameInfo();
8619       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8620 
8621       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8622       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8623 
8624       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8625                                    MachinePointerInfo::getFixedStack(
8626                                        DAG.getMachineFunction(), FrameIdx));
8627       Chain = Store;
8628 
8629       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8630              "Expected an i32 store");
8631 
8632       RLI.Ptr = FIdx;
8633       RLI.Chain = Chain;
8634       RLI.MPI =
8635           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8636       RLI.Alignment = Align(4);
8637 
8638       MachineMemOperand *MMO =
8639         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8640                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8641       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8642       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8643                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8644                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8645                                      Ops, MVT::i32, MMO);
8646       Chain = Bits.getValue(1);
8647     } else
8648       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8649 
8650     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8651     if (IsStrict)
8652       Chain = FP.getValue(1);
8653 
8654     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8655       if (IsStrict)
8656         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8657                          DAG.getVTList(MVT::f32, MVT::Other),
8658                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8659       else
8660         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8661                          DAG.getIntPtrConstant(0, dl));
8662     }
8663     return FP;
8664   }
8665 
8666   assert(Src.getValueType() == MVT::i32 &&
8667          "Unhandled INT_TO_FP type in custom expander!");
8668   // Since we only generate this in 64-bit mode, we can take advantage of
8669   // 64-bit registers.  In particular, sign extend the input value into the
8670   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8671   // then lfd it and fcfid it.
8672   MachineFunction &MF = DAG.getMachineFunction();
8673   MachineFrameInfo &MFI = MF.getFrameInfo();
8674   EVT PtrVT = getPointerTy(MF.getDataLayout());
8675 
8676   SDValue Ld;
8677   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8678     ReuseLoadInfo RLI;
8679     bool ReusingLoad;
8680     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8681       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8682       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8683 
8684       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8685                                    MachinePointerInfo::getFixedStack(
8686                                        DAG.getMachineFunction(), FrameIdx));
8687       Chain = Store;
8688 
8689       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8690              "Expected an i32 store");
8691 
8692       RLI.Ptr = FIdx;
8693       RLI.Chain = Chain;
8694       RLI.MPI =
8695           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8696       RLI.Alignment = Align(4);
8697     }
8698 
8699     MachineMemOperand *MMO =
8700       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8701                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8702     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8703     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8704                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8705                                  MVT::i32, MMO);
8706     Chain = Ld.getValue(1);
8707     if (ReusingLoad)
8708       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8709   } else {
8710     assert(Subtarget.isPPC64() &&
8711            "i32->FP without LFIWAX supported only on PPC64");
8712 
8713     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8714     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8715 
8716     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8717 
8718     // STD the extended value into the stack slot.
8719     SDValue Store = DAG.getStore(
8720         Chain, dl, Ext64, FIdx,
8721         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8722     Chain = Store;
8723 
8724     // Load the value as a double.
8725     Ld = DAG.getLoad(
8726         MVT::f64, dl, Chain, FIdx,
8727         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8728     Chain = Ld.getValue(1);
8729   }
8730 
8731   // FCFID it and return it.
8732   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8733   if (IsStrict)
8734     Chain = FP.getValue(1);
8735   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8736     if (IsStrict)
8737       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8738                        DAG.getVTList(MVT::f32, MVT::Other),
8739                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8740     else
8741       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8742                        DAG.getIntPtrConstant(0, dl));
8743   }
8744   return FP;
8745 }
8746 
8747 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8748                                             SelectionDAG &DAG) const {
8749   SDLoc dl(Op);
8750   /*
8751    The rounding mode is in bits 30:31 of FPSR, and has the following
8752    settings:
8753      00 Round to nearest
8754      01 Round to 0
8755      10 Round to +inf
8756      11 Round to -inf
8757 
8758   FLT_ROUNDS, on the other hand, expects the following:
8759     -1 Undefined
8760      0 Round to 0
8761      1 Round to nearest
8762      2 Round to +inf
8763      3 Round to -inf
8764 
8765   To perform the conversion, we do:
8766     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8767   */
8768 
8769   MachineFunction &MF = DAG.getMachineFunction();
8770   EVT VT = Op.getValueType();
8771   EVT PtrVT = getPointerTy(MF.getDataLayout());
8772 
8773   // Save FP Control Word to register
8774   SDValue Chain = Op.getOperand(0);
8775   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8776   Chain = MFFS.getValue(1);
8777 
8778   SDValue CWD;
8779   if (isTypeLegal(MVT::i64)) {
8780     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8781                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8782   } else {
8783     // Save FP register to stack slot
8784     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8785     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8786     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8787 
8788     // Load FP Control Word from low 32 bits of stack slot.
8789     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8790            "Stack slot adjustment is valid only on big endian subtargets!");
8791     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8792     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8793     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8794     Chain = CWD.getValue(1);
8795   }
8796 
8797   // Transform as necessary
8798   SDValue CWD1 =
8799     DAG.getNode(ISD::AND, dl, MVT::i32,
8800                 CWD, DAG.getConstant(3, dl, MVT::i32));
8801   SDValue CWD2 =
8802     DAG.getNode(ISD::SRL, dl, MVT::i32,
8803                 DAG.getNode(ISD::AND, dl, MVT::i32,
8804                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8805                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8806                             DAG.getConstant(3, dl, MVT::i32)),
8807                 DAG.getConstant(1, dl, MVT::i32));
8808 
8809   SDValue RetVal =
8810     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8811 
8812   RetVal =
8813       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8814                   dl, VT, RetVal);
8815 
8816   return DAG.getMergeValues({RetVal, Chain}, dl);
8817 }
8818 
8819 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8820   EVT VT = Op.getValueType();
8821   unsigned BitWidth = VT.getSizeInBits();
8822   SDLoc dl(Op);
8823   assert(Op.getNumOperands() == 3 &&
8824          VT == Op.getOperand(1).getValueType() &&
8825          "Unexpected SHL!");
8826 
8827   // Expand into a bunch of logical ops.  Note that these ops
8828   // depend on the PPC behavior for oversized shift amounts.
8829   SDValue Lo = Op.getOperand(0);
8830   SDValue Hi = Op.getOperand(1);
8831   SDValue Amt = Op.getOperand(2);
8832   EVT AmtVT = Amt.getValueType();
8833 
8834   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8835                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8836   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8837   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8838   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8839   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8840                              DAG.getConstant(-BitWidth, dl, AmtVT));
8841   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8842   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8843   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8844   SDValue OutOps[] = { OutLo, OutHi };
8845   return DAG.getMergeValues(OutOps, dl);
8846 }
8847 
8848 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8849   EVT VT = Op.getValueType();
8850   SDLoc dl(Op);
8851   unsigned BitWidth = VT.getSizeInBits();
8852   assert(Op.getNumOperands() == 3 &&
8853          VT == Op.getOperand(1).getValueType() &&
8854          "Unexpected SRL!");
8855 
8856   // Expand into a bunch of logical ops.  Note that these ops
8857   // depend on the PPC behavior for oversized shift amounts.
8858   SDValue Lo = Op.getOperand(0);
8859   SDValue Hi = Op.getOperand(1);
8860   SDValue Amt = Op.getOperand(2);
8861   EVT AmtVT = Amt.getValueType();
8862 
8863   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8864                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8865   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8866   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8867   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8868   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8869                              DAG.getConstant(-BitWidth, dl, AmtVT));
8870   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8871   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8872   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8873   SDValue OutOps[] = { OutLo, OutHi };
8874   return DAG.getMergeValues(OutOps, dl);
8875 }
8876 
8877 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8878   SDLoc dl(Op);
8879   EVT VT = Op.getValueType();
8880   unsigned BitWidth = VT.getSizeInBits();
8881   assert(Op.getNumOperands() == 3 &&
8882          VT == Op.getOperand(1).getValueType() &&
8883          "Unexpected SRA!");
8884 
8885   // Expand into a bunch of logical ops, followed by a select_cc.
8886   SDValue Lo = Op.getOperand(0);
8887   SDValue Hi = Op.getOperand(1);
8888   SDValue Amt = Op.getOperand(2);
8889   EVT AmtVT = Amt.getValueType();
8890 
8891   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8892                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8893   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8894   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8895   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8896   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8897                              DAG.getConstant(-BitWidth, dl, AmtVT));
8898   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8899   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8900   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8901                                   Tmp4, Tmp6, ISD::SETLE);
8902   SDValue OutOps[] = { OutLo, OutHi };
8903   return DAG.getMergeValues(OutOps, dl);
8904 }
8905 
8906 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8907                                             SelectionDAG &DAG) const {
8908   SDLoc dl(Op);
8909   EVT VT = Op.getValueType();
8910   unsigned BitWidth = VT.getSizeInBits();
8911 
8912   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8913   SDValue X = Op.getOperand(0);
8914   SDValue Y = Op.getOperand(1);
8915   SDValue Z = Op.getOperand(2);
8916   EVT AmtVT = Z.getValueType();
8917 
8918   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8919   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8920   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8921   // on PowerPC shift by BW being well defined.
8922   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8923                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8924   SDValue SubZ =
8925       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8926   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8927   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8928   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8929 }
8930 
8931 //===----------------------------------------------------------------------===//
8932 // Vector related lowering.
8933 //
8934 
8935 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8936 /// element size of SplatSize. Cast the result to VT.
8937 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8938                                       SelectionDAG &DAG, const SDLoc &dl) {
8939   static const MVT VTys[] = { // canonical VT to use for each size.
8940     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8941   };
8942 
8943   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8944 
8945   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8946   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8947     SplatSize = 1;
8948     Val = 0xFF;
8949   }
8950 
8951   EVT CanonicalVT = VTys[SplatSize-1];
8952 
8953   // Build a canonical splat for this value.
8954   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8955 }
8956 
8957 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8958 /// specified intrinsic ID.
8959 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8960                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8961   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8962   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8963                      DAG.getConstant(IID, dl, MVT::i32), Op);
8964 }
8965 
8966 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8967 /// specified intrinsic ID.
8968 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8969                                 SelectionDAG &DAG, const SDLoc &dl,
8970                                 EVT DestVT = MVT::Other) {
8971   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8972   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8973                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8974 }
8975 
8976 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8977 /// specified intrinsic ID.
8978 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8979                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8980                                 EVT DestVT = MVT::Other) {
8981   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8982   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8983                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8984 }
8985 
8986 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8987 /// amount.  The result has the specified value type.
8988 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8989                            SelectionDAG &DAG, const SDLoc &dl) {
8990   // Force LHS/RHS to be the right type.
8991   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8992   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8993 
8994   int Ops[16];
8995   for (unsigned i = 0; i != 16; ++i)
8996     Ops[i] = i + Amt;
8997   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8998   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8999 }
9000 
9001 /// Do we have an efficient pattern in a .td file for this node?
9002 ///
9003 /// \param V - pointer to the BuildVectorSDNode being matched
9004 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9005 ///
9006 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9007 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9008 /// the opposite is true (expansion is beneficial) are:
9009 /// - The node builds a vector out of integers that are not 32 or 64-bits
9010 /// - The node builds a vector out of constants
9011 /// - The node is a "load-and-splat"
9012 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9013 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9014                                             bool HasDirectMove,
9015                                             bool HasP8Vector) {
9016   EVT VecVT = V->getValueType(0);
9017   bool RightType = VecVT == MVT::v2f64 ||
9018     (HasP8Vector && VecVT == MVT::v4f32) ||
9019     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9020   if (!RightType)
9021     return false;
9022 
9023   bool IsSplat = true;
9024   bool IsLoad = false;
9025   SDValue Op0 = V->getOperand(0);
9026 
9027   // This function is called in a block that confirms the node is not a constant
9028   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9029   // different constants.
9030   if (V->isConstant())
9031     return false;
9032   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9033     if (V->getOperand(i).isUndef())
9034       return false;
9035     // We want to expand nodes that represent load-and-splat even if the
9036     // loaded value is a floating point truncation or conversion to int.
9037     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9038         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9039          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9040         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9041          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9042         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9043          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9044       IsLoad = true;
9045     // If the operands are different or the input is not a load and has more
9046     // uses than just this BV node, then it isn't a splat.
9047     if (V->getOperand(i) != Op0 ||
9048         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9049       IsSplat = false;
9050   }
9051   return !(IsSplat && IsLoad);
9052 }
9053 
9054 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9055 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9056 
9057   SDLoc dl(Op);
9058   SDValue Op0 = Op->getOperand(0);
9059 
9060   if ((Op.getValueType() != MVT::f128) ||
9061       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9062       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9063       (Op0.getOperand(1).getValueType() != MVT::i64))
9064     return SDValue();
9065 
9066   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9067                      Op0.getOperand(1));
9068 }
9069 
9070 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9071   const SDValue *InputLoad = &Op;
9072   if (InputLoad->getOpcode() == ISD::BITCAST)
9073     InputLoad = &InputLoad->getOperand(0);
9074   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9075       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9076     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9077     InputLoad = &InputLoad->getOperand(0);
9078   }
9079   if (InputLoad->getOpcode() != ISD::LOAD)
9080     return nullptr;
9081   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9082   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9083 }
9084 
9085 // Convert the argument APFloat to a single precision APFloat if there is no
9086 // loss in information during the conversion to single precision APFloat and the
9087 // resulting number is not a denormal number. Return true if successful.
9088 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9089   APFloat APFloatToConvert = ArgAPFloat;
9090   bool LosesInfo = true;
9091   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9092                            &LosesInfo);
9093   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9094   if (Success)
9095     ArgAPFloat = APFloatToConvert;
9096   return Success;
9097 }
9098 
9099 // Bitcast the argument APInt to a double and convert it to a single precision
9100 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9101 // argument if there is no loss in information during the conversion from
9102 // double to single precision APFloat and the resulting number is not a denormal
9103 // number. Return true if successful.
9104 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9105   double DpValue = ArgAPInt.bitsToDouble();
9106   APFloat APFloatDp(DpValue);
9107   bool Success = convertToNonDenormSingle(APFloatDp);
9108   if (Success)
9109     ArgAPInt = APFloatDp.bitcastToAPInt();
9110   return Success;
9111 }
9112 
9113 // Nondestructive check for convertTonNonDenormSingle.
9114 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9115   // Only convert if it loses info, since XXSPLTIDP should
9116   // handle the other case.
9117   APFloat APFloatToConvert = ArgAPFloat;
9118   bool LosesInfo = true;
9119   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9120                            &LosesInfo);
9121 
9122   return (!LosesInfo && !APFloatToConvert.isDenormal());
9123 }
9124 
9125 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9126                              unsigned &Opcode) {
9127   LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9128   if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9129     return false;
9130 
9131   EVT Ty = Op->getValueType(0);
9132   // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9133   // as we cannot handle extending loads for these types.
9134   if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9135       ISD::isNON_EXTLoad(InputNode))
9136     return true;
9137 
9138   EVT MemVT = InputNode->getMemoryVT();
9139   // For v8i16 and v16i8 types, extending loads can be handled as long as the
9140   // memory VT is the same vector element VT type.
9141   // The loads feeding into the v8i16 and v16i8 types will be extending because
9142   // scalar i8/i16 are not legal types.
9143   if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9144       (MemVT == Ty.getVectorElementType()))
9145     return true;
9146 
9147   if (Ty == MVT::v2i64) {
9148     // Check the extend type, when the input type is i32, and the output vector
9149     // type is v2i64.
9150     if (MemVT == MVT::i32) {
9151       if (ISD::isZEXTLoad(InputNode))
9152         Opcode = PPCISD::ZEXT_LD_SPLAT;
9153       if (ISD::isSEXTLoad(InputNode))
9154         Opcode = PPCISD::SEXT_LD_SPLAT;
9155     }
9156     return true;
9157   }
9158   return false;
9159 }
9160 
9161 // If this is a case we can't handle, return null and let the default
9162 // expansion code take care of it.  If we CAN select this case, and if it
9163 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9164 // this case more efficiently than a constant pool load, lower it to the
9165 // sequence of ops that should be used.
9166 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9167                                              SelectionDAG &DAG) const {
9168   SDLoc dl(Op);
9169   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9170   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9171 
9172   // Check if this is a splat of a constant value.
9173   APInt APSplatBits, APSplatUndef;
9174   unsigned SplatBitSize;
9175   bool HasAnyUndefs;
9176   bool BVNIsConstantSplat =
9177       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9178                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9179 
9180   // If it is a splat of a double, check if we can shrink it to a 32 bit
9181   // non-denormal float which when converted back to double gives us the same
9182   // double. This is to exploit the XXSPLTIDP instruction.
9183   // If we lose precision, we use XXSPLTI32DX.
9184   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9185       Subtarget.hasPrefixInstrs()) {
9186     // Check the type first to short-circuit so we don't modify APSplatBits if
9187     // this block isn't executed.
9188     if ((Op->getValueType(0) == MVT::v2f64) &&
9189         convertToNonDenormSingle(APSplatBits)) {
9190       SDValue SplatNode = DAG.getNode(
9191           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9192           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9193       return DAG.getBitcast(Op.getValueType(), SplatNode);
9194     } else {
9195       // We may lose precision, so we have to use XXSPLTI32DX.
9196 
9197       uint32_t Hi =
9198           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9199       uint32_t Lo =
9200           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9201       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9202 
9203       if (!Hi || !Lo)
9204         // If either load is 0, then we should generate XXLXOR to set to 0.
9205         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9206 
9207       if (Hi)
9208         SplatNode = DAG.getNode(
9209             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9210             DAG.getTargetConstant(0, dl, MVT::i32),
9211             DAG.getTargetConstant(Hi, dl, MVT::i32));
9212 
9213       if (Lo)
9214         SplatNode =
9215             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9216                         DAG.getTargetConstant(1, dl, MVT::i32),
9217                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9218 
9219       return DAG.getBitcast(Op.getValueType(), SplatNode);
9220     }
9221   }
9222 
9223   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9224     unsigned NewOpcode = PPCISD::LD_SPLAT;
9225 
9226     // Handle load-and-splat patterns as we have instructions that will do this
9227     // in one go.
9228     if (DAG.isSplatValue(Op, true) &&
9229         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9230       const SDValue *InputLoad = &Op.getOperand(0);
9231       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9232 
9233       // If the input load is an extending load, it will be an i32 -> i64
9234       // extending load and isValidSplatLoad() will update NewOpcode.
9235       unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9236       unsigned ElementSize =
9237           MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9238 
9239       assert(((ElementSize == 2 * MemorySize)
9240                   ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9241                      NewOpcode == PPCISD::SEXT_LD_SPLAT)
9242                   : (NewOpcode == PPCISD::LD_SPLAT)) &&
9243              "Unmatched element size and opcode!\n");
9244 
9245       // Checking for a single use of this load, we have to check for vector
9246       // width (128 bits) / ElementSize uses (since each operand of the
9247       // BUILD_VECTOR is a separate use of the value.
9248       unsigned NumUsesOfInputLD = 128 / ElementSize;
9249       for (SDValue BVInOp : Op->ops())
9250         if (BVInOp.isUndef())
9251           NumUsesOfInputLD--;
9252 
9253       // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9254       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9255       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9256       // 15", but funciton IsValidSplatLoad() now will only return true when
9257       // the data at index 0 is not nullptr. So we will not get into trouble for
9258       // these cases.
9259       //
9260       // case 1 - lfiwzx/lfiwax
9261       // 1.1: load result is i32 and is sign/zero extend to i64;
9262       // 1.2: build a v2i64 vector type with above loaded value;
9263       // 1.3: the vector has only one value at index 0, others are all undef;
9264       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9265       if (NumUsesOfInputLD == 1 &&
9266           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9267            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9268            Subtarget.hasLFIWAX()))
9269         return SDValue();
9270 
9271       // case 2 - lxvr[hb]x
9272       // 2.1: load result is at most i16;
9273       // 2.2: build a vector with above loaded value;
9274       // 2.3: the vector has only one value at index 0, others are all undef;
9275       // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9276       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9277           Subtarget.isISA3_1() && ElementSize <= 16)
9278         return SDValue();
9279 
9280       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9281       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9282           Subtarget.hasVSX()) {
9283         SDValue Ops[] = {
9284           LD->getChain(),    // Chain
9285           LD->getBasePtr(),  // Ptr
9286           DAG.getValueType(Op.getValueType()) // VT
9287         };
9288         SDValue LdSplt = DAG.getMemIntrinsicNode(
9289             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9290             LD->getMemoryVT(), LD->getMemOperand());
9291         // Replace all uses of the output chain of the original load with the
9292         // output chain of the new load.
9293         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9294                                       LdSplt.getValue(1));
9295         return LdSplt;
9296       }
9297     }
9298 
9299     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9300     // 32-bits can be lowered to VSX instructions under certain conditions.
9301     // Without VSX, there is no pattern more efficient than expanding the node.
9302     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9303         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9304                                         Subtarget.hasP8Vector()))
9305       return Op;
9306     return SDValue();
9307   }
9308 
9309   uint64_t SplatBits = APSplatBits.getZExtValue();
9310   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9311   unsigned SplatSize = SplatBitSize / 8;
9312 
9313   // First, handle single instruction cases.
9314 
9315   // All zeros?
9316   if (SplatBits == 0) {
9317     // Canonicalize all zero vectors to be v4i32.
9318     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9319       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9320       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9321     }
9322     return Op;
9323   }
9324 
9325   // We have XXSPLTIW for constant splats four bytes wide.
9326   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9327   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9328   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9329   // turned into a 4-byte splat of 0xABABABAB.
9330   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9331     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9332                                   Op.getValueType(), DAG, dl);
9333 
9334   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9335     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9336                                   dl);
9337 
9338   // We have XXSPLTIB for constant splats one byte wide.
9339   if (Subtarget.hasP9Vector() && SplatSize == 1)
9340     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9341                                   dl);
9342 
9343   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9344   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9345                     (32-SplatBitSize));
9346   if (SextVal >= -16 && SextVal <= 15)
9347     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9348                                   dl);
9349 
9350   // Two instruction sequences.
9351 
9352   // If this value is in the range [-32,30] and is even, use:
9353   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9354   // If this value is in the range [17,31] and is odd, use:
9355   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9356   // If this value is in the range [-31,-17] and is odd, use:
9357   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9358   // Note the last two are three-instruction sequences.
9359   if (SextVal >= -32 && SextVal <= 31) {
9360     // To avoid having these optimizations undone by constant folding,
9361     // we convert to a pseudo that will be expanded later into one of
9362     // the above forms.
9363     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9364     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9365               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9366     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9367     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9368     if (VT == Op.getValueType())
9369       return RetVal;
9370     else
9371       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9372   }
9373 
9374   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9375   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9376   // for fneg/fabs.
9377   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9378     // Make -1 and vspltisw -1:
9379     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9380 
9381     // Make the VSLW intrinsic, computing 0x8000_0000.
9382     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9383                                    OnesV, DAG, dl);
9384 
9385     // xor by OnesV to invert it.
9386     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9387     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9388   }
9389 
9390   // Check to see if this is a wide variety of vsplti*, binop self cases.
9391   static const signed char SplatCsts[] = {
9392     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9393     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9394   };
9395 
9396   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9397     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9398     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9399     int i = SplatCsts[idx];
9400 
9401     // Figure out what shift amount will be used by altivec if shifted by i in
9402     // this splat size.
9403     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9404 
9405     // vsplti + shl 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_vslb, Intrinsic::ppc_altivec_vslh, 0,
9410         Intrinsic::ppc_altivec_vslw
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 + srl self.
9417     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9418       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9419       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9420         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9421         Intrinsic::ppc_altivec_vsrw
9422       };
9423       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9424       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9425     }
9426 
9427     // vsplti + rol self.
9428     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9429                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9430       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9431       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9432         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9433         Intrinsic::ppc_altivec_vrlw
9434       };
9435       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9436       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9437     }
9438 
9439     // t = vsplti c, result = vsldoi t, t, 1
9440     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9441       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9442       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9443       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9444     }
9445     // t = vsplti c, result = vsldoi t, t, 2
9446     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9447       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9448       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9449       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9450     }
9451     // t = vsplti c, result = vsldoi t, t, 3
9452     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9453       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9454       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9455       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9456     }
9457   }
9458 
9459   return SDValue();
9460 }
9461 
9462 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9463 /// the specified operations to build the shuffle.
9464 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9465                                       SDValue RHS, SelectionDAG &DAG,
9466                                       const SDLoc &dl) {
9467   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9468   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9469   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9470 
9471   enum {
9472     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9473     OP_VMRGHW,
9474     OP_VMRGLW,
9475     OP_VSPLTISW0,
9476     OP_VSPLTISW1,
9477     OP_VSPLTISW2,
9478     OP_VSPLTISW3,
9479     OP_VSLDOI4,
9480     OP_VSLDOI8,
9481     OP_VSLDOI12
9482   };
9483 
9484   if (OpNum == OP_COPY) {
9485     if (LHSID == (1*9+2)*9+3) return LHS;
9486     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9487     return RHS;
9488   }
9489 
9490   SDValue OpLHS, OpRHS;
9491   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9492   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9493 
9494   int ShufIdxs[16];
9495   switch (OpNum) {
9496   default: llvm_unreachable("Unknown i32 permute!");
9497   case OP_VMRGHW:
9498     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9499     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9500     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9501     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9502     break;
9503   case OP_VMRGLW:
9504     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9505     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9506     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9507     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9508     break;
9509   case OP_VSPLTISW0:
9510     for (unsigned i = 0; i != 16; ++i)
9511       ShufIdxs[i] = (i&3)+0;
9512     break;
9513   case OP_VSPLTISW1:
9514     for (unsigned i = 0; i != 16; ++i)
9515       ShufIdxs[i] = (i&3)+4;
9516     break;
9517   case OP_VSPLTISW2:
9518     for (unsigned i = 0; i != 16; ++i)
9519       ShufIdxs[i] = (i&3)+8;
9520     break;
9521   case OP_VSPLTISW3:
9522     for (unsigned i = 0; i != 16; ++i)
9523       ShufIdxs[i] = (i&3)+12;
9524     break;
9525   case OP_VSLDOI4:
9526     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9527   case OP_VSLDOI8:
9528     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9529   case OP_VSLDOI12:
9530     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9531   }
9532   EVT VT = OpLHS.getValueType();
9533   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9534   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9535   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9536   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9537 }
9538 
9539 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9540 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9541 /// SDValue.
9542 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9543                                            SelectionDAG &DAG) const {
9544   const unsigned BytesInVector = 16;
9545   bool IsLE = Subtarget.isLittleEndian();
9546   SDLoc dl(N);
9547   SDValue V1 = N->getOperand(0);
9548   SDValue V2 = N->getOperand(1);
9549   unsigned ShiftElts = 0, InsertAtByte = 0;
9550   bool Swap = false;
9551 
9552   // Shifts required to get the byte we want at element 7.
9553   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9554                                    0, 15, 14, 13, 12, 11, 10, 9};
9555   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9556                                 1, 2,  3,  4,  5,  6,  7,  8};
9557 
9558   ArrayRef<int> Mask = N->getMask();
9559   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9560 
9561   // For each mask element, find out if we're just inserting something
9562   // from V2 into V1 or vice versa.
9563   // Possible permutations inserting an element from V2 into V1:
9564   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9565   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9566   //   ...
9567   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9568   // Inserting from V1 into V2 will be similar, except mask range will be
9569   // [16,31].
9570 
9571   bool FoundCandidate = false;
9572   // If both vector operands for the shuffle are the same vector, the mask
9573   // will contain only elements from the first one and the second one will be
9574   // undef.
9575   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9576   // Go through the mask of half-words to find an element that's being moved
9577   // from one vector to the other.
9578   for (unsigned i = 0; i < BytesInVector; ++i) {
9579     unsigned CurrentElement = Mask[i];
9580     // If 2nd operand is undefined, we should only look for element 7 in the
9581     // Mask.
9582     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9583       continue;
9584 
9585     bool OtherElementsInOrder = true;
9586     // Examine the other elements in the Mask to see if they're in original
9587     // order.
9588     for (unsigned j = 0; j < BytesInVector; ++j) {
9589       if (j == i)
9590         continue;
9591       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9592       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9593       // in which we always assume we're always picking from the 1st operand.
9594       int MaskOffset =
9595           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9596       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9597         OtherElementsInOrder = false;
9598         break;
9599       }
9600     }
9601     // If other elements are in original order, we record the number of shifts
9602     // we need to get the element we want into element 7. Also record which byte
9603     // in the vector we should insert into.
9604     if (OtherElementsInOrder) {
9605       // If 2nd operand is undefined, we assume no shifts and no swapping.
9606       if (V2.isUndef()) {
9607         ShiftElts = 0;
9608         Swap = false;
9609       } else {
9610         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9611         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9612                          : BigEndianShifts[CurrentElement & 0xF];
9613         Swap = CurrentElement < BytesInVector;
9614       }
9615       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9616       FoundCandidate = true;
9617       break;
9618     }
9619   }
9620 
9621   if (!FoundCandidate)
9622     return SDValue();
9623 
9624   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9625   // optionally with VECSHL if shift is required.
9626   if (Swap)
9627     std::swap(V1, V2);
9628   if (V2.isUndef())
9629     V2 = V1;
9630   if (ShiftElts) {
9631     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9632                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9633     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9634                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9635   }
9636   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9637                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9638 }
9639 
9640 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9641 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9642 /// SDValue.
9643 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9644                                            SelectionDAG &DAG) const {
9645   const unsigned NumHalfWords = 8;
9646   const unsigned BytesInVector = NumHalfWords * 2;
9647   // Check that the shuffle is on half-words.
9648   if (!isNByteElemShuffleMask(N, 2, 1))
9649     return SDValue();
9650 
9651   bool IsLE = Subtarget.isLittleEndian();
9652   SDLoc dl(N);
9653   SDValue V1 = N->getOperand(0);
9654   SDValue V2 = N->getOperand(1);
9655   unsigned ShiftElts = 0, InsertAtByte = 0;
9656   bool Swap = false;
9657 
9658   // Shifts required to get the half-word we want at element 3.
9659   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9660   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9661 
9662   uint32_t Mask = 0;
9663   uint32_t OriginalOrderLow = 0x1234567;
9664   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9665   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9666   // 32-bit space, only need 4-bit nibbles per element.
9667   for (unsigned i = 0; i < NumHalfWords; ++i) {
9668     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9669     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9670   }
9671 
9672   // For each mask element, find out if we're just inserting something
9673   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9674   // from V2 into V1:
9675   //   X, 1, 2, 3, 4, 5, 6, 7
9676   //   0, X, 2, 3, 4, 5, 6, 7
9677   //   0, 1, X, 3, 4, 5, 6, 7
9678   //   0, 1, 2, X, 4, 5, 6, 7
9679   //   0, 1, 2, 3, X, 5, 6, 7
9680   //   0, 1, 2, 3, 4, X, 6, 7
9681   //   0, 1, 2, 3, 4, 5, X, 7
9682   //   0, 1, 2, 3, 4, 5, 6, X
9683   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9684 
9685   bool FoundCandidate = false;
9686   // Go through the mask of half-words to find an element that's being moved
9687   // from one vector to the other.
9688   for (unsigned i = 0; i < NumHalfWords; ++i) {
9689     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9690     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9691     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9692     uint32_t TargetOrder = 0x0;
9693 
9694     // If both vector operands for the shuffle are the same vector, the mask
9695     // will contain only elements from the first one and the second one will be
9696     // undef.
9697     if (V2.isUndef()) {
9698       ShiftElts = 0;
9699       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9700       TargetOrder = OriginalOrderLow;
9701       Swap = false;
9702       // Skip if not the correct element or mask of other elements don't equal
9703       // to our expected order.
9704       if (MaskOneElt == VINSERTHSrcElem &&
9705           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9706         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9707         FoundCandidate = true;
9708         break;
9709       }
9710     } else { // If both operands are defined.
9711       // Target order is [8,15] if the current mask is between [0,7].
9712       TargetOrder =
9713           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9714       // Skip if mask of other elements don't equal our expected order.
9715       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9716         // We only need the last 3 bits for the number of shifts.
9717         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9718                          : BigEndianShifts[MaskOneElt & 0x7];
9719         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9720         Swap = MaskOneElt < NumHalfWords;
9721         FoundCandidate = true;
9722         break;
9723       }
9724     }
9725   }
9726 
9727   if (!FoundCandidate)
9728     return SDValue();
9729 
9730   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9731   // optionally with VECSHL if shift is required.
9732   if (Swap)
9733     std::swap(V1, V2);
9734   if (V2.isUndef())
9735     V2 = V1;
9736   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9737   if (ShiftElts) {
9738     // Double ShiftElts because we're left shifting on v16i8 type.
9739     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9740                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9741     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9742     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9743                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9744     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9745   }
9746   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9747   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9748                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9749   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9750 }
9751 
9752 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9753 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9754 /// return the default SDValue.
9755 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9756                                               SelectionDAG &DAG) const {
9757   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9758   // to v16i8. Peek through the bitcasts to get the actual operands.
9759   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9760   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9761 
9762   auto ShuffleMask = SVN->getMask();
9763   SDValue VecShuffle(SVN, 0);
9764   SDLoc DL(SVN);
9765 
9766   // Check that we have a four byte shuffle.
9767   if (!isNByteElemShuffleMask(SVN, 4, 1))
9768     return SDValue();
9769 
9770   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9771   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9772     std::swap(LHS, RHS);
9773     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9774     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9775   }
9776 
9777   // Ensure that the RHS is a vector of constants.
9778   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9779   if (!BVN)
9780     return SDValue();
9781 
9782   // Check if RHS is a splat of 4-bytes (or smaller).
9783   APInt APSplatValue, APSplatUndef;
9784   unsigned SplatBitSize;
9785   bool HasAnyUndefs;
9786   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9787                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9788       SplatBitSize > 32)
9789     return SDValue();
9790 
9791   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9792   // The instruction splats a constant C into two words of the source vector
9793   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9794   // Thus we check that the shuffle mask is the equivalent  of
9795   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9796   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9797   // within each word are consecutive, so we only need to check the first byte.
9798   SDValue Index;
9799   bool IsLE = Subtarget.isLittleEndian();
9800   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9801       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9802        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9803     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9804   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9805            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9806             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9807     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9808   else
9809     return SDValue();
9810 
9811   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9812   // for XXSPLTI32DX.
9813   unsigned SplatVal = APSplatValue.getZExtValue();
9814   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9815     SplatVal |= (SplatVal << SplatBitSize);
9816 
9817   SDValue SplatNode = DAG.getNode(
9818       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9819       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9820   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9821 }
9822 
9823 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9824 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9825 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9826 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9827 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9828   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9829   assert(Op.getValueType() == MVT::v1i128 &&
9830          "Only set v1i128 as custom, other type shouldn't reach here!");
9831   SDLoc dl(Op);
9832   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9833   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9834   unsigned SHLAmt = N1.getConstantOperandVal(0);
9835   if (SHLAmt % 8 == 0) {
9836     std::array<int, 16> Mask;
9837     std::iota(Mask.begin(), Mask.end(), 0);
9838     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9839     if (SDValue Shuffle =
9840             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9841                                  DAG.getUNDEF(MVT::v16i8), Mask))
9842       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9843   }
9844   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9845   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9846                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9847   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9848                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9849   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9850   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9851 }
9852 
9853 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9854 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9855 /// return the code it can be lowered into.  Worst case, it can always be
9856 /// lowered into a vperm.
9857 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9858                                                SelectionDAG &DAG) const {
9859   SDLoc dl(Op);
9860   SDValue V1 = Op.getOperand(0);
9861   SDValue V2 = Op.getOperand(1);
9862   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9863 
9864   // Any nodes that were combined in the target-independent combiner prior
9865   // to vector legalization will not be sent to the target combine. Try to
9866   // combine it here.
9867   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9868     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9869       return NewShuffle;
9870     Op = NewShuffle;
9871     SVOp = cast<ShuffleVectorSDNode>(Op);
9872     V1 = Op.getOperand(0);
9873     V2 = Op.getOperand(1);
9874   }
9875   EVT VT = Op.getValueType();
9876   bool isLittleEndian = Subtarget.isLittleEndian();
9877 
9878   unsigned ShiftElts, InsertAtByte;
9879   bool Swap = false;
9880 
9881   // If this is a load-and-splat, we can do that with a single instruction
9882   // in some cases. However if the load has multiple uses, we don't want to
9883   // combine it because that will just produce multiple loads.
9884   bool IsPermutedLoad = false;
9885   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9886   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9887       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9888       InputLoad->hasOneUse()) {
9889     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9890     int SplatIdx =
9891       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9892 
9893     // The splat index for permuted loads will be in the left half of the vector
9894     // which is strictly wider than the loaded value by 8 bytes. So we need to
9895     // adjust the splat index to point to the correct address in memory.
9896     if (IsPermutedLoad) {
9897       assert((isLittleEndian || IsFourByte) &&
9898              "Unexpected size for permuted load on big endian target");
9899       SplatIdx += IsFourByte ? 2 : 1;
9900       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9901              "Splat of a value outside of the loaded memory");
9902     }
9903 
9904     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9905     // For 4-byte load-and-splat, we need Power9.
9906     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9907       uint64_t Offset = 0;
9908       if (IsFourByte)
9909         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9910       else
9911         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9912 
9913       // If the width of the load is the same as the width of the splat,
9914       // loading with an offset would load the wrong memory.
9915       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9916         Offset = 0;
9917 
9918       SDValue BasePtr = LD->getBasePtr();
9919       if (Offset != 0)
9920         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9921                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9922       SDValue Ops[] = {
9923         LD->getChain(),    // Chain
9924         BasePtr,           // BasePtr
9925         DAG.getValueType(Op.getValueType()) // VT
9926       };
9927       SDVTList VTL =
9928         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9929       SDValue LdSplt =
9930         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9931                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9932       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9933       if (LdSplt.getValueType() != SVOp->getValueType(0))
9934         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9935       return LdSplt;
9936     }
9937   }
9938   if (Subtarget.hasP9Vector() &&
9939       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9940                            isLittleEndian)) {
9941     if (Swap)
9942       std::swap(V1, V2);
9943     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9944     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9945     if (ShiftElts) {
9946       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9947                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9948       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9949                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9950       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9951     }
9952     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9953                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9954     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9955   }
9956 
9957   if (Subtarget.hasPrefixInstrs()) {
9958     SDValue SplatInsertNode;
9959     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9960       return SplatInsertNode;
9961   }
9962 
9963   if (Subtarget.hasP9Altivec()) {
9964     SDValue NewISDNode;
9965     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9966       return NewISDNode;
9967 
9968     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9969       return NewISDNode;
9970   }
9971 
9972   if (Subtarget.hasVSX() &&
9973       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9974     if (Swap)
9975       std::swap(V1, V2);
9976     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9977     SDValue Conv2 =
9978         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9979 
9980     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9981                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9982     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9983   }
9984 
9985   if (Subtarget.hasVSX() &&
9986     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9987     if (Swap)
9988       std::swap(V1, V2);
9989     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9990     SDValue Conv2 =
9991         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9992 
9993     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9994                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9995     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9996   }
9997 
9998   if (Subtarget.hasP9Vector()) {
9999      if (PPC::isXXBRHShuffleMask(SVOp)) {
10000       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10001       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10002       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10003     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10004       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10005       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10006       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10007     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10008       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10009       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10010       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10011     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10012       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10013       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10014       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10015     }
10016   }
10017 
10018   if (Subtarget.hasVSX()) {
10019     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10020       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10021 
10022       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10023       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10024                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10025       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10026     }
10027 
10028     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10029     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10030       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10031       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10032       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10033     }
10034   }
10035 
10036   // Cases that are handled by instructions that take permute immediates
10037   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10038   // selected by the instruction selector.
10039   if (V2.isUndef()) {
10040     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10041         PPC::isSplatShuffleMask(SVOp, 2) ||
10042         PPC::isSplatShuffleMask(SVOp, 4) ||
10043         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10044         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10045         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10046         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10047         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10048         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10049         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10050         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10051         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10052         (Subtarget.hasP8Altivec() && (
10053          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10054          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10055          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10056       return Op;
10057     }
10058   }
10059 
10060   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10061   // and produce a fixed permutation.  If any of these match, do not lower to
10062   // VPERM.
10063   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10064   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10065       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10066       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10067       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10068       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10069       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10070       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10071       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10072       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10073       (Subtarget.hasP8Altivec() && (
10074        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10075        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10076        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10077     return Op;
10078 
10079   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10080   // perfect shuffle table to emit an optimal matching sequence.
10081   ArrayRef<int> PermMask = SVOp->getMask();
10082 
10083   if (!DisablePerfectShuffle && !isLittleEndian) {
10084     unsigned PFIndexes[4];
10085     bool isFourElementShuffle = true;
10086     for (unsigned i = 0; i != 4 && isFourElementShuffle;
10087          ++i) {                           // Element number
10088       unsigned EltNo = 8;                 // Start out undef.
10089       for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10090         if (PermMask[i * 4 + j] < 0)
10091           continue; // Undef, ignore it.
10092 
10093         unsigned ByteSource = PermMask[i * 4 + j];
10094         if ((ByteSource & 3) != j) {
10095           isFourElementShuffle = false;
10096           break;
10097         }
10098 
10099         if (EltNo == 8) {
10100           EltNo = ByteSource / 4;
10101         } else if (EltNo != ByteSource / 4) {
10102           isFourElementShuffle = false;
10103           break;
10104         }
10105       }
10106       PFIndexes[i] = EltNo;
10107     }
10108 
10109     // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10110     // perfect shuffle vector to determine if it is cost effective to do this as
10111     // discrete instructions, or whether we should use a vperm.
10112     // For now, we skip this for little endian until such time as we have a
10113     // little-endian perfect shuffle table.
10114     if (isFourElementShuffle) {
10115       // Compute the index in the perfect shuffle table.
10116       unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10117                               PFIndexes[2] * 9 + PFIndexes[3];
10118 
10119       unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10120       unsigned Cost = (PFEntry >> 30);
10121 
10122       // Determining when to avoid vperm is tricky.  Many things affect the cost
10123       // of vperm, particularly how many times the perm mask needs to be
10124       // computed. For example, if the perm mask can be hoisted out of a loop or
10125       // is already used (perhaps because there are multiple permutes with the
10126       // same shuffle mask?) the vperm has a cost of 1.  OTOH, hoisting the
10127       // permute mask out of the loop requires an extra register.
10128       //
10129       // As a compromise, we only emit discrete instructions if the shuffle can
10130       // be generated in 3 or fewer operations.  When we have loop information
10131       // available, if this block is within a loop, we should avoid using vperm
10132       // for 3-operation perms and use a constant pool load instead.
10133       if (Cost < 3)
10134         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10135     }
10136   }
10137 
10138   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10139   // vector that will get spilled to the constant pool.
10140   if (V2.isUndef()) V2 = V1;
10141 
10142   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10143   // that it is in input element units, not in bytes.  Convert now.
10144 
10145   // For little endian, the order of the input vectors is reversed, and
10146   // the permutation mask is complemented with respect to 31.  This is
10147   // necessary to produce proper semantics with the big-endian-biased vperm
10148   // instruction.
10149   EVT EltVT = V1.getValueType().getVectorElementType();
10150   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10151 
10152   SmallVector<SDValue, 16> ResultMask;
10153   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10154     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10155 
10156     for (unsigned j = 0; j != BytesPerElement; ++j)
10157       if (isLittleEndian)
10158         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10159                                              dl, MVT::i32));
10160       else
10161         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10162                                              MVT::i32));
10163   }
10164 
10165   ShufflesHandledWithVPERM++;
10166   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10167   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10168   LLVM_DEBUG(SVOp->dump());
10169   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10170   LLVM_DEBUG(VPermMask.dump());
10171 
10172   if (isLittleEndian)
10173     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10174                        V2, V1, VPermMask);
10175   else
10176     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10177                        V1, V2, VPermMask);
10178 }
10179 
10180 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10181 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10182 /// information about the intrinsic.
10183 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10184                                  bool &isDot, const PPCSubtarget &Subtarget) {
10185   unsigned IntrinsicID =
10186       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10187   CompareOpc = -1;
10188   isDot = false;
10189   switch (IntrinsicID) {
10190   default:
10191     return false;
10192   // Comparison predicates.
10193   case Intrinsic::ppc_altivec_vcmpbfp_p:
10194     CompareOpc = 966;
10195     isDot = true;
10196     break;
10197   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10198     CompareOpc = 198;
10199     isDot = true;
10200     break;
10201   case Intrinsic::ppc_altivec_vcmpequb_p:
10202     CompareOpc = 6;
10203     isDot = true;
10204     break;
10205   case Intrinsic::ppc_altivec_vcmpequh_p:
10206     CompareOpc = 70;
10207     isDot = true;
10208     break;
10209   case Intrinsic::ppc_altivec_vcmpequw_p:
10210     CompareOpc = 134;
10211     isDot = true;
10212     break;
10213   case Intrinsic::ppc_altivec_vcmpequd_p:
10214     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10215       CompareOpc = 199;
10216       isDot = true;
10217     } else
10218       return false;
10219     break;
10220   case Intrinsic::ppc_altivec_vcmpneb_p:
10221   case Intrinsic::ppc_altivec_vcmpneh_p:
10222   case Intrinsic::ppc_altivec_vcmpnew_p:
10223   case Intrinsic::ppc_altivec_vcmpnezb_p:
10224   case Intrinsic::ppc_altivec_vcmpnezh_p:
10225   case Intrinsic::ppc_altivec_vcmpnezw_p:
10226     if (Subtarget.hasP9Altivec()) {
10227       switch (IntrinsicID) {
10228       default:
10229         llvm_unreachable("Unknown comparison intrinsic.");
10230       case Intrinsic::ppc_altivec_vcmpneb_p:
10231         CompareOpc = 7;
10232         break;
10233       case Intrinsic::ppc_altivec_vcmpneh_p:
10234         CompareOpc = 71;
10235         break;
10236       case Intrinsic::ppc_altivec_vcmpnew_p:
10237         CompareOpc = 135;
10238         break;
10239       case Intrinsic::ppc_altivec_vcmpnezb_p:
10240         CompareOpc = 263;
10241         break;
10242       case Intrinsic::ppc_altivec_vcmpnezh_p:
10243         CompareOpc = 327;
10244         break;
10245       case Intrinsic::ppc_altivec_vcmpnezw_p:
10246         CompareOpc = 391;
10247         break;
10248       }
10249       isDot = true;
10250     } else
10251       return false;
10252     break;
10253   case Intrinsic::ppc_altivec_vcmpgefp_p:
10254     CompareOpc = 454;
10255     isDot = true;
10256     break;
10257   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10258     CompareOpc = 710;
10259     isDot = true;
10260     break;
10261   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10262     CompareOpc = 774;
10263     isDot = true;
10264     break;
10265   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10266     CompareOpc = 838;
10267     isDot = true;
10268     break;
10269   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10270     CompareOpc = 902;
10271     isDot = true;
10272     break;
10273   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10274     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10275       CompareOpc = 967;
10276       isDot = true;
10277     } else
10278       return false;
10279     break;
10280   case Intrinsic::ppc_altivec_vcmpgtub_p:
10281     CompareOpc = 518;
10282     isDot = true;
10283     break;
10284   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10285     CompareOpc = 582;
10286     isDot = true;
10287     break;
10288   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10289     CompareOpc = 646;
10290     isDot = true;
10291     break;
10292   case Intrinsic::ppc_altivec_vcmpgtud_p:
10293     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10294       CompareOpc = 711;
10295       isDot = true;
10296     } else
10297       return false;
10298     break;
10299 
10300   case Intrinsic::ppc_altivec_vcmpequq:
10301   case Intrinsic::ppc_altivec_vcmpgtsq:
10302   case Intrinsic::ppc_altivec_vcmpgtuq:
10303     if (!Subtarget.isISA3_1())
10304       return false;
10305     switch (IntrinsicID) {
10306     default:
10307       llvm_unreachable("Unknown comparison intrinsic.");
10308     case Intrinsic::ppc_altivec_vcmpequq:
10309       CompareOpc = 455;
10310       break;
10311     case Intrinsic::ppc_altivec_vcmpgtsq:
10312       CompareOpc = 903;
10313       break;
10314     case Intrinsic::ppc_altivec_vcmpgtuq:
10315       CompareOpc = 647;
10316       break;
10317     }
10318     break;
10319 
10320   // VSX predicate comparisons use the same infrastructure
10321   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10322   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10323   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10324   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10325   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10326   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10327     if (Subtarget.hasVSX()) {
10328       switch (IntrinsicID) {
10329       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10330         CompareOpc = 99;
10331         break;
10332       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10333         CompareOpc = 115;
10334         break;
10335       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10336         CompareOpc = 107;
10337         break;
10338       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10339         CompareOpc = 67;
10340         break;
10341       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10342         CompareOpc = 83;
10343         break;
10344       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10345         CompareOpc = 75;
10346         break;
10347       }
10348       isDot = true;
10349     } else
10350       return false;
10351     break;
10352 
10353   // Normal Comparisons.
10354   case Intrinsic::ppc_altivec_vcmpbfp:
10355     CompareOpc = 966;
10356     break;
10357   case Intrinsic::ppc_altivec_vcmpeqfp:
10358     CompareOpc = 198;
10359     break;
10360   case Intrinsic::ppc_altivec_vcmpequb:
10361     CompareOpc = 6;
10362     break;
10363   case Intrinsic::ppc_altivec_vcmpequh:
10364     CompareOpc = 70;
10365     break;
10366   case Intrinsic::ppc_altivec_vcmpequw:
10367     CompareOpc = 134;
10368     break;
10369   case Intrinsic::ppc_altivec_vcmpequd:
10370     if (Subtarget.hasP8Altivec())
10371       CompareOpc = 199;
10372     else
10373       return false;
10374     break;
10375   case Intrinsic::ppc_altivec_vcmpneb:
10376   case Intrinsic::ppc_altivec_vcmpneh:
10377   case Intrinsic::ppc_altivec_vcmpnew:
10378   case Intrinsic::ppc_altivec_vcmpnezb:
10379   case Intrinsic::ppc_altivec_vcmpnezh:
10380   case Intrinsic::ppc_altivec_vcmpnezw:
10381     if (Subtarget.hasP9Altivec())
10382       switch (IntrinsicID) {
10383       default:
10384         llvm_unreachable("Unknown comparison intrinsic.");
10385       case Intrinsic::ppc_altivec_vcmpneb:
10386         CompareOpc = 7;
10387         break;
10388       case Intrinsic::ppc_altivec_vcmpneh:
10389         CompareOpc = 71;
10390         break;
10391       case Intrinsic::ppc_altivec_vcmpnew:
10392         CompareOpc = 135;
10393         break;
10394       case Intrinsic::ppc_altivec_vcmpnezb:
10395         CompareOpc = 263;
10396         break;
10397       case Intrinsic::ppc_altivec_vcmpnezh:
10398         CompareOpc = 327;
10399         break;
10400       case Intrinsic::ppc_altivec_vcmpnezw:
10401         CompareOpc = 391;
10402         break;
10403       }
10404     else
10405       return false;
10406     break;
10407   case Intrinsic::ppc_altivec_vcmpgefp:
10408     CompareOpc = 454;
10409     break;
10410   case Intrinsic::ppc_altivec_vcmpgtfp:
10411     CompareOpc = 710;
10412     break;
10413   case Intrinsic::ppc_altivec_vcmpgtsb:
10414     CompareOpc = 774;
10415     break;
10416   case Intrinsic::ppc_altivec_vcmpgtsh:
10417     CompareOpc = 838;
10418     break;
10419   case Intrinsic::ppc_altivec_vcmpgtsw:
10420     CompareOpc = 902;
10421     break;
10422   case Intrinsic::ppc_altivec_vcmpgtsd:
10423     if (Subtarget.hasP8Altivec())
10424       CompareOpc = 967;
10425     else
10426       return false;
10427     break;
10428   case Intrinsic::ppc_altivec_vcmpgtub:
10429     CompareOpc = 518;
10430     break;
10431   case Intrinsic::ppc_altivec_vcmpgtuh:
10432     CompareOpc = 582;
10433     break;
10434   case Intrinsic::ppc_altivec_vcmpgtuw:
10435     CompareOpc = 646;
10436     break;
10437   case Intrinsic::ppc_altivec_vcmpgtud:
10438     if (Subtarget.hasP8Altivec())
10439       CompareOpc = 711;
10440     else
10441       return false;
10442     break;
10443   case Intrinsic::ppc_altivec_vcmpequq_p:
10444   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10445   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10446     if (!Subtarget.isISA3_1())
10447       return false;
10448     switch (IntrinsicID) {
10449     default:
10450       llvm_unreachable("Unknown comparison intrinsic.");
10451     case Intrinsic::ppc_altivec_vcmpequq_p:
10452       CompareOpc = 455;
10453       break;
10454     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10455       CompareOpc = 903;
10456       break;
10457     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10458       CompareOpc = 647;
10459       break;
10460     }
10461     isDot = true;
10462     break;
10463   }
10464   return true;
10465 }
10466 
10467 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10468 /// lower, do it, otherwise return null.
10469 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10470                                                    SelectionDAG &DAG) const {
10471   unsigned IntrinsicID =
10472     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10473 
10474   SDLoc dl(Op);
10475 
10476   switch (IntrinsicID) {
10477   case Intrinsic::thread_pointer:
10478     // Reads the thread pointer register, used for __builtin_thread_pointer.
10479     if (Subtarget.isPPC64())
10480       return DAG.getRegister(PPC::X13, MVT::i64);
10481     return DAG.getRegister(PPC::R2, MVT::i32);
10482 
10483   case Intrinsic::ppc_mma_disassemble_acc:
10484   case Intrinsic::ppc_vsx_disassemble_pair: {
10485     int NumVecs = 2;
10486     SDValue WideVec = Op.getOperand(1);
10487     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10488       NumVecs = 4;
10489       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10490     }
10491     SmallVector<SDValue, 4> RetOps;
10492     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10493       SDValue Extract = DAG.getNode(
10494           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10495           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10496                                                      : VecNo,
10497                           dl, getPointerTy(DAG.getDataLayout())));
10498       RetOps.push_back(Extract);
10499     }
10500     return DAG.getMergeValues(RetOps, dl);
10501   }
10502 
10503   case Intrinsic::ppc_unpack_longdouble: {
10504     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10505     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10506            "Argument of long double unpack must be 0 or 1!");
10507     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10508                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10509                                        Idx->getValueType(0)));
10510   }
10511 
10512   case Intrinsic::ppc_compare_exp_lt:
10513   case Intrinsic::ppc_compare_exp_gt:
10514   case Intrinsic::ppc_compare_exp_eq:
10515   case Intrinsic::ppc_compare_exp_uo: {
10516     unsigned Pred;
10517     switch (IntrinsicID) {
10518     case Intrinsic::ppc_compare_exp_lt:
10519       Pred = PPC::PRED_LT;
10520       break;
10521     case Intrinsic::ppc_compare_exp_gt:
10522       Pred = PPC::PRED_GT;
10523       break;
10524     case Intrinsic::ppc_compare_exp_eq:
10525       Pred = PPC::PRED_EQ;
10526       break;
10527     case Intrinsic::ppc_compare_exp_uo:
10528       Pred = PPC::PRED_UN;
10529       break;
10530     }
10531     return SDValue(
10532         DAG.getMachineNode(
10533             PPC::SELECT_CC_I4, dl, MVT::i32,
10534             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10535                                         Op.getOperand(1), Op.getOperand(2)),
10536                      0),
10537              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10538              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10539         0);
10540   }
10541   case Intrinsic::ppc_test_data_class_d:
10542   case Intrinsic::ppc_test_data_class_f: {
10543     unsigned CmprOpc = PPC::XSTSTDCDP;
10544     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10545       CmprOpc = PPC::XSTSTDCSP;
10546     return SDValue(
10547         DAG.getMachineNode(
10548             PPC::SELECT_CC_I4, dl, MVT::i32,
10549             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10550                                         Op.getOperand(1)),
10551                      0),
10552              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10553              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10554         0);
10555   }
10556   case Intrinsic::ppc_fnmsub: {
10557     EVT VT = Op.getOperand(1).getValueType();
10558     if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
10559       return DAG.getNode(
10560           ISD::FNEG, dl, VT,
10561           DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
10562                       DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
10563     return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
10564                        Op.getOperand(2), Op.getOperand(3));
10565   }
10566   case Intrinsic::ppc_convert_f128_to_ppcf128:
10567   case Intrinsic::ppc_convert_ppcf128_to_f128: {
10568     RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10569                             ? RTLIB::CONVERT_PPCF128_F128
10570                             : RTLIB::CONVERT_F128_PPCF128;
10571     MakeLibCallOptions CallOptions;
10572     std::pair<SDValue, SDValue> Result =
10573         makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10574                     dl, SDValue());
10575     return Result.first;
10576   }
10577   }
10578 
10579   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10580   // opcode number of the comparison.
10581   int CompareOpc;
10582   bool isDot;
10583   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10584     return SDValue();    // Don't custom lower most intrinsics.
10585 
10586   // If this is a non-dot comparison, make the VCMP node and we are done.
10587   if (!isDot) {
10588     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10589                               Op.getOperand(1), Op.getOperand(2),
10590                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10591     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10592   }
10593 
10594   // Create the PPCISD altivec 'dot' comparison node.
10595   SDValue Ops[] = {
10596     Op.getOperand(2),  // LHS
10597     Op.getOperand(3),  // RHS
10598     DAG.getConstant(CompareOpc, dl, MVT::i32)
10599   };
10600   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10601   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10602 
10603   // Now that we have the comparison, emit a copy from the CR to a GPR.
10604   // This is flagged to the above dot comparison.
10605   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10606                                 DAG.getRegister(PPC::CR6, MVT::i32),
10607                                 CompNode.getValue(1));
10608 
10609   // Unpack the result based on how the target uses it.
10610   unsigned BitNo;   // Bit # of CR6.
10611   bool InvertBit;   // Invert result?
10612   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10613   default:  // Can't happen, don't crash on invalid number though.
10614   case 0:   // Return the value of the EQ bit of CR6.
10615     BitNo = 0; InvertBit = false;
10616     break;
10617   case 1:   // Return the inverted value of the EQ bit of CR6.
10618     BitNo = 0; InvertBit = true;
10619     break;
10620   case 2:   // Return the value of the LT bit of CR6.
10621     BitNo = 2; InvertBit = false;
10622     break;
10623   case 3:   // Return the inverted value of the LT bit of CR6.
10624     BitNo = 2; InvertBit = true;
10625     break;
10626   }
10627 
10628   // Shift the bit into the low position.
10629   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10630                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10631   // Isolate the bit.
10632   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10633                       DAG.getConstant(1, dl, MVT::i32));
10634 
10635   // If we are supposed to, toggle the bit.
10636   if (InvertBit)
10637     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10638                         DAG.getConstant(1, dl, MVT::i32));
10639   return Flags;
10640 }
10641 
10642 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10643                                                SelectionDAG &DAG) const {
10644   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10645   // the beginning of the argument list.
10646   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10647   SDLoc DL(Op);
10648   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10649   case Intrinsic::ppc_cfence: {
10650     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10651     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10652     SDValue Val = Op.getOperand(ArgStart + 1);
10653     EVT Ty = Val.getValueType();
10654     if (Ty == MVT::i128) {
10655       // FIXME: Testing one of two paired registers is sufficient to guarantee
10656       // ordering?
10657       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10658     }
10659     return SDValue(
10660         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10661                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10662                            Op.getOperand(0)),
10663         0);
10664   }
10665   default:
10666     break;
10667   }
10668   return SDValue();
10669 }
10670 
10671 // Lower scalar BSWAP64 to xxbrd.
10672 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10673   SDLoc dl(Op);
10674   if (!Subtarget.isPPC64())
10675     return Op;
10676   // MTVSRDD
10677   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10678                    Op.getOperand(0));
10679   // XXBRD
10680   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10681   // MFVSRD
10682   int VectorIndex = 0;
10683   if (Subtarget.isLittleEndian())
10684     VectorIndex = 1;
10685   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10686                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10687   return Op;
10688 }
10689 
10690 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10691 // compared to a value that is atomically loaded (atomic loads zero-extend).
10692 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10693                                                 SelectionDAG &DAG) const {
10694   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10695          "Expecting an atomic compare-and-swap here.");
10696   SDLoc dl(Op);
10697   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10698   EVT MemVT = AtomicNode->getMemoryVT();
10699   if (MemVT.getSizeInBits() >= 32)
10700     return Op;
10701 
10702   SDValue CmpOp = Op.getOperand(2);
10703   // If this is already correctly zero-extended, leave it alone.
10704   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10705   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10706     return Op;
10707 
10708   // Clear the high bits of the compare operand.
10709   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10710   SDValue NewCmpOp =
10711     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10712                 DAG.getConstant(MaskVal, dl, MVT::i32));
10713 
10714   // Replace the existing compare operand with the properly zero-extended one.
10715   SmallVector<SDValue, 4> Ops;
10716   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10717     Ops.push_back(AtomicNode->getOperand(i));
10718   Ops[2] = NewCmpOp;
10719   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10720   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10721   auto NodeTy =
10722     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10723   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10724 }
10725 
10726 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10727                                                   SelectionDAG &DAG) const {
10728   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10729   EVT MemVT = N->getMemoryVT();
10730   assert(MemVT.getSimpleVT() == MVT::i128 &&
10731          "Expect quadword atomic operations");
10732   SDLoc dl(N);
10733   unsigned Opc = N->getOpcode();
10734   switch (Opc) {
10735   case ISD::ATOMIC_LOAD: {
10736     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10737     // lowered to ppc instructions by pattern matching instruction selector.
10738     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10739     SmallVector<SDValue, 4> Ops{
10740         N->getOperand(0),
10741         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10742     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10743       Ops.push_back(N->getOperand(I));
10744     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10745                                                 Ops, MemVT, N->getMemOperand());
10746     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10747     SDValue ValHi =
10748         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10749     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10750                         DAG.getConstant(64, dl, MVT::i32));
10751     SDValue Val =
10752         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10753     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10754                        {Val, LoadedVal.getValue(2)});
10755   }
10756   case ISD::ATOMIC_STORE: {
10757     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10758     // lowered to ppc instructions by pattern matching instruction selector.
10759     SDVTList Tys = DAG.getVTList(MVT::Other);
10760     SmallVector<SDValue, 4> Ops{
10761         N->getOperand(0),
10762         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10763     SDValue Val = N->getOperand(2);
10764     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10765     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10766                                 DAG.getConstant(64, dl, MVT::i32));
10767     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10768     Ops.push_back(ValLo);
10769     Ops.push_back(ValHi);
10770     Ops.push_back(N->getOperand(1));
10771     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10772                                    N->getMemOperand());
10773   }
10774   default:
10775     llvm_unreachable("Unexpected atomic opcode");
10776   }
10777 }
10778 
10779 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10780                                                  SelectionDAG &DAG) const {
10781   SDLoc dl(Op);
10782   // Create a stack slot that is 16-byte aligned.
10783   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10784   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10785   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10786   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10787 
10788   // Store the input value into Value#0 of the stack slot.
10789   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10790                                MachinePointerInfo());
10791   // Load it out.
10792   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10793 }
10794 
10795 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10796                                                   SelectionDAG &DAG) const {
10797   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10798          "Should only be called for ISD::INSERT_VECTOR_ELT");
10799 
10800   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10801 
10802   EVT VT = Op.getValueType();
10803   SDLoc dl(Op);
10804   SDValue V1 = Op.getOperand(0);
10805   SDValue V2 = Op.getOperand(1);
10806 
10807   if (VT == MVT::v2f64 && C)
10808     return Op;
10809 
10810   if (Subtarget.hasP9Vector()) {
10811     // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
10812     // because on P10, it allows this specific insert_vector_elt load pattern to
10813     // utilize the refactored load and store infrastructure in order to exploit
10814     // prefixed loads.
10815     // On targets with inexpensive direct moves (Power9 and up), a
10816     // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
10817     // load since a single precision load will involve conversion to double
10818     // precision on the load followed by another conversion to single precision.
10819     if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
10820         (isa<LoadSDNode>(V2))) {
10821       SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
10822       SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
10823       SDValue InsVecElt =
10824           DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
10825                       BitcastLoad, Op.getOperand(2));
10826       return DAG.getBitcast(MVT::v4f32, InsVecElt);
10827     }
10828   }
10829 
10830   if (Subtarget.isISA3_1()) {
10831     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10832       return SDValue();
10833     // On P10, we have legal lowering for constant and variable indices for
10834     // all vectors.
10835     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10836         VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
10837       return Op;
10838   }
10839 
10840   // Before P10, we have legal lowering for constant indices but not for
10841   // variable ones.
10842   if (!C)
10843     return SDValue();
10844 
10845   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10846   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10847     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10848     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10849     unsigned InsertAtElement = C->getZExtValue();
10850     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10851     if (Subtarget.isLittleEndian()) {
10852       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10853     }
10854     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10855                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10856   }
10857   return Op;
10858 }
10859 
10860 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10861                                            SelectionDAG &DAG) const {
10862   SDLoc dl(Op);
10863   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10864   SDValue LoadChain = LN->getChain();
10865   SDValue BasePtr = LN->getBasePtr();
10866   EVT VT = Op.getValueType();
10867 
10868   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10869     return Op;
10870 
10871   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10872   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10873   // 2 or 4 vsx registers.
10874   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10875          "Type unsupported without MMA");
10876   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10877          "Type unsupported without paired vector support");
10878   Align Alignment = LN->getAlign();
10879   SmallVector<SDValue, 4> Loads;
10880   SmallVector<SDValue, 4> LoadChains;
10881   unsigned NumVecs = VT.getSizeInBits() / 128;
10882   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10883     SDValue Load =
10884         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10885                     LN->getPointerInfo().getWithOffset(Idx * 16),
10886                     commonAlignment(Alignment, Idx * 16),
10887                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10888     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10889                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10890     Loads.push_back(Load);
10891     LoadChains.push_back(Load.getValue(1));
10892   }
10893   if (Subtarget.isLittleEndian()) {
10894     std::reverse(Loads.begin(), Loads.end());
10895     std::reverse(LoadChains.begin(), LoadChains.end());
10896   }
10897   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10898   SDValue Value =
10899       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10900                   dl, VT, Loads);
10901   SDValue RetOps[] = {Value, TF};
10902   return DAG.getMergeValues(RetOps, dl);
10903 }
10904 
10905 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10906                                             SelectionDAG &DAG) const {
10907   SDLoc dl(Op);
10908   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10909   SDValue StoreChain = SN->getChain();
10910   SDValue BasePtr = SN->getBasePtr();
10911   SDValue Value = SN->getValue();
10912   EVT StoreVT = Value.getValueType();
10913 
10914   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10915     return Op;
10916 
10917   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10918   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10919   // underlying registers individually.
10920   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10921          "Type unsupported without MMA");
10922   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10923          "Type unsupported without paired vector support");
10924   Align Alignment = SN->getAlign();
10925   SmallVector<SDValue, 4> Stores;
10926   unsigned NumVecs = 2;
10927   if (StoreVT == MVT::v512i1) {
10928     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10929     NumVecs = 4;
10930   }
10931   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10932     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10933     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10934                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10935     SDValue Store =
10936         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10937                      SN->getPointerInfo().getWithOffset(Idx * 16),
10938                      commonAlignment(Alignment, Idx * 16),
10939                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10940     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10941                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10942     Stores.push_back(Store);
10943   }
10944   SDValue TF = DAG.getTokenFactor(dl, Stores);
10945   return TF;
10946 }
10947 
10948 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10949   SDLoc dl(Op);
10950   if (Op.getValueType() == MVT::v4i32) {
10951     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10952 
10953     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10954     // +16 as shift amt.
10955     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10956     SDValue RHSSwap =   // = vrlw RHS, 16
10957       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10958 
10959     // Shrinkify inputs to v8i16.
10960     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10961     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10962     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10963 
10964     // Low parts multiplied together, generating 32-bit results (we ignore the
10965     // top parts).
10966     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10967                                         LHS, RHS, DAG, dl, MVT::v4i32);
10968 
10969     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10970                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10971     // Shift the high parts up 16 bits.
10972     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10973                               Neg16, DAG, dl);
10974     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10975   } else if (Op.getValueType() == MVT::v16i8) {
10976     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10977     bool isLittleEndian = Subtarget.isLittleEndian();
10978 
10979     // Multiply the even 8-bit parts, producing 16-bit sums.
10980     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10981                                            LHS, RHS, DAG, dl, MVT::v8i16);
10982     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10983 
10984     // Multiply the odd 8-bit parts, producing 16-bit sums.
10985     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10986                                           LHS, RHS, DAG, dl, MVT::v8i16);
10987     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10988 
10989     // Merge the results together.  Because vmuleub and vmuloub are
10990     // instructions with a big-endian bias, we must reverse the
10991     // element numbering and reverse the meaning of "odd" and "even"
10992     // when generating little endian code.
10993     int Ops[16];
10994     for (unsigned i = 0; i != 8; ++i) {
10995       if (isLittleEndian) {
10996         Ops[i*2  ] = 2*i;
10997         Ops[i*2+1] = 2*i+16;
10998       } else {
10999         Ops[i*2  ] = 2*i+1;
11000         Ops[i*2+1] = 2*i+1+16;
11001       }
11002     }
11003     if (isLittleEndian)
11004       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
11005     else
11006       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
11007   } else {
11008     llvm_unreachable("Unknown mul to lower!");
11009   }
11010 }
11011 
11012 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11013   bool IsStrict = Op->isStrictFPOpcode();
11014   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
11015       !Subtarget.hasP9Vector())
11016     return SDValue();
11017 
11018   return Op;
11019 }
11020 
11021 // Custom lowering for fpext vf32 to v2f64
11022 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11023 
11024   assert(Op.getOpcode() == ISD::FP_EXTEND &&
11025          "Should only be called for ISD::FP_EXTEND");
11026 
11027   // FIXME: handle extends from half precision float vectors on P9.
11028   // We only want to custom lower an extend from v2f32 to v2f64.
11029   if (Op.getValueType() != MVT::v2f64 ||
11030       Op.getOperand(0).getValueType() != MVT::v2f32)
11031     return SDValue();
11032 
11033   SDLoc dl(Op);
11034   SDValue Op0 = Op.getOperand(0);
11035 
11036   switch (Op0.getOpcode()) {
11037   default:
11038     return SDValue();
11039   case ISD::EXTRACT_SUBVECTOR: {
11040     assert(Op0.getNumOperands() == 2 &&
11041            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11042            "Node should have 2 operands with second one being a constant!");
11043 
11044     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11045       return SDValue();
11046 
11047     // Custom lower is only done for high or low doubleword.
11048     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11049     if (Idx % 2 != 0)
11050       return SDValue();
11051 
11052     // Since input is v4f32, at this point Idx is either 0 or 2.
11053     // Shift to get the doubleword position we want.
11054     int DWord = Idx >> 1;
11055 
11056     // High and low word positions are different on little endian.
11057     if (Subtarget.isLittleEndian())
11058       DWord ^= 0x1;
11059 
11060     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11061                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11062   }
11063   case ISD::FADD:
11064   case ISD::FMUL:
11065   case ISD::FSUB: {
11066     SDValue NewLoad[2];
11067     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11068       // Ensure both input are loads.
11069       SDValue LdOp = Op0.getOperand(i);
11070       if (LdOp.getOpcode() != ISD::LOAD)
11071         return SDValue();
11072       // Generate new load node.
11073       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11074       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11075       NewLoad[i] = DAG.getMemIntrinsicNode(
11076           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11077           LD->getMemoryVT(), LD->getMemOperand());
11078     }
11079     SDValue NewOp =
11080         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11081                     NewLoad[1], Op0.getNode()->getFlags());
11082     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11083                        DAG.getConstant(0, dl, MVT::i32));
11084   }
11085   case ISD::LOAD: {
11086     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11087     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11088     SDValue NewLd = DAG.getMemIntrinsicNode(
11089         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11090         LD->getMemoryVT(), LD->getMemOperand());
11091     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11092                        DAG.getConstant(0, dl, MVT::i32));
11093   }
11094   }
11095   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11096 }
11097 
11098 /// LowerOperation - Provide custom lowering hooks for some operations.
11099 ///
11100 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11101   switch (Op.getOpcode()) {
11102   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11103   case ISD::FPOW:               return lowerPow(Op, DAG);
11104   case ISD::FSIN:               return lowerSin(Op, DAG);
11105   case ISD::FCOS:               return lowerCos(Op, DAG);
11106   case ISD::FLOG:               return lowerLog(Op, DAG);
11107   case ISD::FLOG10:             return lowerLog10(Op, DAG);
11108   case ISD::FEXP:               return lowerExp(Op, DAG);
11109   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11110   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11111   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11112   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11113   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11114   case ISD::STRICT_FSETCC:
11115   case ISD::STRICT_FSETCCS:
11116   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11117   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11118   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11119 
11120   case ISD::INLINEASM:
11121   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11122   // Variable argument lowering.
11123   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11124   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11125   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11126 
11127   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11128   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11129   case ISD::GET_DYNAMIC_AREA_OFFSET:
11130     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11131 
11132   // Exception handling lowering.
11133   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11134   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11135   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11136 
11137   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11138   case ISD::STORE:              return LowerSTORE(Op, DAG);
11139   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11140   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11141   case ISD::STRICT_FP_TO_UINT:
11142   case ISD::STRICT_FP_TO_SINT:
11143   case ISD::FP_TO_UINT:
11144   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11145   case ISD::STRICT_UINT_TO_FP:
11146   case ISD::STRICT_SINT_TO_FP:
11147   case ISD::UINT_TO_FP:
11148   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11149   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11150 
11151   // Lower 64-bit shifts.
11152   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11153   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11154   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11155 
11156   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11157   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11158 
11159   // Vector-related lowering.
11160   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11161   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11162   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11163   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11164   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11165   case ISD::MUL:                return LowerMUL(Op, DAG);
11166   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11167   case ISD::STRICT_FP_ROUND:
11168   case ISD::FP_ROUND:
11169     return LowerFP_ROUND(Op, DAG);
11170   case ISD::ROTL:               return LowerROTL(Op, DAG);
11171 
11172   // For counter-based loop handling.
11173   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11174 
11175   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11176 
11177   // Frame & Return address.
11178   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11179   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11180 
11181   case ISD::INTRINSIC_VOID:
11182     return LowerINTRINSIC_VOID(Op, DAG);
11183   case ISD::BSWAP:
11184     return LowerBSWAP(Op, DAG);
11185   case ISD::ATOMIC_CMP_SWAP:
11186     return LowerATOMIC_CMP_SWAP(Op, DAG);
11187   case ISD::ATOMIC_STORE:
11188     return LowerATOMIC_LOAD_STORE(Op, DAG);
11189   }
11190 }
11191 
11192 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11193                                            SmallVectorImpl<SDValue>&Results,
11194                                            SelectionDAG &DAG) const {
11195   SDLoc dl(N);
11196   switch (N->getOpcode()) {
11197   default:
11198     llvm_unreachable("Do not know how to custom type legalize this operation!");
11199   case ISD::ATOMIC_LOAD: {
11200     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11201     Results.push_back(Res);
11202     Results.push_back(Res.getValue(1));
11203     break;
11204   }
11205   case ISD::READCYCLECOUNTER: {
11206     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11207     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11208 
11209     Results.push_back(
11210         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11211     Results.push_back(RTB.getValue(2));
11212     break;
11213   }
11214   case ISD::INTRINSIC_W_CHAIN: {
11215     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11216         Intrinsic::loop_decrement)
11217       break;
11218 
11219     assert(N->getValueType(0) == MVT::i1 &&
11220            "Unexpected result type for CTR decrement intrinsic");
11221     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11222                                  N->getValueType(0));
11223     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11224     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11225                                  N->getOperand(1));
11226 
11227     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11228     Results.push_back(NewInt.getValue(1));
11229     break;
11230   }
11231   case ISD::INTRINSIC_WO_CHAIN: {
11232     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11233     case Intrinsic::ppc_pack_longdouble:
11234       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11235                                     N->getOperand(2), N->getOperand(1)));
11236       break;
11237     case Intrinsic::ppc_fnmsub:
11238     case Intrinsic::ppc_convert_f128_to_ppcf128:
11239       Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11240       break;
11241     }
11242     break;
11243   }
11244   case ISD::VAARG: {
11245     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11246       return;
11247 
11248     EVT VT = N->getValueType(0);
11249 
11250     if (VT == MVT::i64) {
11251       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11252 
11253       Results.push_back(NewNode);
11254       Results.push_back(NewNode.getValue(1));
11255     }
11256     return;
11257   }
11258   case ISD::STRICT_FP_TO_SINT:
11259   case ISD::STRICT_FP_TO_UINT:
11260   case ISD::FP_TO_SINT:
11261   case ISD::FP_TO_UINT: {
11262     // LowerFP_TO_INT() can only handle f32 and f64.
11263     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11264         MVT::ppcf128)
11265       return;
11266     SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11267     Results.push_back(LoweredValue);
11268     if (N->isStrictFPOpcode())
11269       Results.push_back(LoweredValue.getValue(1));
11270     return;
11271   }
11272   case ISD::TRUNCATE: {
11273     if (!N->getValueType(0).isVector())
11274       return;
11275     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11276     if (Lowered)
11277       Results.push_back(Lowered);
11278     return;
11279   }
11280   case ISD::FSHL:
11281   case ISD::FSHR:
11282     // Don't handle funnel shifts here.
11283     return;
11284   case ISD::BITCAST:
11285     // Don't handle bitcast here.
11286     return;
11287   case ISD::FP_EXTEND:
11288     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11289     if (Lowered)
11290       Results.push_back(Lowered);
11291     return;
11292   }
11293 }
11294 
11295 //===----------------------------------------------------------------------===//
11296 //  Other Lowering Code
11297 //===----------------------------------------------------------------------===//
11298 
11299 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11300   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11301   Function *Func = Intrinsic::getDeclaration(M, Id);
11302   return Builder.CreateCall(Func, {});
11303 }
11304 
11305 // The mappings for emitLeading/TrailingFence is taken from
11306 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11307 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11308                                                  Instruction *Inst,
11309                                                  AtomicOrdering Ord) const {
11310   if (Ord == AtomicOrdering::SequentiallyConsistent)
11311     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11312   if (isReleaseOrStronger(Ord))
11313     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11314   return nullptr;
11315 }
11316 
11317 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11318                                                   Instruction *Inst,
11319                                                   AtomicOrdering Ord) const {
11320   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11321     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11322     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11323     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11324     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11325       return Builder.CreateCall(
11326           Intrinsic::getDeclaration(
11327               Builder.GetInsertBlock()->getParent()->getParent(),
11328               Intrinsic::ppc_cfence, {Inst->getType()}),
11329           {Inst});
11330     // FIXME: Can use isync for rmw operation.
11331     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11332   }
11333   return nullptr;
11334 }
11335 
11336 MachineBasicBlock *
11337 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11338                                     unsigned AtomicSize,
11339                                     unsigned BinOpcode,
11340                                     unsigned CmpOpcode,
11341                                     unsigned CmpPred) const {
11342   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11343   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11344 
11345   auto LoadMnemonic = PPC::LDARX;
11346   auto StoreMnemonic = PPC::STDCX;
11347   switch (AtomicSize) {
11348   default:
11349     llvm_unreachable("Unexpected size of atomic entity");
11350   case 1:
11351     LoadMnemonic = PPC::LBARX;
11352     StoreMnemonic = PPC::STBCX;
11353     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11354     break;
11355   case 2:
11356     LoadMnemonic = PPC::LHARX;
11357     StoreMnemonic = PPC::STHCX;
11358     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11359     break;
11360   case 4:
11361     LoadMnemonic = PPC::LWARX;
11362     StoreMnemonic = PPC::STWCX;
11363     break;
11364   case 8:
11365     LoadMnemonic = PPC::LDARX;
11366     StoreMnemonic = PPC::STDCX;
11367     break;
11368   }
11369 
11370   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11371   MachineFunction *F = BB->getParent();
11372   MachineFunction::iterator It = ++BB->getIterator();
11373 
11374   Register dest = MI.getOperand(0).getReg();
11375   Register ptrA = MI.getOperand(1).getReg();
11376   Register ptrB = MI.getOperand(2).getReg();
11377   Register incr = MI.getOperand(3).getReg();
11378   DebugLoc dl = MI.getDebugLoc();
11379 
11380   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11381   MachineBasicBlock *loop2MBB =
11382     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11383   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11384   F->insert(It, loopMBB);
11385   if (CmpOpcode)
11386     F->insert(It, loop2MBB);
11387   F->insert(It, exitMBB);
11388   exitMBB->splice(exitMBB->begin(), BB,
11389                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11390   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11391 
11392   MachineRegisterInfo &RegInfo = F->getRegInfo();
11393   Register TmpReg = (!BinOpcode) ? incr :
11394     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11395                                            : &PPC::GPRCRegClass);
11396 
11397   //  thisMBB:
11398   //   ...
11399   //   fallthrough --> loopMBB
11400   BB->addSuccessor(loopMBB);
11401 
11402   //  loopMBB:
11403   //   l[wd]arx dest, ptr
11404   //   add r0, dest, incr
11405   //   st[wd]cx. r0, ptr
11406   //   bne- loopMBB
11407   //   fallthrough --> exitMBB
11408 
11409   // For max/min...
11410   //  loopMBB:
11411   //   l[wd]arx dest, ptr
11412   //   cmpl?[wd] incr, dest
11413   //   bgt exitMBB
11414   //  loop2MBB:
11415   //   st[wd]cx. dest, ptr
11416   //   bne- loopMBB
11417   //   fallthrough --> exitMBB
11418 
11419   BB = loopMBB;
11420   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11421     .addReg(ptrA).addReg(ptrB);
11422   if (BinOpcode)
11423     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11424   if (CmpOpcode) {
11425     // Signed comparisons of byte or halfword values must be sign-extended.
11426     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11427       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11428       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11429               ExtReg).addReg(dest);
11430       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11431         .addReg(incr).addReg(ExtReg);
11432     } else
11433       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11434         .addReg(incr).addReg(dest);
11435 
11436     BuildMI(BB, dl, TII->get(PPC::BCC))
11437       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11438     BB->addSuccessor(loop2MBB);
11439     BB->addSuccessor(exitMBB);
11440     BB = loop2MBB;
11441   }
11442   BuildMI(BB, dl, TII->get(StoreMnemonic))
11443     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11444   BuildMI(BB, dl, TII->get(PPC::BCC))
11445     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11446   BB->addSuccessor(loopMBB);
11447   BB->addSuccessor(exitMBB);
11448 
11449   //  exitMBB:
11450   //   ...
11451   BB = exitMBB;
11452   return BB;
11453 }
11454 
11455 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11456   switch(MI.getOpcode()) {
11457   default:
11458     return false;
11459   case PPC::COPY:
11460     return TII->isSignExtended(MI);
11461   case PPC::LHA:
11462   case PPC::LHA8:
11463   case PPC::LHAU:
11464   case PPC::LHAU8:
11465   case PPC::LHAUX:
11466   case PPC::LHAUX8:
11467   case PPC::LHAX:
11468   case PPC::LHAX8:
11469   case PPC::LWA:
11470   case PPC::LWAUX:
11471   case PPC::LWAX:
11472   case PPC::LWAX_32:
11473   case PPC::LWA_32:
11474   case PPC::PLHA:
11475   case PPC::PLHA8:
11476   case PPC::PLHA8pc:
11477   case PPC::PLHApc:
11478   case PPC::PLWA:
11479   case PPC::PLWA8:
11480   case PPC::PLWA8pc:
11481   case PPC::PLWApc:
11482   case PPC::EXTSB:
11483   case PPC::EXTSB8:
11484   case PPC::EXTSB8_32_64:
11485   case PPC::EXTSB8_rec:
11486   case PPC::EXTSB_rec:
11487   case PPC::EXTSH:
11488   case PPC::EXTSH8:
11489   case PPC::EXTSH8_32_64:
11490   case PPC::EXTSH8_rec:
11491   case PPC::EXTSH_rec:
11492   case PPC::EXTSW:
11493   case PPC::EXTSWSLI:
11494   case PPC::EXTSWSLI_32_64:
11495   case PPC::EXTSWSLI_32_64_rec:
11496   case PPC::EXTSWSLI_rec:
11497   case PPC::EXTSW_32:
11498   case PPC::EXTSW_32_64:
11499   case PPC::EXTSW_32_64_rec:
11500   case PPC::EXTSW_rec:
11501   case PPC::SRAW:
11502   case PPC::SRAWI:
11503   case PPC::SRAWI_rec:
11504   case PPC::SRAW_rec:
11505     return true;
11506   }
11507   return false;
11508 }
11509 
11510 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11511     MachineInstr &MI, MachineBasicBlock *BB,
11512     bool is8bit, // operation
11513     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11514   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11515   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11516 
11517   // If this is a signed comparison and the value being compared is not known
11518   // to be sign extended, sign extend it here.
11519   DebugLoc dl = MI.getDebugLoc();
11520   MachineFunction *F = BB->getParent();
11521   MachineRegisterInfo &RegInfo = F->getRegInfo();
11522   Register incr = MI.getOperand(3).getReg();
11523   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11524     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11525 
11526   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11527     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11528     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11529         .addReg(MI.getOperand(3).getReg());
11530     MI.getOperand(3).setReg(ValueReg);
11531   }
11532   // If we support part-word atomic mnemonics, just use them
11533   if (Subtarget.hasPartwordAtomics())
11534     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11535                             CmpPred);
11536 
11537   // In 64 bit mode we have to use 64 bits for addresses, even though the
11538   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11539   // registers without caring whether they're 32 or 64, but here we're
11540   // doing actual arithmetic on the addresses.
11541   bool is64bit = Subtarget.isPPC64();
11542   bool isLittleEndian = Subtarget.isLittleEndian();
11543   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11544 
11545   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11546   MachineFunction::iterator It = ++BB->getIterator();
11547 
11548   Register dest = MI.getOperand(0).getReg();
11549   Register ptrA = MI.getOperand(1).getReg();
11550   Register ptrB = MI.getOperand(2).getReg();
11551 
11552   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11553   MachineBasicBlock *loop2MBB =
11554       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11555   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11556   F->insert(It, loopMBB);
11557   if (CmpOpcode)
11558     F->insert(It, loop2MBB);
11559   F->insert(It, exitMBB);
11560   exitMBB->splice(exitMBB->begin(), BB,
11561                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11562   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11563 
11564   const TargetRegisterClass *RC =
11565       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11566   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11567 
11568   Register PtrReg = RegInfo.createVirtualRegister(RC);
11569   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11570   Register ShiftReg =
11571       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11572   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11573   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11574   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11575   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11576   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11577   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11578   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11579   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11580   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11581   Register Ptr1Reg;
11582   Register TmpReg =
11583       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11584 
11585   //  thisMBB:
11586   //   ...
11587   //   fallthrough --> loopMBB
11588   BB->addSuccessor(loopMBB);
11589 
11590   // The 4-byte load must be aligned, while a char or short may be
11591   // anywhere in the word.  Hence all this nasty bookkeeping code.
11592   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11593   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11594   //   xori shift, shift1, 24 [16]
11595   //   rlwinm ptr, ptr1, 0, 0, 29
11596   //   slw incr2, incr, shift
11597   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11598   //   slw mask, mask2, shift
11599   //  loopMBB:
11600   //   lwarx tmpDest, ptr
11601   //   add tmp, tmpDest, incr2
11602   //   andc tmp2, tmpDest, mask
11603   //   and tmp3, tmp, mask
11604   //   or tmp4, tmp3, tmp2
11605   //   stwcx. tmp4, ptr
11606   //   bne- loopMBB
11607   //   fallthrough --> exitMBB
11608   //   srw SrwDest, tmpDest, shift
11609   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11610   if (ptrA != ZeroReg) {
11611     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11612     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11613         .addReg(ptrA)
11614         .addReg(ptrB);
11615   } else {
11616     Ptr1Reg = ptrB;
11617   }
11618   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11619   // mode.
11620   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11621       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11622       .addImm(3)
11623       .addImm(27)
11624       .addImm(is8bit ? 28 : 27);
11625   if (!isLittleEndian)
11626     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11627         .addReg(Shift1Reg)
11628         .addImm(is8bit ? 24 : 16);
11629   if (is64bit)
11630     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11631         .addReg(Ptr1Reg)
11632         .addImm(0)
11633         .addImm(61);
11634   else
11635     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11636         .addReg(Ptr1Reg)
11637         .addImm(0)
11638         .addImm(0)
11639         .addImm(29);
11640   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11641   if (is8bit)
11642     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11643   else {
11644     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11645     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11646         .addReg(Mask3Reg)
11647         .addImm(65535);
11648   }
11649   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11650       .addReg(Mask2Reg)
11651       .addReg(ShiftReg);
11652 
11653   BB = loopMBB;
11654   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11655       .addReg(ZeroReg)
11656       .addReg(PtrReg);
11657   if (BinOpcode)
11658     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11659         .addReg(Incr2Reg)
11660         .addReg(TmpDestReg);
11661   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11662       .addReg(TmpDestReg)
11663       .addReg(MaskReg);
11664   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11665   if (CmpOpcode) {
11666     // For unsigned comparisons, we can directly compare the shifted values.
11667     // For signed comparisons we shift and sign extend.
11668     Register SReg = RegInfo.createVirtualRegister(GPRC);
11669     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11670         .addReg(TmpDestReg)
11671         .addReg(MaskReg);
11672     unsigned ValueReg = SReg;
11673     unsigned CmpReg = Incr2Reg;
11674     if (CmpOpcode == PPC::CMPW) {
11675       ValueReg = RegInfo.createVirtualRegister(GPRC);
11676       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11677           .addReg(SReg)
11678           .addReg(ShiftReg);
11679       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11680       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11681           .addReg(ValueReg);
11682       ValueReg = ValueSReg;
11683       CmpReg = incr;
11684     }
11685     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11686         .addReg(CmpReg)
11687         .addReg(ValueReg);
11688     BuildMI(BB, dl, TII->get(PPC::BCC))
11689         .addImm(CmpPred)
11690         .addReg(PPC::CR0)
11691         .addMBB(exitMBB);
11692     BB->addSuccessor(loop2MBB);
11693     BB->addSuccessor(exitMBB);
11694     BB = loop2MBB;
11695   }
11696   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11697   BuildMI(BB, dl, TII->get(PPC::STWCX))
11698       .addReg(Tmp4Reg)
11699       .addReg(ZeroReg)
11700       .addReg(PtrReg);
11701   BuildMI(BB, dl, TII->get(PPC::BCC))
11702       .addImm(PPC::PRED_NE)
11703       .addReg(PPC::CR0)
11704       .addMBB(loopMBB);
11705   BB->addSuccessor(loopMBB);
11706   BB->addSuccessor(exitMBB);
11707 
11708   //  exitMBB:
11709   //   ...
11710   BB = exitMBB;
11711   // Since the shift amount is not a constant, we need to clear
11712   // the upper bits with a separate RLWINM.
11713   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11714       .addReg(SrwDestReg)
11715       .addImm(0)
11716       .addImm(is8bit ? 24 : 16)
11717       .addImm(31);
11718   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11719       .addReg(TmpDestReg)
11720       .addReg(ShiftReg);
11721   return BB;
11722 }
11723 
11724 llvm::MachineBasicBlock *
11725 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11726                                     MachineBasicBlock *MBB) const {
11727   DebugLoc DL = MI.getDebugLoc();
11728   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11729   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11730 
11731   MachineFunction *MF = MBB->getParent();
11732   MachineRegisterInfo &MRI = MF->getRegInfo();
11733 
11734   const BasicBlock *BB = MBB->getBasicBlock();
11735   MachineFunction::iterator I = ++MBB->getIterator();
11736 
11737   Register DstReg = MI.getOperand(0).getReg();
11738   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11739   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11740   Register mainDstReg = MRI.createVirtualRegister(RC);
11741   Register restoreDstReg = MRI.createVirtualRegister(RC);
11742 
11743   MVT PVT = getPointerTy(MF->getDataLayout());
11744   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11745          "Invalid Pointer Size!");
11746   // For v = setjmp(buf), we generate
11747   //
11748   // thisMBB:
11749   //  SjLjSetup mainMBB
11750   //  bl mainMBB
11751   //  v_restore = 1
11752   //  b sinkMBB
11753   //
11754   // mainMBB:
11755   //  buf[LabelOffset] = LR
11756   //  v_main = 0
11757   //
11758   // sinkMBB:
11759   //  v = phi(main, restore)
11760   //
11761 
11762   MachineBasicBlock *thisMBB = MBB;
11763   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11764   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11765   MF->insert(I, mainMBB);
11766   MF->insert(I, sinkMBB);
11767 
11768   MachineInstrBuilder MIB;
11769 
11770   // Transfer the remainder of BB and its successor edges to sinkMBB.
11771   sinkMBB->splice(sinkMBB->begin(), MBB,
11772                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11773   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11774 
11775   // Note that the structure of the jmp_buf used here is not compatible
11776   // with that used by libc, and is not designed to be. Specifically, it
11777   // stores only those 'reserved' registers that LLVM does not otherwise
11778   // understand how to spill. Also, by convention, by the time this
11779   // intrinsic is called, Clang has already stored the frame address in the
11780   // first slot of the buffer and stack address in the third. Following the
11781   // X86 target code, we'll store the jump address in the second slot. We also
11782   // need to save the TOC pointer (R2) to handle jumps between shared
11783   // libraries, and that will be stored in the fourth slot. The thread
11784   // identifier (R13) is not affected.
11785 
11786   // thisMBB:
11787   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11788   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11789   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11790 
11791   // Prepare IP either in reg.
11792   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11793   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11794   Register BufReg = MI.getOperand(1).getReg();
11795 
11796   if (Subtarget.is64BitELFABI()) {
11797     setUsesTOCBasePtr(*MBB->getParent());
11798     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11799               .addReg(PPC::X2)
11800               .addImm(TOCOffset)
11801               .addReg(BufReg)
11802               .cloneMemRefs(MI);
11803   }
11804 
11805   // Naked functions never have a base pointer, and so we use r1. For all
11806   // other functions, this decision must be delayed until during PEI.
11807   unsigned BaseReg;
11808   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11809     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11810   else
11811     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11812 
11813   MIB = BuildMI(*thisMBB, MI, DL,
11814                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11815             .addReg(BaseReg)
11816             .addImm(BPOffset)
11817             .addReg(BufReg)
11818             .cloneMemRefs(MI);
11819 
11820   // Setup
11821   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11822   MIB.addRegMask(TRI->getNoPreservedMask());
11823 
11824   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11825 
11826   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11827           .addMBB(mainMBB);
11828   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11829 
11830   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11831   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11832 
11833   // mainMBB:
11834   //  mainDstReg = 0
11835   MIB =
11836       BuildMI(mainMBB, DL,
11837               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11838 
11839   // Store IP
11840   if (Subtarget.isPPC64()) {
11841     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11842             .addReg(LabelReg)
11843             .addImm(LabelOffset)
11844             .addReg(BufReg);
11845   } else {
11846     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11847             .addReg(LabelReg)
11848             .addImm(LabelOffset)
11849             .addReg(BufReg);
11850   }
11851   MIB.cloneMemRefs(MI);
11852 
11853   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11854   mainMBB->addSuccessor(sinkMBB);
11855 
11856   // sinkMBB:
11857   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11858           TII->get(PPC::PHI), DstReg)
11859     .addReg(mainDstReg).addMBB(mainMBB)
11860     .addReg(restoreDstReg).addMBB(thisMBB);
11861 
11862   MI.eraseFromParent();
11863   return sinkMBB;
11864 }
11865 
11866 MachineBasicBlock *
11867 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11868                                      MachineBasicBlock *MBB) const {
11869   DebugLoc DL = MI.getDebugLoc();
11870   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11871 
11872   MachineFunction *MF = MBB->getParent();
11873   MachineRegisterInfo &MRI = MF->getRegInfo();
11874 
11875   MVT PVT = getPointerTy(MF->getDataLayout());
11876   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11877          "Invalid Pointer Size!");
11878 
11879   const TargetRegisterClass *RC =
11880     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11881   Register Tmp = MRI.createVirtualRegister(RC);
11882   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11883   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11884   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11885   unsigned BP =
11886       (PVT == MVT::i64)
11887           ? PPC::X30
11888           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11889                                                               : PPC::R30);
11890 
11891   MachineInstrBuilder MIB;
11892 
11893   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11894   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11895   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11896   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11897 
11898   Register BufReg = MI.getOperand(0).getReg();
11899 
11900   // Reload FP (the jumped-to function may not have had a
11901   // frame pointer, and if so, then its r31 will be restored
11902   // as necessary).
11903   if (PVT == MVT::i64) {
11904     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11905             .addImm(0)
11906             .addReg(BufReg);
11907   } else {
11908     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11909             .addImm(0)
11910             .addReg(BufReg);
11911   }
11912   MIB.cloneMemRefs(MI);
11913 
11914   // Reload IP
11915   if (PVT == MVT::i64) {
11916     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11917             .addImm(LabelOffset)
11918             .addReg(BufReg);
11919   } else {
11920     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11921             .addImm(LabelOffset)
11922             .addReg(BufReg);
11923   }
11924   MIB.cloneMemRefs(MI);
11925 
11926   // Reload SP
11927   if (PVT == MVT::i64) {
11928     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11929             .addImm(SPOffset)
11930             .addReg(BufReg);
11931   } else {
11932     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11933             .addImm(SPOffset)
11934             .addReg(BufReg);
11935   }
11936   MIB.cloneMemRefs(MI);
11937 
11938   // Reload BP
11939   if (PVT == MVT::i64) {
11940     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11941             .addImm(BPOffset)
11942             .addReg(BufReg);
11943   } else {
11944     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11945             .addImm(BPOffset)
11946             .addReg(BufReg);
11947   }
11948   MIB.cloneMemRefs(MI);
11949 
11950   // Reload TOC
11951   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11952     setUsesTOCBasePtr(*MBB->getParent());
11953     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11954               .addImm(TOCOffset)
11955               .addReg(BufReg)
11956               .cloneMemRefs(MI);
11957   }
11958 
11959   // Jump
11960   BuildMI(*MBB, MI, DL,
11961           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11962   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11963 
11964   MI.eraseFromParent();
11965   return MBB;
11966 }
11967 
11968 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11969   // If the function specifically requests inline stack probes, emit them.
11970   if (MF.getFunction().hasFnAttribute("probe-stack"))
11971     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11972            "inline-asm";
11973   return false;
11974 }
11975 
11976 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11977   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11978   unsigned StackAlign = TFI->getStackAlignment();
11979   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11980          "Unexpected stack alignment");
11981   // The default stack probe size is 4096 if the function has no
11982   // stack-probe-size attribute.
11983   unsigned StackProbeSize = 4096;
11984   const Function &Fn = MF.getFunction();
11985   if (Fn.hasFnAttribute("stack-probe-size"))
11986     Fn.getFnAttribute("stack-probe-size")
11987         .getValueAsString()
11988         .getAsInteger(0, StackProbeSize);
11989   // Round down to the stack alignment.
11990   StackProbeSize &= ~(StackAlign - 1);
11991   return StackProbeSize ? StackProbeSize : StackAlign;
11992 }
11993 
11994 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11995 // into three phases. In the first phase, it uses pseudo instruction
11996 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11997 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11998 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11999 // MaxCallFrameSize so that it can calculate correct data area pointer.
12000 MachineBasicBlock *
12001 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
12002                                     MachineBasicBlock *MBB) const {
12003   const bool isPPC64 = Subtarget.isPPC64();
12004   MachineFunction *MF = MBB->getParent();
12005   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12006   DebugLoc DL = MI.getDebugLoc();
12007   const unsigned ProbeSize = getStackProbeSize(*MF);
12008   const BasicBlock *ProbedBB = MBB->getBasicBlock();
12009   MachineRegisterInfo &MRI = MF->getRegInfo();
12010   // The CFG of probing stack looks as
12011   //         +-----+
12012   //         | MBB |
12013   //         +--+--+
12014   //            |
12015   //       +----v----+
12016   //  +--->+ TestMBB +---+
12017   //  |    +----+----+   |
12018   //  |         |        |
12019   //  |   +-----v----+   |
12020   //  +---+ BlockMBB |   |
12021   //      +----------+   |
12022   //                     |
12023   //       +---------+   |
12024   //       | TailMBB +<--+
12025   //       +---------+
12026   // In MBB, calculate previous frame pointer and final stack pointer.
12027   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
12028   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
12029   // TailMBB is spliced via \p MI.
12030   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
12031   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
12032   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
12033 
12034   MachineFunction::iterator MBBIter = ++MBB->getIterator();
12035   MF->insert(MBBIter, TestMBB);
12036   MF->insert(MBBIter, BlockMBB);
12037   MF->insert(MBBIter, TailMBB);
12038 
12039   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
12040   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12041 
12042   Register DstReg = MI.getOperand(0).getReg();
12043   Register NegSizeReg = MI.getOperand(1).getReg();
12044   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12045   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12046   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12047   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12048 
12049   // Since value of NegSizeReg might be realigned in prologepilog, insert a
12050   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
12051   // NegSize.
12052   unsigned ProbeOpc;
12053   if (!MRI.hasOneNonDBGUse(NegSizeReg))
12054     ProbeOpc =
12055         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
12056   else
12057     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
12058     // and NegSizeReg will be allocated in the same phyreg to avoid
12059     // redundant copy when NegSizeReg has only one use which is current MI and
12060     // will be replaced by PREPARE_PROBED_ALLOCA then.
12061     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
12062                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
12063   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
12064       .addDef(ActualNegSizeReg)
12065       .addReg(NegSizeReg)
12066       .add(MI.getOperand(2))
12067       .add(MI.getOperand(3));
12068 
12069   // Calculate final stack pointer, which equals to SP + ActualNegSize.
12070   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12071           FinalStackPtr)
12072       .addReg(SPReg)
12073       .addReg(ActualNegSizeReg);
12074 
12075   // Materialize a scratch register for update.
12076   int64_t NegProbeSize = -(int64_t)ProbeSize;
12077   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
12078   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12079   if (!isInt<16>(NegProbeSize)) {
12080     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12081     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12082         .addImm(NegProbeSize >> 16);
12083     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12084             ScratchReg)
12085         .addReg(TempReg)
12086         .addImm(NegProbeSize & 0xFFFF);
12087   } else
12088     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12089         .addImm(NegProbeSize);
12090 
12091   {
12092     // Probing leading residual part.
12093     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12094     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12095         .addReg(ActualNegSizeReg)
12096         .addReg(ScratchReg);
12097     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12098     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12099         .addReg(Div)
12100         .addReg(ScratchReg);
12101     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12102     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12103         .addReg(Mul)
12104         .addReg(ActualNegSizeReg);
12105     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12106         .addReg(FramePointer)
12107         .addReg(SPReg)
12108         .addReg(NegMod);
12109   }
12110 
12111   {
12112     // Remaining part should be multiple of ProbeSize.
12113     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12114     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12115         .addReg(SPReg)
12116         .addReg(FinalStackPtr);
12117     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12118         .addImm(PPC::PRED_EQ)
12119         .addReg(CmpResult)
12120         .addMBB(TailMBB);
12121     TestMBB->addSuccessor(BlockMBB);
12122     TestMBB->addSuccessor(TailMBB);
12123   }
12124 
12125   {
12126     // Touch the block.
12127     // |P...|P...|P...
12128     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12129         .addReg(FramePointer)
12130         .addReg(SPReg)
12131         .addReg(ScratchReg);
12132     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12133     BlockMBB->addSuccessor(TestMBB);
12134   }
12135 
12136   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12137   // DYNAREAOFFSET pseudo instruction to get the future result.
12138   Register MaxCallFrameSizeReg =
12139       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12140   BuildMI(TailMBB, DL,
12141           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12142           MaxCallFrameSizeReg)
12143       .add(MI.getOperand(2))
12144       .add(MI.getOperand(3));
12145   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12146       .addReg(SPReg)
12147       .addReg(MaxCallFrameSizeReg);
12148 
12149   // Splice instructions after MI to TailMBB.
12150   TailMBB->splice(TailMBB->end(), MBB,
12151                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12152   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12153   MBB->addSuccessor(TestMBB);
12154 
12155   // Delete the pseudo instruction.
12156   MI.eraseFromParent();
12157 
12158   ++NumDynamicAllocaProbed;
12159   return TailMBB;
12160 }
12161 
12162 MachineBasicBlock *
12163 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12164                                                MachineBasicBlock *BB) const {
12165   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12166       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12167     if (Subtarget.is64BitELFABI() &&
12168         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12169         !Subtarget.isUsingPCRelativeCalls()) {
12170       // Call lowering should have added an r2 operand to indicate a dependence
12171       // on the TOC base pointer value. It can't however, because there is no
12172       // way to mark the dependence as implicit there, and so the stackmap code
12173       // will confuse it with a regular operand. Instead, add the dependence
12174       // here.
12175       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12176     }
12177 
12178     return emitPatchPoint(MI, BB);
12179   }
12180 
12181   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12182       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12183     return emitEHSjLjSetJmp(MI, BB);
12184   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12185              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12186     return emitEHSjLjLongJmp(MI, BB);
12187   }
12188 
12189   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12190 
12191   // To "insert" these instructions we actually have to insert their
12192   // control-flow patterns.
12193   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12194   MachineFunction::iterator It = ++BB->getIterator();
12195 
12196   MachineFunction *F = BB->getParent();
12197   MachineRegisterInfo &MRI = F->getRegInfo();
12198 
12199   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12200       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12201       MI.getOpcode() == PPC::SELECT_I8) {
12202     SmallVector<MachineOperand, 2> Cond;
12203     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12204         MI.getOpcode() == PPC::SELECT_CC_I8)
12205       Cond.push_back(MI.getOperand(4));
12206     else
12207       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12208     Cond.push_back(MI.getOperand(1));
12209 
12210     DebugLoc dl = MI.getDebugLoc();
12211     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12212                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12213   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12214              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12215              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12216              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12217              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12218              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12219              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12220              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12221              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12222              MI.getOpcode() == PPC::SELECT_F4 ||
12223              MI.getOpcode() == PPC::SELECT_F8 ||
12224              MI.getOpcode() == PPC::SELECT_F16 ||
12225              MI.getOpcode() == PPC::SELECT_SPE ||
12226              MI.getOpcode() == PPC::SELECT_SPE4 ||
12227              MI.getOpcode() == PPC::SELECT_VRRC ||
12228              MI.getOpcode() == PPC::SELECT_VSFRC ||
12229              MI.getOpcode() == PPC::SELECT_VSSRC ||
12230              MI.getOpcode() == PPC::SELECT_VSRC) {
12231     // The incoming instruction knows the destination vreg to set, the
12232     // condition code register to branch on, the true/false values to
12233     // select between, and a branch opcode to use.
12234 
12235     //  thisMBB:
12236     //  ...
12237     //   TrueVal = ...
12238     //   cmpTY ccX, r1, r2
12239     //   bCC copy1MBB
12240     //   fallthrough --> copy0MBB
12241     MachineBasicBlock *thisMBB = BB;
12242     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12243     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12244     DebugLoc dl = MI.getDebugLoc();
12245     F->insert(It, copy0MBB);
12246     F->insert(It, sinkMBB);
12247 
12248     // Transfer the remainder of BB and its successor edges to sinkMBB.
12249     sinkMBB->splice(sinkMBB->begin(), BB,
12250                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12251     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12252 
12253     // Next, add the true and fallthrough blocks as its successors.
12254     BB->addSuccessor(copy0MBB);
12255     BB->addSuccessor(sinkMBB);
12256 
12257     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12258         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12259         MI.getOpcode() == PPC::SELECT_F16 ||
12260         MI.getOpcode() == PPC::SELECT_SPE4 ||
12261         MI.getOpcode() == PPC::SELECT_SPE ||
12262         MI.getOpcode() == PPC::SELECT_VRRC ||
12263         MI.getOpcode() == PPC::SELECT_VSFRC ||
12264         MI.getOpcode() == PPC::SELECT_VSSRC ||
12265         MI.getOpcode() == PPC::SELECT_VSRC) {
12266       BuildMI(BB, dl, TII->get(PPC::BC))
12267           .addReg(MI.getOperand(1).getReg())
12268           .addMBB(sinkMBB);
12269     } else {
12270       unsigned SelectPred = MI.getOperand(4).getImm();
12271       BuildMI(BB, dl, TII->get(PPC::BCC))
12272           .addImm(SelectPred)
12273           .addReg(MI.getOperand(1).getReg())
12274           .addMBB(sinkMBB);
12275     }
12276 
12277     //  copy0MBB:
12278     //   %FalseValue = ...
12279     //   # fallthrough to sinkMBB
12280     BB = copy0MBB;
12281 
12282     // Update machine-CFG edges
12283     BB->addSuccessor(sinkMBB);
12284 
12285     //  sinkMBB:
12286     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12287     //  ...
12288     BB = sinkMBB;
12289     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12290         .addReg(MI.getOperand(3).getReg())
12291         .addMBB(copy0MBB)
12292         .addReg(MI.getOperand(2).getReg())
12293         .addMBB(thisMBB);
12294   } else if (MI.getOpcode() == PPC::ReadTB) {
12295     // To read the 64-bit time-base register on a 32-bit target, we read the
12296     // two halves. Should the counter have wrapped while it was being read, we
12297     // need to try again.
12298     // ...
12299     // readLoop:
12300     // mfspr Rx,TBU # load from TBU
12301     // mfspr Ry,TB  # load from TB
12302     // mfspr Rz,TBU # load from TBU
12303     // cmpw crX,Rx,Rz # check if 'old'='new'
12304     // bne readLoop   # branch if they're not equal
12305     // ...
12306 
12307     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12308     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12309     DebugLoc dl = MI.getDebugLoc();
12310     F->insert(It, readMBB);
12311     F->insert(It, sinkMBB);
12312 
12313     // Transfer the remainder of BB and its successor edges to sinkMBB.
12314     sinkMBB->splice(sinkMBB->begin(), BB,
12315                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12316     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12317 
12318     BB->addSuccessor(readMBB);
12319     BB = readMBB;
12320 
12321     MachineRegisterInfo &RegInfo = F->getRegInfo();
12322     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12323     Register LoReg = MI.getOperand(0).getReg();
12324     Register HiReg = MI.getOperand(1).getReg();
12325 
12326     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12327     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12328     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12329 
12330     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12331 
12332     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12333         .addReg(HiReg)
12334         .addReg(ReadAgainReg);
12335     BuildMI(BB, dl, TII->get(PPC::BCC))
12336         .addImm(PPC::PRED_NE)
12337         .addReg(CmpReg)
12338         .addMBB(readMBB);
12339 
12340     BB->addSuccessor(readMBB);
12341     BB->addSuccessor(sinkMBB);
12342   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12343     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12344   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12345     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12346   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12347     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12348   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12349     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12350 
12351   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12352     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12353   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12354     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12355   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12356     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12357   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12358     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12359 
12360   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12361     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12362   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12363     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12364   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12365     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12366   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12367     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12368 
12369   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12370     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12371   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12372     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12373   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12374     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12375   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12376     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12377 
12378   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12379     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12380   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12381     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12382   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12383     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12384   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12385     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12386 
12387   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12388     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12389   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12390     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12391   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12392     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12393   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12394     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12395 
12396   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12397     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12398   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12399     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12400   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12401     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12402   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12403     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12404 
12405   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12406     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12407   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12408     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12409   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12410     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12411   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12412     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12413 
12414   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12415     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12416   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12417     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12418   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12419     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12420   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12421     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12422 
12423   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12424     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12425   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12426     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12427   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12428     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12429   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12430     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12431 
12432   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12433     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12434   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12435     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12436   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12437     BB = EmitAtomicBinary(MI, BB, 4, 0);
12438   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12439     BB = EmitAtomicBinary(MI, BB, 8, 0);
12440   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12441            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12442            (Subtarget.hasPartwordAtomics() &&
12443             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12444            (Subtarget.hasPartwordAtomics() &&
12445             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12446     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12447 
12448     auto LoadMnemonic = PPC::LDARX;
12449     auto StoreMnemonic = PPC::STDCX;
12450     switch (MI.getOpcode()) {
12451     default:
12452       llvm_unreachable("Compare and swap of unknown size");
12453     case PPC::ATOMIC_CMP_SWAP_I8:
12454       LoadMnemonic = PPC::LBARX;
12455       StoreMnemonic = PPC::STBCX;
12456       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12457       break;
12458     case PPC::ATOMIC_CMP_SWAP_I16:
12459       LoadMnemonic = PPC::LHARX;
12460       StoreMnemonic = PPC::STHCX;
12461       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12462       break;
12463     case PPC::ATOMIC_CMP_SWAP_I32:
12464       LoadMnemonic = PPC::LWARX;
12465       StoreMnemonic = PPC::STWCX;
12466       break;
12467     case PPC::ATOMIC_CMP_SWAP_I64:
12468       LoadMnemonic = PPC::LDARX;
12469       StoreMnemonic = PPC::STDCX;
12470       break;
12471     }
12472     Register dest = MI.getOperand(0).getReg();
12473     Register ptrA = MI.getOperand(1).getReg();
12474     Register ptrB = MI.getOperand(2).getReg();
12475     Register oldval = MI.getOperand(3).getReg();
12476     Register newval = MI.getOperand(4).getReg();
12477     DebugLoc dl = MI.getDebugLoc();
12478 
12479     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12480     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12481     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12482     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12483     F->insert(It, loop1MBB);
12484     F->insert(It, loop2MBB);
12485     F->insert(It, midMBB);
12486     F->insert(It, exitMBB);
12487     exitMBB->splice(exitMBB->begin(), BB,
12488                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12489     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12490 
12491     //  thisMBB:
12492     //   ...
12493     //   fallthrough --> loopMBB
12494     BB->addSuccessor(loop1MBB);
12495 
12496     // loop1MBB:
12497     //   l[bhwd]arx dest, ptr
12498     //   cmp[wd] dest, oldval
12499     //   bne- midMBB
12500     // loop2MBB:
12501     //   st[bhwd]cx. newval, ptr
12502     //   bne- loopMBB
12503     //   b exitBB
12504     // midMBB:
12505     //   st[bhwd]cx. dest, ptr
12506     // exitBB:
12507     BB = loop1MBB;
12508     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12509     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12510         .addReg(oldval)
12511         .addReg(dest);
12512     BuildMI(BB, dl, TII->get(PPC::BCC))
12513         .addImm(PPC::PRED_NE)
12514         .addReg(PPC::CR0)
12515         .addMBB(midMBB);
12516     BB->addSuccessor(loop2MBB);
12517     BB->addSuccessor(midMBB);
12518 
12519     BB = loop2MBB;
12520     BuildMI(BB, dl, TII->get(StoreMnemonic))
12521         .addReg(newval)
12522         .addReg(ptrA)
12523         .addReg(ptrB);
12524     BuildMI(BB, dl, TII->get(PPC::BCC))
12525         .addImm(PPC::PRED_NE)
12526         .addReg(PPC::CR0)
12527         .addMBB(loop1MBB);
12528     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12529     BB->addSuccessor(loop1MBB);
12530     BB->addSuccessor(exitMBB);
12531 
12532     BB = midMBB;
12533     BuildMI(BB, dl, TII->get(StoreMnemonic))
12534         .addReg(dest)
12535         .addReg(ptrA)
12536         .addReg(ptrB);
12537     BB->addSuccessor(exitMBB);
12538 
12539     //  exitMBB:
12540     //   ...
12541     BB = exitMBB;
12542   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12543              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12544     // We must use 64-bit registers for addresses when targeting 64-bit,
12545     // since we're actually doing arithmetic on them.  Other registers
12546     // can be 32-bit.
12547     bool is64bit = Subtarget.isPPC64();
12548     bool isLittleEndian = Subtarget.isLittleEndian();
12549     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12550 
12551     Register dest = MI.getOperand(0).getReg();
12552     Register ptrA = MI.getOperand(1).getReg();
12553     Register ptrB = MI.getOperand(2).getReg();
12554     Register oldval = MI.getOperand(3).getReg();
12555     Register newval = MI.getOperand(4).getReg();
12556     DebugLoc dl = MI.getDebugLoc();
12557 
12558     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12559     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12560     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12561     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12562     F->insert(It, loop1MBB);
12563     F->insert(It, loop2MBB);
12564     F->insert(It, midMBB);
12565     F->insert(It, exitMBB);
12566     exitMBB->splice(exitMBB->begin(), BB,
12567                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12568     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12569 
12570     MachineRegisterInfo &RegInfo = F->getRegInfo();
12571     const TargetRegisterClass *RC =
12572         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12573     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12574 
12575     Register PtrReg = RegInfo.createVirtualRegister(RC);
12576     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12577     Register ShiftReg =
12578         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12579     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12580     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12581     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12582     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12583     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12584     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12585     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12586     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12587     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12588     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12589     Register Ptr1Reg;
12590     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12591     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12592     //  thisMBB:
12593     //   ...
12594     //   fallthrough --> loopMBB
12595     BB->addSuccessor(loop1MBB);
12596 
12597     // The 4-byte load must be aligned, while a char or short may be
12598     // anywhere in the word.  Hence all this nasty bookkeeping code.
12599     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12600     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12601     //   xori shift, shift1, 24 [16]
12602     //   rlwinm ptr, ptr1, 0, 0, 29
12603     //   slw newval2, newval, shift
12604     //   slw oldval2, oldval,shift
12605     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12606     //   slw mask, mask2, shift
12607     //   and newval3, newval2, mask
12608     //   and oldval3, oldval2, mask
12609     // loop1MBB:
12610     //   lwarx tmpDest, ptr
12611     //   and tmp, tmpDest, mask
12612     //   cmpw tmp, oldval3
12613     //   bne- midMBB
12614     // loop2MBB:
12615     //   andc tmp2, tmpDest, mask
12616     //   or tmp4, tmp2, newval3
12617     //   stwcx. tmp4, ptr
12618     //   bne- loop1MBB
12619     //   b exitBB
12620     // midMBB:
12621     //   stwcx. tmpDest, ptr
12622     // exitBB:
12623     //   srw dest, tmpDest, shift
12624     if (ptrA != ZeroReg) {
12625       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12626       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12627           .addReg(ptrA)
12628           .addReg(ptrB);
12629     } else {
12630       Ptr1Reg = ptrB;
12631     }
12632 
12633     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12634     // mode.
12635     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12636         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12637         .addImm(3)
12638         .addImm(27)
12639         .addImm(is8bit ? 28 : 27);
12640     if (!isLittleEndian)
12641       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12642           .addReg(Shift1Reg)
12643           .addImm(is8bit ? 24 : 16);
12644     if (is64bit)
12645       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12646           .addReg(Ptr1Reg)
12647           .addImm(0)
12648           .addImm(61);
12649     else
12650       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12651           .addReg(Ptr1Reg)
12652           .addImm(0)
12653           .addImm(0)
12654           .addImm(29);
12655     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12656         .addReg(newval)
12657         .addReg(ShiftReg);
12658     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12659         .addReg(oldval)
12660         .addReg(ShiftReg);
12661     if (is8bit)
12662       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12663     else {
12664       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12665       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12666           .addReg(Mask3Reg)
12667           .addImm(65535);
12668     }
12669     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12670         .addReg(Mask2Reg)
12671         .addReg(ShiftReg);
12672     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12673         .addReg(NewVal2Reg)
12674         .addReg(MaskReg);
12675     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12676         .addReg(OldVal2Reg)
12677         .addReg(MaskReg);
12678 
12679     BB = loop1MBB;
12680     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12681         .addReg(ZeroReg)
12682         .addReg(PtrReg);
12683     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12684         .addReg(TmpDestReg)
12685         .addReg(MaskReg);
12686     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12687         .addReg(TmpReg)
12688         .addReg(OldVal3Reg);
12689     BuildMI(BB, dl, TII->get(PPC::BCC))
12690         .addImm(PPC::PRED_NE)
12691         .addReg(PPC::CR0)
12692         .addMBB(midMBB);
12693     BB->addSuccessor(loop2MBB);
12694     BB->addSuccessor(midMBB);
12695 
12696     BB = loop2MBB;
12697     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12698         .addReg(TmpDestReg)
12699         .addReg(MaskReg);
12700     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12701         .addReg(Tmp2Reg)
12702         .addReg(NewVal3Reg);
12703     BuildMI(BB, dl, TII->get(PPC::STWCX))
12704         .addReg(Tmp4Reg)
12705         .addReg(ZeroReg)
12706         .addReg(PtrReg);
12707     BuildMI(BB, dl, TII->get(PPC::BCC))
12708         .addImm(PPC::PRED_NE)
12709         .addReg(PPC::CR0)
12710         .addMBB(loop1MBB);
12711     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12712     BB->addSuccessor(loop1MBB);
12713     BB->addSuccessor(exitMBB);
12714 
12715     BB = midMBB;
12716     BuildMI(BB, dl, TII->get(PPC::STWCX))
12717         .addReg(TmpDestReg)
12718         .addReg(ZeroReg)
12719         .addReg(PtrReg);
12720     BB->addSuccessor(exitMBB);
12721 
12722     //  exitMBB:
12723     //   ...
12724     BB = exitMBB;
12725     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12726         .addReg(TmpReg)
12727         .addReg(ShiftReg);
12728   } else if (MI.getOpcode() == PPC::FADDrtz) {
12729     // This pseudo performs an FADD with rounding mode temporarily forced
12730     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12731     // is not modeled at the SelectionDAG level.
12732     Register Dest = MI.getOperand(0).getReg();
12733     Register Src1 = MI.getOperand(1).getReg();
12734     Register Src2 = MI.getOperand(2).getReg();
12735     DebugLoc dl = MI.getDebugLoc();
12736 
12737     MachineRegisterInfo &RegInfo = F->getRegInfo();
12738     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12739 
12740     // Save FPSCR value.
12741     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12742 
12743     // Set rounding mode to round-to-zero.
12744     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12745         .addImm(31)
12746         .addReg(PPC::RM, RegState::ImplicitDefine);
12747 
12748     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12749         .addImm(30)
12750         .addReg(PPC::RM, RegState::ImplicitDefine);
12751 
12752     // Perform addition.
12753     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12754                    .addReg(Src1)
12755                    .addReg(Src2);
12756     if (MI.getFlag(MachineInstr::NoFPExcept))
12757       MIB.setMIFlag(MachineInstr::NoFPExcept);
12758 
12759     // Restore FPSCR value.
12760     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12761   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12762              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12763              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12764              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12765     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12766                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12767                           ? PPC::ANDI8_rec
12768                           : PPC::ANDI_rec;
12769     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12770                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12771 
12772     MachineRegisterInfo &RegInfo = F->getRegInfo();
12773     Register Dest = RegInfo.createVirtualRegister(
12774         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12775 
12776     DebugLoc Dl = MI.getDebugLoc();
12777     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12778         .addReg(MI.getOperand(1).getReg())
12779         .addImm(1);
12780     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12781             MI.getOperand(0).getReg())
12782         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12783   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12784     DebugLoc Dl = MI.getDebugLoc();
12785     MachineRegisterInfo &RegInfo = F->getRegInfo();
12786     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12787     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12788     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12789             MI.getOperand(0).getReg())
12790         .addReg(CRReg);
12791   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12792     DebugLoc Dl = MI.getDebugLoc();
12793     unsigned Imm = MI.getOperand(1).getImm();
12794     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12795     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12796             MI.getOperand(0).getReg())
12797         .addReg(PPC::CR0EQ);
12798   } else if (MI.getOpcode() == PPC::SETRNDi) {
12799     DebugLoc dl = MI.getDebugLoc();
12800     Register OldFPSCRReg = MI.getOperand(0).getReg();
12801 
12802     // Save FPSCR value.
12803     if (MRI.use_empty(OldFPSCRReg))
12804       BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12805     else
12806       BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12807 
12808     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12809     // the following settings:
12810     //   00 Round to nearest
12811     //   01 Round to 0
12812     //   10 Round to +inf
12813     //   11 Round to -inf
12814 
12815     // When the operand is immediate, using the two least significant bits of
12816     // the immediate to set the bits 62:63 of FPSCR.
12817     unsigned Mode = MI.getOperand(1).getImm();
12818     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12819         .addImm(31)
12820         .addReg(PPC::RM, RegState::ImplicitDefine);
12821 
12822     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12823         .addImm(30)
12824         .addReg(PPC::RM, RegState::ImplicitDefine);
12825   } else if (MI.getOpcode() == PPC::SETRND) {
12826     DebugLoc dl = MI.getDebugLoc();
12827 
12828     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12829     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12830     // If the target doesn't have DirectMove, we should use stack to do the
12831     // conversion, because the target doesn't have the instructions like mtvsrd
12832     // or mfvsrd to do this conversion directly.
12833     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12834       if (Subtarget.hasDirectMove()) {
12835         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12836           .addReg(SrcReg);
12837       } else {
12838         // Use stack to do the register copy.
12839         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12840         MachineRegisterInfo &RegInfo = F->getRegInfo();
12841         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12842         if (RC == &PPC::F8RCRegClass) {
12843           // Copy register from F8RCRegClass to G8RCRegclass.
12844           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12845                  "Unsupported RegClass.");
12846 
12847           StoreOp = PPC::STFD;
12848           LoadOp = PPC::LD;
12849         } else {
12850           // Copy register from G8RCRegClass to F8RCRegclass.
12851           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12852                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12853                  "Unsupported RegClass.");
12854         }
12855 
12856         MachineFrameInfo &MFI = F->getFrameInfo();
12857         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12858 
12859         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12860             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12861             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12862             MFI.getObjectAlign(FrameIdx));
12863 
12864         // Store the SrcReg into the stack.
12865         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12866           .addReg(SrcReg)
12867           .addImm(0)
12868           .addFrameIndex(FrameIdx)
12869           .addMemOperand(MMOStore);
12870 
12871         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12872             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12873             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12874             MFI.getObjectAlign(FrameIdx));
12875 
12876         // Load from the stack where SrcReg is stored, and save to DestReg,
12877         // so we have done the RegClass conversion from RegClass::SrcReg to
12878         // RegClass::DestReg.
12879         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12880           .addImm(0)
12881           .addFrameIndex(FrameIdx)
12882           .addMemOperand(MMOLoad);
12883       }
12884     };
12885 
12886     Register OldFPSCRReg = MI.getOperand(0).getReg();
12887 
12888     // Save FPSCR value.
12889     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12890 
12891     // When the operand is gprc register, use two least significant bits of the
12892     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12893     //
12894     // copy OldFPSCRTmpReg, OldFPSCRReg
12895     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12896     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12897     // copy NewFPSCRReg, NewFPSCRTmpReg
12898     // mtfsf 255, NewFPSCRReg
12899     MachineOperand SrcOp = MI.getOperand(1);
12900     MachineRegisterInfo &RegInfo = F->getRegInfo();
12901     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12902 
12903     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12904 
12905     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12906     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12907 
12908     // The first operand of INSERT_SUBREG should be a register which has
12909     // subregisters, we only care about its RegClass, so we should use an
12910     // IMPLICIT_DEF register.
12911     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12912     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12913       .addReg(ImDefReg)
12914       .add(SrcOp)
12915       .addImm(1);
12916 
12917     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12918     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12919       .addReg(OldFPSCRTmpReg)
12920       .addReg(ExtSrcReg)
12921       .addImm(0)
12922       .addImm(62);
12923 
12924     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12925     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12926 
12927     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12928     // bits of FPSCR.
12929     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12930       .addImm(255)
12931       .addReg(NewFPSCRReg)
12932       .addImm(0)
12933       .addImm(0);
12934   } else if (MI.getOpcode() == PPC::SETFLM) {
12935     DebugLoc Dl = MI.getDebugLoc();
12936 
12937     // Result of setflm is previous FPSCR content, so we need to save it first.
12938     Register OldFPSCRReg = MI.getOperand(0).getReg();
12939     if (MRI.use_empty(OldFPSCRReg))
12940       BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12941     else
12942       BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12943 
12944     // Put bits in 32:63 to FPSCR.
12945     Register NewFPSCRReg = MI.getOperand(1).getReg();
12946     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12947         .addImm(255)
12948         .addReg(NewFPSCRReg)
12949         .addImm(0)
12950         .addImm(0);
12951   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12952              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12953     return emitProbedAlloca(MI, BB);
12954   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12955     DebugLoc DL = MI.getDebugLoc();
12956     Register Src = MI.getOperand(2).getReg();
12957     Register Lo = MI.getOperand(0).getReg();
12958     Register Hi = MI.getOperand(1).getReg();
12959     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12960         .addDef(Lo)
12961         .addUse(Src, 0, PPC::sub_gp8_x1);
12962     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12963         .addDef(Hi)
12964         .addUse(Src, 0, PPC::sub_gp8_x0);
12965   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12966              MI.getOpcode() == PPC::STQX_PSEUDO) {
12967     DebugLoc DL = MI.getDebugLoc();
12968     // Ptr is used as the ptr_rc_no_r0 part
12969     // of LQ/STQ's memory operand and adding result of RA and RB,
12970     // so it has to be g8rc_and_g8rc_nox0.
12971     Register Ptr =
12972         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12973     Register Val = MI.getOperand(0).getReg();
12974     Register RA = MI.getOperand(1).getReg();
12975     Register RB = MI.getOperand(2).getReg();
12976     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12977     BuildMI(*BB, MI, DL,
12978             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12979                                               : TII->get(PPC::STQ))
12980         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12981         .addImm(0)
12982         .addReg(Ptr);
12983   } else {
12984     llvm_unreachable("Unexpected instr type to insert");
12985   }
12986 
12987   MI.eraseFromParent(); // The pseudo instruction is gone now.
12988   return BB;
12989 }
12990 
12991 //===----------------------------------------------------------------------===//
12992 // Target Optimization Hooks
12993 //===----------------------------------------------------------------------===//
12994 
12995 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12996   // For the estimates, convergence is quadratic, so we essentially double the
12997   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12998   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12999   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
13000   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
13001   if (VT.getScalarType() == MVT::f64)
13002     RefinementSteps++;
13003   return RefinementSteps;
13004 }
13005 
13006 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
13007                                             const DenormalMode &Mode) const {
13008   // We only have VSX Vector Test for software Square Root.
13009   EVT VT = Op.getValueType();
13010   if (!isTypeLegal(MVT::i1) ||
13011       (VT != MVT::f64 &&
13012        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
13013     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
13014 
13015   SDLoc DL(Op);
13016   // The output register of FTSQRT is CR field.
13017   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
13018   // ftsqrt BF,FRB
13019   // Let e_b be the unbiased exponent of the double-precision
13020   // floating-point operand in register FRB.
13021   // fe_flag is set to 1 if either of the following conditions occurs.
13022   //   - The double-precision floating-point operand in register FRB is a zero,
13023   //     a NaN, or an infinity, or a negative value.
13024   //   - e_b is less than or equal to -970.
13025   // Otherwise fe_flag is set to 0.
13026   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
13027   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
13028   // exponent is less than -970)
13029   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
13030   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
13031                                     FTSQRT, SRIdxVal),
13032                  0);
13033 }
13034 
13035 SDValue
13036 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
13037                                                SelectionDAG &DAG) const {
13038   // We only have VSX Vector Square Root.
13039   EVT VT = Op.getValueType();
13040   if (VT != MVT::f64 &&
13041       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
13042     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
13043 
13044   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
13045 }
13046 
13047 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
13048                                            int Enabled, int &RefinementSteps,
13049                                            bool &UseOneConstNR,
13050                                            bool Reciprocal) const {
13051   EVT VT = Operand.getValueType();
13052   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
13053       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
13054       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13055       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13056     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13057       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13058 
13059     // The Newton-Raphson computation with a single constant does not provide
13060     // enough accuracy on some CPUs.
13061     UseOneConstNR = !Subtarget.needsTwoConstNR();
13062     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
13063   }
13064   return SDValue();
13065 }
13066 
13067 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
13068                                             int Enabled,
13069                                             int &RefinementSteps) const {
13070   EVT VT = Operand.getValueType();
13071   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13072       (VT == MVT::f64 && Subtarget.hasFRE()) ||
13073       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13074       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13075     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13076       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13077     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13078   }
13079   return SDValue();
13080 }
13081 
13082 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13083   // Note: This functionality is used only when unsafe-fp-math is enabled, and
13084   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13085   // enabled for division), this functionality is redundant with the default
13086   // combiner logic (once the division -> reciprocal/multiply transformation
13087   // has taken place). As a result, this matters more for older cores than for
13088   // newer ones.
13089 
13090   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13091   // reciprocal if there are two or more FDIVs (for embedded cores with only
13092   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13093   switch (Subtarget.getCPUDirective()) {
13094   default:
13095     return 3;
13096   case PPC::DIR_440:
13097   case PPC::DIR_A2:
13098   case PPC::DIR_E500:
13099   case PPC::DIR_E500mc:
13100   case PPC::DIR_E5500:
13101     return 2;
13102   }
13103 }
13104 
13105 // isConsecutiveLSLoc needs to work even if all adds have not yet been
13106 // collapsed, and so we need to look through chains of them.
13107 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13108                                      int64_t& Offset, SelectionDAG &DAG) {
13109   if (DAG.isBaseWithConstantOffset(Loc)) {
13110     Base = Loc.getOperand(0);
13111     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13112 
13113     // The base might itself be a base plus an offset, and if so, accumulate
13114     // that as well.
13115     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13116   }
13117 }
13118 
13119 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13120                             unsigned Bytes, int Dist,
13121                             SelectionDAG &DAG) {
13122   if (VT.getSizeInBits() / 8 != Bytes)
13123     return false;
13124 
13125   SDValue BaseLoc = Base->getBasePtr();
13126   if (Loc.getOpcode() == ISD::FrameIndex) {
13127     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13128       return false;
13129     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13130     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13131     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13132     int FS  = MFI.getObjectSize(FI);
13133     int BFS = MFI.getObjectSize(BFI);
13134     if (FS != BFS || FS != (int)Bytes) return false;
13135     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13136   }
13137 
13138   SDValue Base1 = Loc, Base2 = BaseLoc;
13139   int64_t Offset1 = 0, Offset2 = 0;
13140   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13141   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13142   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13143     return true;
13144 
13145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13146   const GlobalValue *GV1 = nullptr;
13147   const GlobalValue *GV2 = nullptr;
13148   Offset1 = 0;
13149   Offset2 = 0;
13150   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13151   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13152   if (isGA1 && isGA2 && GV1 == GV2)
13153     return Offset1 == (Offset2 + Dist*Bytes);
13154   return false;
13155 }
13156 
13157 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13158 // not enforce equality of the chain operands.
13159 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13160                             unsigned Bytes, int Dist,
13161                             SelectionDAG &DAG) {
13162   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13163     EVT VT = LS->getMemoryVT();
13164     SDValue Loc = LS->getBasePtr();
13165     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13166   }
13167 
13168   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13169     EVT VT;
13170     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13171     default: return false;
13172     case Intrinsic::ppc_altivec_lvx:
13173     case Intrinsic::ppc_altivec_lvxl:
13174     case Intrinsic::ppc_vsx_lxvw4x:
13175     case Intrinsic::ppc_vsx_lxvw4x_be:
13176       VT = MVT::v4i32;
13177       break;
13178     case Intrinsic::ppc_vsx_lxvd2x:
13179     case Intrinsic::ppc_vsx_lxvd2x_be:
13180       VT = MVT::v2f64;
13181       break;
13182     case Intrinsic::ppc_altivec_lvebx:
13183       VT = MVT::i8;
13184       break;
13185     case Intrinsic::ppc_altivec_lvehx:
13186       VT = MVT::i16;
13187       break;
13188     case Intrinsic::ppc_altivec_lvewx:
13189       VT = MVT::i32;
13190       break;
13191     }
13192 
13193     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13194   }
13195 
13196   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13197     EVT VT;
13198     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13199     default: return false;
13200     case Intrinsic::ppc_altivec_stvx:
13201     case Intrinsic::ppc_altivec_stvxl:
13202     case Intrinsic::ppc_vsx_stxvw4x:
13203       VT = MVT::v4i32;
13204       break;
13205     case Intrinsic::ppc_vsx_stxvd2x:
13206       VT = MVT::v2f64;
13207       break;
13208     case Intrinsic::ppc_vsx_stxvw4x_be:
13209       VT = MVT::v4i32;
13210       break;
13211     case Intrinsic::ppc_vsx_stxvd2x_be:
13212       VT = MVT::v2f64;
13213       break;
13214     case Intrinsic::ppc_altivec_stvebx:
13215       VT = MVT::i8;
13216       break;
13217     case Intrinsic::ppc_altivec_stvehx:
13218       VT = MVT::i16;
13219       break;
13220     case Intrinsic::ppc_altivec_stvewx:
13221       VT = MVT::i32;
13222       break;
13223     }
13224 
13225     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13226   }
13227 
13228   return false;
13229 }
13230 
13231 // Return true is there is a nearyby consecutive load to the one provided
13232 // (regardless of alignment). We search up and down the chain, looking though
13233 // token factors and other loads (but nothing else). As a result, a true result
13234 // indicates that it is safe to create a new consecutive load adjacent to the
13235 // load provided.
13236 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13237   SDValue Chain = LD->getChain();
13238   EVT VT = LD->getMemoryVT();
13239 
13240   SmallSet<SDNode *, 16> LoadRoots;
13241   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13242   SmallSet<SDNode *, 16> Visited;
13243 
13244   // First, search up the chain, branching to follow all token-factor operands.
13245   // If we find a consecutive load, then we're done, otherwise, record all
13246   // nodes just above the top-level loads and token factors.
13247   while (!Queue.empty()) {
13248     SDNode *ChainNext = Queue.pop_back_val();
13249     if (!Visited.insert(ChainNext).second)
13250       continue;
13251 
13252     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13253       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13254         return true;
13255 
13256       if (!Visited.count(ChainLD->getChain().getNode()))
13257         Queue.push_back(ChainLD->getChain().getNode());
13258     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13259       for (const SDUse &O : ChainNext->ops())
13260         if (!Visited.count(O.getNode()))
13261           Queue.push_back(O.getNode());
13262     } else
13263       LoadRoots.insert(ChainNext);
13264   }
13265 
13266   // Second, search down the chain, starting from the top-level nodes recorded
13267   // in the first phase. These top-level nodes are the nodes just above all
13268   // loads and token factors. Starting with their uses, recursively look though
13269   // all loads (just the chain uses) and token factors to find a consecutive
13270   // load.
13271   Visited.clear();
13272   Queue.clear();
13273 
13274   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13275        IE = LoadRoots.end(); I != IE; ++I) {
13276     Queue.push_back(*I);
13277 
13278     while (!Queue.empty()) {
13279       SDNode *LoadRoot = Queue.pop_back_val();
13280       if (!Visited.insert(LoadRoot).second)
13281         continue;
13282 
13283       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13284         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13285           return true;
13286 
13287       for (SDNode *U : LoadRoot->uses())
13288         if (((isa<MemSDNode>(U) &&
13289               cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13290              U->getOpcode() == ISD::TokenFactor) &&
13291             !Visited.count(U))
13292           Queue.push_back(U);
13293     }
13294   }
13295 
13296   return false;
13297 }
13298 
13299 /// This function is called when we have proved that a SETCC node can be replaced
13300 /// by subtraction (and other supporting instructions) so that the result of
13301 /// comparison is kept in a GPR instead of CR. This function is purely for
13302 /// codegen purposes and has some flags to guide the codegen process.
13303 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13304                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13305   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13306 
13307   // Zero extend the operands to the largest legal integer. Originally, they
13308   // must be of a strictly smaller size.
13309   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13310                          DAG.getConstant(Size, DL, MVT::i32));
13311   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13312                          DAG.getConstant(Size, DL, MVT::i32));
13313 
13314   // Swap if needed. Depends on the condition code.
13315   if (Swap)
13316     std::swap(Op0, Op1);
13317 
13318   // Subtract extended integers.
13319   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13320 
13321   // Move the sign bit to the least significant position and zero out the rest.
13322   // Now the least significant bit carries the result of original comparison.
13323   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13324                              DAG.getConstant(Size - 1, DL, MVT::i32));
13325   auto Final = Shifted;
13326 
13327   // Complement the result if needed. Based on the condition code.
13328   if (Complement)
13329     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13330                         DAG.getConstant(1, DL, MVT::i64));
13331 
13332   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13333 }
13334 
13335 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13336                                                   DAGCombinerInfo &DCI) const {
13337   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13338 
13339   SelectionDAG &DAG = DCI.DAG;
13340   SDLoc DL(N);
13341 
13342   // Size of integers being compared has a critical role in the following
13343   // analysis, so we prefer to do this when all types are legal.
13344   if (!DCI.isAfterLegalizeDAG())
13345     return SDValue();
13346 
13347   // If all users of SETCC extend its value to a legal integer type
13348   // then we replace SETCC with a subtraction
13349   for (const SDNode *U : N->uses())
13350     if (U->getOpcode() != ISD::ZERO_EXTEND)
13351       return SDValue();
13352 
13353   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13354   auto OpSize = N->getOperand(0).getValueSizeInBits();
13355 
13356   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13357 
13358   if (OpSize < Size) {
13359     switch (CC) {
13360     default: break;
13361     case ISD::SETULT:
13362       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13363     case ISD::SETULE:
13364       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13365     case ISD::SETUGT:
13366       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13367     case ISD::SETUGE:
13368       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13369     }
13370   }
13371 
13372   return SDValue();
13373 }
13374 
13375 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13376                                                   DAGCombinerInfo &DCI) const {
13377   SelectionDAG &DAG = DCI.DAG;
13378   SDLoc dl(N);
13379 
13380   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13381   // If we're tracking CR bits, we need to be careful that we don't have:
13382   //   trunc(binary-ops(zext(x), zext(y)))
13383   // or
13384   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13385   // such that we're unnecessarily moving things into GPRs when it would be
13386   // better to keep them in CR bits.
13387 
13388   // Note that trunc here can be an actual i1 trunc, or can be the effective
13389   // truncation that comes from a setcc or select_cc.
13390   if (N->getOpcode() == ISD::TRUNCATE &&
13391       N->getValueType(0) != MVT::i1)
13392     return SDValue();
13393 
13394   if (N->getOperand(0).getValueType() != MVT::i32 &&
13395       N->getOperand(0).getValueType() != MVT::i64)
13396     return SDValue();
13397 
13398   if (N->getOpcode() == ISD::SETCC ||
13399       N->getOpcode() == ISD::SELECT_CC) {
13400     // If we're looking at a comparison, then we need to make sure that the
13401     // high bits (all except for the first) don't matter the result.
13402     ISD::CondCode CC =
13403       cast<CondCodeSDNode>(N->getOperand(
13404         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13405     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13406 
13407     if (ISD::isSignedIntSetCC(CC)) {
13408       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13409           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13410         return SDValue();
13411     } else if (ISD::isUnsignedIntSetCC(CC)) {
13412       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13413                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13414           !DAG.MaskedValueIsZero(N->getOperand(1),
13415                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13416         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13417                                              : SDValue());
13418     } else {
13419       // This is neither a signed nor an unsigned comparison, just make sure
13420       // that the high bits are equal.
13421       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13422       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13423 
13424       // We don't really care about what is known about the first bit (if
13425       // anything), so pretend that it is known zero for both to ensure they can
13426       // be compared as constants.
13427       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13428       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13429 
13430       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13431           Op1Known.getConstant() != Op2Known.getConstant())
13432         return SDValue();
13433     }
13434   }
13435 
13436   // We now know that the higher-order bits are irrelevant, we just need to
13437   // make sure that all of the intermediate operations are bit operations, and
13438   // all inputs are extensions.
13439   if (N->getOperand(0).getOpcode() != ISD::AND &&
13440       N->getOperand(0).getOpcode() != ISD::OR  &&
13441       N->getOperand(0).getOpcode() != ISD::XOR &&
13442       N->getOperand(0).getOpcode() != ISD::SELECT &&
13443       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13444       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13445       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13446       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13447       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13448     return SDValue();
13449 
13450   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13451       N->getOperand(1).getOpcode() != ISD::AND &&
13452       N->getOperand(1).getOpcode() != ISD::OR  &&
13453       N->getOperand(1).getOpcode() != ISD::XOR &&
13454       N->getOperand(1).getOpcode() != ISD::SELECT &&
13455       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13456       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13457       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13458       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13459       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13460     return SDValue();
13461 
13462   SmallVector<SDValue, 4> Inputs;
13463   SmallVector<SDValue, 8> BinOps, PromOps;
13464   SmallPtrSet<SDNode *, 16> Visited;
13465 
13466   for (unsigned i = 0; i < 2; ++i) {
13467     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13468           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13469           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13470           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13471         isa<ConstantSDNode>(N->getOperand(i)))
13472       Inputs.push_back(N->getOperand(i));
13473     else
13474       BinOps.push_back(N->getOperand(i));
13475 
13476     if (N->getOpcode() == ISD::TRUNCATE)
13477       break;
13478   }
13479 
13480   // Visit all inputs, collect all binary operations (and, or, xor and
13481   // select) that are all fed by extensions.
13482   while (!BinOps.empty()) {
13483     SDValue BinOp = BinOps.pop_back_val();
13484 
13485     if (!Visited.insert(BinOp.getNode()).second)
13486       continue;
13487 
13488     PromOps.push_back(BinOp);
13489 
13490     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13491       // The condition of the select is not promoted.
13492       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13493         continue;
13494       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13495         continue;
13496 
13497       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13498             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13499             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13500            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13501           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13502         Inputs.push_back(BinOp.getOperand(i));
13503       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13504                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13505                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13506                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13507                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13508                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13509                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13510                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13511                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13512         BinOps.push_back(BinOp.getOperand(i));
13513       } else {
13514         // We have an input that is not an extension or another binary
13515         // operation; we'll abort this transformation.
13516         return SDValue();
13517       }
13518     }
13519   }
13520 
13521   // Make sure that this is a self-contained cluster of operations (which
13522   // is not quite the same thing as saying that everything has only one
13523   // use).
13524   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13525     if (isa<ConstantSDNode>(Inputs[i]))
13526       continue;
13527 
13528     for (const SDNode *User : Inputs[i].getNode()->uses()) {
13529       if (User != N && !Visited.count(User))
13530         return SDValue();
13531 
13532       // Make sure that we're not going to promote the non-output-value
13533       // operand(s) or SELECT or SELECT_CC.
13534       // FIXME: Although we could sometimes handle this, and it does occur in
13535       // practice that one of the condition inputs to the select is also one of
13536       // the outputs, we currently can't deal with this.
13537       if (User->getOpcode() == ISD::SELECT) {
13538         if (User->getOperand(0) == Inputs[i])
13539           return SDValue();
13540       } else if (User->getOpcode() == ISD::SELECT_CC) {
13541         if (User->getOperand(0) == Inputs[i] ||
13542             User->getOperand(1) == Inputs[i])
13543           return SDValue();
13544       }
13545     }
13546   }
13547 
13548   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13549     for (const SDNode *User : PromOps[i].getNode()->uses()) {
13550       if (User != N && !Visited.count(User))
13551         return SDValue();
13552 
13553       // Make sure that we're not going to promote the non-output-value
13554       // operand(s) or SELECT or SELECT_CC.
13555       // FIXME: Although we could sometimes handle this, and it does occur in
13556       // practice that one of the condition inputs to the select is also one of
13557       // the outputs, we currently can't deal with this.
13558       if (User->getOpcode() == ISD::SELECT) {
13559         if (User->getOperand(0) == PromOps[i])
13560           return SDValue();
13561       } else if (User->getOpcode() == ISD::SELECT_CC) {
13562         if (User->getOperand(0) == PromOps[i] ||
13563             User->getOperand(1) == PromOps[i])
13564           return SDValue();
13565       }
13566     }
13567   }
13568 
13569   // Replace all inputs with the extension operand.
13570   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13571     // Constants may have users outside the cluster of to-be-promoted nodes,
13572     // and so we need to replace those as we do the promotions.
13573     if (isa<ConstantSDNode>(Inputs[i]))
13574       continue;
13575     else
13576       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13577   }
13578 
13579   std::list<HandleSDNode> PromOpHandles;
13580   for (auto &PromOp : PromOps)
13581     PromOpHandles.emplace_back(PromOp);
13582 
13583   // Replace all operations (these are all the same, but have a different
13584   // (i1) return type). DAG.getNode will validate that the types of
13585   // a binary operator match, so go through the list in reverse so that
13586   // we've likely promoted both operands first. Any intermediate truncations or
13587   // extensions disappear.
13588   while (!PromOpHandles.empty()) {
13589     SDValue PromOp = PromOpHandles.back().getValue();
13590     PromOpHandles.pop_back();
13591 
13592     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13593         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13594         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13595         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13596       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13597           PromOp.getOperand(0).getValueType() != MVT::i1) {
13598         // The operand is not yet ready (see comment below).
13599         PromOpHandles.emplace_front(PromOp);
13600         continue;
13601       }
13602 
13603       SDValue RepValue = PromOp.getOperand(0);
13604       if (isa<ConstantSDNode>(RepValue))
13605         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13606 
13607       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13608       continue;
13609     }
13610 
13611     unsigned C;
13612     switch (PromOp.getOpcode()) {
13613     default:             C = 0; break;
13614     case ISD::SELECT:    C = 1; break;
13615     case ISD::SELECT_CC: C = 2; break;
13616     }
13617 
13618     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13619          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13620         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13621          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13622       // The to-be-promoted operands of this node have not yet been
13623       // promoted (this should be rare because we're going through the
13624       // list backward, but if one of the operands has several users in
13625       // this cluster of to-be-promoted nodes, it is possible).
13626       PromOpHandles.emplace_front(PromOp);
13627       continue;
13628     }
13629 
13630     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13631                                 PromOp.getNode()->op_end());
13632 
13633     // If there are any constant inputs, make sure they're replaced now.
13634     for (unsigned i = 0; i < 2; ++i)
13635       if (isa<ConstantSDNode>(Ops[C+i]))
13636         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13637 
13638     DAG.ReplaceAllUsesOfValueWith(PromOp,
13639       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13640   }
13641 
13642   // Now we're left with the initial truncation itself.
13643   if (N->getOpcode() == ISD::TRUNCATE)
13644     return N->getOperand(0);
13645 
13646   // Otherwise, this is a comparison. The operands to be compared have just
13647   // changed type (to i1), but everything else is the same.
13648   return SDValue(N, 0);
13649 }
13650 
13651 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13652                                                   DAGCombinerInfo &DCI) const {
13653   SelectionDAG &DAG = DCI.DAG;
13654   SDLoc dl(N);
13655 
13656   // If we're tracking CR bits, we need to be careful that we don't have:
13657   //   zext(binary-ops(trunc(x), trunc(y)))
13658   // or
13659   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13660   // such that we're unnecessarily moving things into CR bits that can more
13661   // efficiently stay in GPRs. Note that if we're not certain that the high
13662   // bits are set as required by the final extension, we still may need to do
13663   // some masking to get the proper behavior.
13664 
13665   // This same functionality is important on PPC64 when dealing with
13666   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13667   // the return values of functions. Because it is so similar, it is handled
13668   // here as well.
13669 
13670   if (N->getValueType(0) != MVT::i32 &&
13671       N->getValueType(0) != MVT::i64)
13672     return SDValue();
13673 
13674   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13675         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13676     return SDValue();
13677 
13678   if (N->getOperand(0).getOpcode() != ISD::AND &&
13679       N->getOperand(0).getOpcode() != ISD::OR  &&
13680       N->getOperand(0).getOpcode() != ISD::XOR &&
13681       N->getOperand(0).getOpcode() != ISD::SELECT &&
13682       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13683     return SDValue();
13684 
13685   SmallVector<SDValue, 4> Inputs;
13686   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13687   SmallPtrSet<SDNode *, 16> Visited;
13688 
13689   // Visit all inputs, collect all binary operations (and, or, xor and
13690   // select) that are all fed by truncations.
13691   while (!BinOps.empty()) {
13692     SDValue BinOp = BinOps.pop_back_val();
13693 
13694     if (!Visited.insert(BinOp.getNode()).second)
13695       continue;
13696 
13697     PromOps.push_back(BinOp);
13698 
13699     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13700       // The condition of the select is not promoted.
13701       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13702         continue;
13703       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13704         continue;
13705 
13706       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13707           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13708         Inputs.push_back(BinOp.getOperand(i));
13709       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13710                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13711                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13712                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13713                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13714         BinOps.push_back(BinOp.getOperand(i));
13715       } else {
13716         // We have an input that is not a truncation or another binary
13717         // operation; we'll abort this transformation.
13718         return SDValue();
13719       }
13720     }
13721   }
13722 
13723   // The operands of a select that must be truncated when the select is
13724   // promoted because the operand is actually part of the to-be-promoted set.
13725   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13726 
13727   // Make sure that this is a self-contained cluster of operations (which
13728   // is not quite the same thing as saying that everything has only one
13729   // use).
13730   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13731     if (isa<ConstantSDNode>(Inputs[i]))
13732       continue;
13733 
13734     for (SDNode *User : Inputs[i].getNode()->uses()) {
13735       if (User != N && !Visited.count(User))
13736         return SDValue();
13737 
13738       // If we're going to promote the non-output-value operand(s) or SELECT or
13739       // SELECT_CC, record them for truncation.
13740       if (User->getOpcode() == ISD::SELECT) {
13741         if (User->getOperand(0) == Inputs[i])
13742           SelectTruncOp[0].insert(std::make_pair(User,
13743                                     User->getOperand(0).getValueType()));
13744       } else if (User->getOpcode() == ISD::SELECT_CC) {
13745         if (User->getOperand(0) == Inputs[i])
13746           SelectTruncOp[0].insert(std::make_pair(User,
13747                                     User->getOperand(0).getValueType()));
13748         if (User->getOperand(1) == Inputs[i])
13749           SelectTruncOp[1].insert(std::make_pair(User,
13750                                     User->getOperand(1).getValueType()));
13751       }
13752     }
13753   }
13754 
13755   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13756     for (SDNode *User : PromOps[i].getNode()->uses()) {
13757       if (User != N && !Visited.count(User))
13758         return SDValue();
13759 
13760       // If we're going to promote the non-output-value operand(s) or SELECT or
13761       // SELECT_CC, record them for truncation.
13762       if (User->getOpcode() == ISD::SELECT) {
13763         if (User->getOperand(0) == PromOps[i])
13764           SelectTruncOp[0].insert(std::make_pair(User,
13765                                     User->getOperand(0).getValueType()));
13766       } else if (User->getOpcode() == ISD::SELECT_CC) {
13767         if (User->getOperand(0) == PromOps[i])
13768           SelectTruncOp[0].insert(std::make_pair(User,
13769                                     User->getOperand(0).getValueType()));
13770         if (User->getOperand(1) == PromOps[i])
13771           SelectTruncOp[1].insert(std::make_pair(User,
13772                                     User->getOperand(1).getValueType()));
13773       }
13774     }
13775   }
13776 
13777   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13778   bool ReallyNeedsExt = false;
13779   if (N->getOpcode() != ISD::ANY_EXTEND) {
13780     // If all of the inputs are not already sign/zero extended, then
13781     // we'll still need to do that at the end.
13782     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13783       if (isa<ConstantSDNode>(Inputs[i]))
13784         continue;
13785 
13786       unsigned OpBits =
13787         Inputs[i].getOperand(0).getValueSizeInBits();
13788       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13789 
13790       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13791            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13792                                   APInt::getHighBitsSet(OpBits,
13793                                                         OpBits-PromBits))) ||
13794           (N->getOpcode() == ISD::SIGN_EXTEND &&
13795            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13796              (OpBits-(PromBits-1)))) {
13797         ReallyNeedsExt = true;
13798         break;
13799       }
13800     }
13801   }
13802 
13803   // Replace all inputs, either with the truncation operand, or a
13804   // truncation or extension to the final output type.
13805   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13806     // Constant inputs need to be replaced with the to-be-promoted nodes that
13807     // use them because they might have users outside of the cluster of
13808     // promoted nodes.
13809     if (isa<ConstantSDNode>(Inputs[i]))
13810       continue;
13811 
13812     SDValue InSrc = Inputs[i].getOperand(0);
13813     if (Inputs[i].getValueType() == N->getValueType(0))
13814       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13815     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13816       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13817         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13818     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13819       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13820         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13821     else
13822       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13823         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13824   }
13825 
13826   std::list<HandleSDNode> PromOpHandles;
13827   for (auto &PromOp : PromOps)
13828     PromOpHandles.emplace_back(PromOp);
13829 
13830   // Replace all operations (these are all the same, but have a different
13831   // (promoted) return type). DAG.getNode will validate that the types of
13832   // a binary operator match, so go through the list in reverse so that
13833   // we've likely promoted both operands first.
13834   while (!PromOpHandles.empty()) {
13835     SDValue PromOp = PromOpHandles.back().getValue();
13836     PromOpHandles.pop_back();
13837 
13838     unsigned C;
13839     switch (PromOp.getOpcode()) {
13840     default:             C = 0; break;
13841     case ISD::SELECT:    C = 1; break;
13842     case ISD::SELECT_CC: C = 2; break;
13843     }
13844 
13845     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13846          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13847         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13848          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13849       // The to-be-promoted operands of this node have not yet been
13850       // promoted (this should be rare because we're going through the
13851       // list backward, but if one of the operands has several users in
13852       // this cluster of to-be-promoted nodes, it is possible).
13853       PromOpHandles.emplace_front(PromOp);
13854       continue;
13855     }
13856 
13857     // For SELECT and SELECT_CC nodes, we do a similar check for any
13858     // to-be-promoted comparison inputs.
13859     if (PromOp.getOpcode() == ISD::SELECT ||
13860         PromOp.getOpcode() == ISD::SELECT_CC) {
13861       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13862            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13863           (SelectTruncOp[1].count(PromOp.getNode()) &&
13864            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13865         PromOpHandles.emplace_front(PromOp);
13866         continue;
13867       }
13868     }
13869 
13870     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13871                                 PromOp.getNode()->op_end());
13872 
13873     // If this node has constant inputs, then they'll need to be promoted here.
13874     for (unsigned i = 0; i < 2; ++i) {
13875       if (!isa<ConstantSDNode>(Ops[C+i]))
13876         continue;
13877       if (Ops[C+i].getValueType() == N->getValueType(0))
13878         continue;
13879 
13880       if (N->getOpcode() == ISD::SIGN_EXTEND)
13881         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13882       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13883         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13884       else
13885         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13886     }
13887 
13888     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13889     // truncate them again to the original value type.
13890     if (PromOp.getOpcode() == ISD::SELECT ||
13891         PromOp.getOpcode() == ISD::SELECT_CC) {
13892       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13893       if (SI0 != SelectTruncOp[0].end())
13894         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13895       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13896       if (SI1 != SelectTruncOp[1].end())
13897         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13898     }
13899 
13900     DAG.ReplaceAllUsesOfValueWith(PromOp,
13901       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13902   }
13903 
13904   // Now we're left with the initial extension itself.
13905   if (!ReallyNeedsExt)
13906     return N->getOperand(0);
13907 
13908   // To zero extend, just mask off everything except for the first bit (in the
13909   // i1 case).
13910   if (N->getOpcode() == ISD::ZERO_EXTEND)
13911     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13912                        DAG.getConstant(APInt::getLowBitsSet(
13913                                          N->getValueSizeInBits(0), PromBits),
13914                                        dl, N->getValueType(0)));
13915 
13916   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13917          "Invalid extension type");
13918   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13919   SDValue ShiftCst =
13920       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13921   return DAG.getNode(
13922       ISD::SRA, dl, N->getValueType(0),
13923       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13924       ShiftCst);
13925 }
13926 
13927 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13928                                         DAGCombinerInfo &DCI) const {
13929   assert(N->getOpcode() == ISD::SETCC &&
13930          "Should be called with a SETCC node");
13931 
13932   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13933   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13934     SDValue LHS = N->getOperand(0);
13935     SDValue RHS = N->getOperand(1);
13936 
13937     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13938     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13939         LHS.hasOneUse())
13940       std::swap(LHS, RHS);
13941 
13942     // x == 0-y --> x+y == 0
13943     // x != 0-y --> x+y != 0
13944     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13945         RHS.hasOneUse()) {
13946       SDLoc DL(N);
13947       SelectionDAG &DAG = DCI.DAG;
13948       EVT VT = N->getValueType(0);
13949       EVT OpVT = LHS.getValueType();
13950       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13951       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13952     }
13953   }
13954 
13955   return DAGCombineTruncBoolExt(N, DCI);
13956 }
13957 
13958 // Is this an extending load from an f32 to an f64?
13959 static bool isFPExtLoad(SDValue Op) {
13960   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13961     return LD->getExtensionType() == ISD::EXTLOAD &&
13962       Op.getValueType() == MVT::f64;
13963   return false;
13964 }
13965 
13966 /// Reduces the number of fp-to-int conversion when building a vector.
13967 ///
13968 /// If this vector is built out of floating to integer conversions,
13969 /// transform it to a vector built out of floating point values followed by a
13970 /// single floating to integer conversion of the vector.
13971 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13972 /// becomes (fptosi (build_vector ($A, $B, ...)))
13973 SDValue PPCTargetLowering::
13974 combineElementTruncationToVectorTruncation(SDNode *N,
13975                                            DAGCombinerInfo &DCI) const {
13976   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13977          "Should be called with a BUILD_VECTOR node");
13978 
13979   SelectionDAG &DAG = DCI.DAG;
13980   SDLoc dl(N);
13981 
13982   SDValue FirstInput = N->getOperand(0);
13983   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13984          "The input operand must be an fp-to-int conversion.");
13985 
13986   // This combine happens after legalization so the fp_to_[su]i nodes are
13987   // already converted to PPCSISD nodes.
13988   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13989   if (FirstConversion == PPCISD::FCTIDZ ||
13990       FirstConversion == PPCISD::FCTIDUZ ||
13991       FirstConversion == PPCISD::FCTIWZ ||
13992       FirstConversion == PPCISD::FCTIWUZ) {
13993     bool IsSplat = true;
13994     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13995       FirstConversion == PPCISD::FCTIWUZ;
13996     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13997     SmallVector<SDValue, 4> Ops;
13998     EVT TargetVT = N->getValueType(0);
13999     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14000       SDValue NextOp = N->getOperand(i);
14001       if (NextOp.getOpcode() != PPCISD::MFVSR)
14002         return SDValue();
14003       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
14004       if (NextConversion != FirstConversion)
14005         return SDValue();
14006       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
14007       // This is not valid if the input was originally double precision. It is
14008       // also not profitable to do unless this is an extending load in which
14009       // case doing this combine will allow us to combine consecutive loads.
14010       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
14011         return SDValue();
14012       if (N->getOperand(i) != FirstInput)
14013         IsSplat = false;
14014     }
14015 
14016     // If this is a splat, we leave it as-is since there will be only a single
14017     // fp-to-int conversion followed by a splat of the integer. This is better
14018     // for 32-bit and smaller ints and neutral for 64-bit ints.
14019     if (IsSplat)
14020       return SDValue();
14021 
14022     // Now that we know we have the right type of node, get its operands
14023     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14024       SDValue In = N->getOperand(i).getOperand(0);
14025       if (Is32Bit) {
14026         // For 32-bit values, we need to add an FP_ROUND node (if we made it
14027         // here, we know that all inputs are extending loads so this is safe).
14028         if (In.isUndef())
14029           Ops.push_back(DAG.getUNDEF(SrcVT));
14030         else {
14031           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
14032                                       MVT::f32, In.getOperand(0),
14033                                       DAG.getIntPtrConstant(1, dl));
14034           Ops.push_back(Trunc);
14035         }
14036       } else
14037         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
14038     }
14039 
14040     unsigned Opcode;
14041     if (FirstConversion == PPCISD::FCTIDZ ||
14042         FirstConversion == PPCISD::FCTIWZ)
14043       Opcode = ISD::FP_TO_SINT;
14044     else
14045       Opcode = ISD::FP_TO_UINT;
14046 
14047     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
14048     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
14049     return DAG.getNode(Opcode, dl, TargetVT, BV);
14050   }
14051   return SDValue();
14052 }
14053 
14054 /// Reduce the number of loads when building a vector.
14055 ///
14056 /// Building a vector out of multiple loads can be converted to a load
14057 /// of the vector type if the loads are consecutive. If the loads are
14058 /// consecutive but in descending order, a shuffle is added at the end
14059 /// to reorder the vector.
14060 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
14061   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14062          "Should be called with a BUILD_VECTOR node");
14063 
14064   SDLoc dl(N);
14065 
14066   // Return early for non byte-sized type, as they can't be consecutive.
14067   if (!N->getValueType(0).getVectorElementType().isByteSized())
14068     return SDValue();
14069 
14070   bool InputsAreConsecutiveLoads = true;
14071   bool InputsAreReverseConsecutive = true;
14072   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14073   SDValue FirstInput = N->getOperand(0);
14074   bool IsRoundOfExtLoad = false;
14075 
14076   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14077       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14078     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
14079     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
14080   }
14081   // Not a build vector of (possibly fp_rounded) loads.
14082   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14083       N->getNumOperands() == 1)
14084     return SDValue();
14085 
14086   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14087     // If any inputs are fp_round(extload), they all must be.
14088     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14089       return SDValue();
14090 
14091     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14092       N->getOperand(i);
14093     if (NextInput.getOpcode() != ISD::LOAD)
14094       return SDValue();
14095 
14096     SDValue PreviousInput =
14097       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14098     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
14099     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
14100 
14101     // If any inputs are fp_round(extload), they all must be.
14102     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14103       return SDValue();
14104 
14105     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
14106       InputsAreConsecutiveLoads = false;
14107     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14108       InputsAreReverseConsecutive = false;
14109 
14110     // Exit early if the loads are neither consecutive nor reverse consecutive.
14111     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14112       return SDValue();
14113   }
14114 
14115   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14116          "The loads cannot be both consecutive and reverse consecutive.");
14117 
14118   SDValue FirstLoadOp =
14119     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14120   SDValue LastLoadOp =
14121     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14122                        N->getOperand(N->getNumOperands()-1);
14123 
14124   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14125   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14126   if (InputsAreConsecutiveLoads) {
14127     assert(LD1 && "Input needs to be a LoadSDNode.");
14128     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14129                        LD1->getBasePtr(), LD1->getPointerInfo(),
14130                        LD1->getAlignment());
14131   }
14132   if (InputsAreReverseConsecutive) {
14133     assert(LDL && "Input needs to be a LoadSDNode.");
14134     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14135                                LDL->getBasePtr(), LDL->getPointerInfo(),
14136                                LDL->getAlignment());
14137     SmallVector<int, 16> Ops;
14138     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14139       Ops.push_back(i);
14140 
14141     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14142                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14143   }
14144   return SDValue();
14145 }
14146 
14147 // This function adds the required vector_shuffle needed to get
14148 // the elements of the vector extract in the correct position
14149 // as specified by the CorrectElems encoding.
14150 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14151                                       SDValue Input, uint64_t Elems,
14152                                       uint64_t CorrectElems) {
14153   SDLoc dl(N);
14154 
14155   unsigned NumElems = Input.getValueType().getVectorNumElements();
14156   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14157 
14158   // Knowing the element indices being extracted from the original
14159   // vector and the order in which they're being inserted, just put
14160   // them at element indices required for the instruction.
14161   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14162     if (DAG.getDataLayout().isLittleEndian())
14163       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14164     else
14165       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14166     CorrectElems = CorrectElems >> 8;
14167     Elems = Elems >> 8;
14168   }
14169 
14170   SDValue Shuffle =
14171       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14172                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14173 
14174   EVT VT = N->getValueType(0);
14175   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14176 
14177   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14178                                Input.getValueType().getVectorElementType(),
14179                                VT.getVectorNumElements());
14180   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14181                      DAG.getValueType(ExtVT));
14182 }
14183 
14184 // Look for build vector patterns where input operands come from sign
14185 // extended vector_extract elements of specific indices. If the correct indices
14186 // aren't used, add a vector shuffle to fix up the indices and create
14187 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14188 // during instruction selection.
14189 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14190   // This array encodes the indices that the vector sign extend instructions
14191   // extract from when extending from one type to another for both BE and LE.
14192   // The right nibble of each byte corresponds to the LE incides.
14193   // and the left nibble of each byte corresponds to the BE incides.
14194   // For example: 0x3074B8FC  byte->word
14195   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14196   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14197   // For example: 0x000070F8  byte->double word
14198   // For LE: the allowed indices are: 0x0,0x8
14199   // For BE: the allowed indices are: 0x7,0xF
14200   uint64_t TargetElems[] = {
14201       0x3074B8FC, // b->w
14202       0x000070F8, // b->d
14203       0x10325476, // h->w
14204       0x00003074, // h->d
14205       0x00001032, // w->d
14206   };
14207 
14208   uint64_t Elems = 0;
14209   int Index;
14210   SDValue Input;
14211 
14212   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14213     if (!Op)
14214       return false;
14215     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14216         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14217       return false;
14218 
14219     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14220     // of the right width.
14221     SDValue Extract = Op.getOperand(0);
14222     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14223       Extract = Extract.getOperand(0);
14224     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14225       return false;
14226 
14227     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14228     if (!ExtOp)
14229       return false;
14230 
14231     Index = ExtOp->getZExtValue();
14232     if (Input && Input != Extract.getOperand(0))
14233       return false;
14234 
14235     if (!Input)
14236       Input = Extract.getOperand(0);
14237 
14238     Elems = Elems << 8;
14239     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14240     Elems |= Index;
14241 
14242     return true;
14243   };
14244 
14245   // If the build vector operands aren't sign extended vector extracts,
14246   // of the same input vector, then return.
14247   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14248     if (!isSExtOfVecExtract(N->getOperand(i))) {
14249       return SDValue();
14250     }
14251   }
14252 
14253   // If the vector extract indicies are not correct, add the appropriate
14254   // vector_shuffle.
14255   int TgtElemArrayIdx;
14256   int InputSize = Input.getValueType().getScalarSizeInBits();
14257   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14258   if (InputSize + OutputSize == 40)
14259     TgtElemArrayIdx = 0;
14260   else if (InputSize + OutputSize == 72)
14261     TgtElemArrayIdx = 1;
14262   else if (InputSize + OutputSize == 48)
14263     TgtElemArrayIdx = 2;
14264   else if (InputSize + OutputSize == 80)
14265     TgtElemArrayIdx = 3;
14266   else if (InputSize + OutputSize == 96)
14267     TgtElemArrayIdx = 4;
14268   else
14269     return SDValue();
14270 
14271   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14272   CorrectElems = DAG.getDataLayout().isLittleEndian()
14273                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14274                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14275   if (Elems != CorrectElems) {
14276     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14277   }
14278 
14279   // Regular lowering will catch cases where a shuffle is not needed.
14280   return SDValue();
14281 }
14282 
14283 // Look for the pattern of a load from a narrow width to i128, feeding
14284 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14285 // (LXVRZX). This node represents a zero extending load that will be matched
14286 // to the Load VSX Vector Rightmost instructions.
14287 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14288   SDLoc DL(N);
14289 
14290   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14291   if (N->getValueType(0) != MVT::v1i128)
14292     return SDValue();
14293 
14294   SDValue Operand = N->getOperand(0);
14295   // Proceed with the transformation if the operand to the BUILD_VECTOR
14296   // is a load instruction.
14297   if (Operand.getOpcode() != ISD::LOAD)
14298     return SDValue();
14299 
14300   auto *LD = cast<LoadSDNode>(Operand);
14301   EVT MemoryType = LD->getMemoryVT();
14302 
14303   // This transformation is only valid if the we are loading either a byte,
14304   // halfword, word, or doubleword.
14305   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14306                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14307 
14308   // Ensure that the load from the narrow width is being zero extended to i128.
14309   if (!ValidLDType ||
14310       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14311        LD->getExtensionType() != ISD::EXTLOAD))
14312     return SDValue();
14313 
14314   SDValue LoadOps[] = {
14315       LD->getChain(), LD->getBasePtr(),
14316       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14317 
14318   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14319                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14320                                  LoadOps, MemoryType, LD->getMemOperand());
14321 }
14322 
14323 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14324                                                  DAGCombinerInfo &DCI) const {
14325   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14326          "Should be called with a BUILD_VECTOR node");
14327 
14328   SelectionDAG &DAG = DCI.DAG;
14329   SDLoc dl(N);
14330 
14331   if (!Subtarget.hasVSX())
14332     return SDValue();
14333 
14334   // The target independent DAG combiner will leave a build_vector of
14335   // float-to-int conversions intact. We can generate MUCH better code for
14336   // a float-to-int conversion of a vector of floats.
14337   SDValue FirstInput = N->getOperand(0);
14338   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14339     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14340     if (Reduced)
14341       return Reduced;
14342   }
14343 
14344   // If we're building a vector out of consecutive loads, just load that
14345   // vector type.
14346   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14347   if (Reduced)
14348     return Reduced;
14349 
14350   // If we're building a vector out of extended elements from another vector
14351   // we have P9 vector integer extend instructions. The code assumes legal
14352   // input types (i.e. it can't handle things like v4i16) so do not run before
14353   // legalization.
14354   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14355     Reduced = combineBVOfVecSExt(N, DAG);
14356     if (Reduced)
14357       return Reduced;
14358   }
14359 
14360   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14361   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14362   // is a load from <valid narrow width> to i128.
14363   if (Subtarget.isISA3_1()) {
14364     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14365     if (BVOfZLoad)
14366       return BVOfZLoad;
14367   }
14368 
14369   if (N->getValueType(0) != MVT::v2f64)
14370     return SDValue();
14371 
14372   // Looking for:
14373   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14374   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14375       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14376     return SDValue();
14377   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14378       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14379     return SDValue();
14380   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14381     return SDValue();
14382 
14383   SDValue Ext1 = FirstInput.getOperand(0);
14384   SDValue Ext2 = N->getOperand(1).getOperand(0);
14385   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14386      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14387     return SDValue();
14388 
14389   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14390   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14391   if (!Ext1Op || !Ext2Op)
14392     return SDValue();
14393   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14394       Ext1.getOperand(0) != Ext2.getOperand(0))
14395     return SDValue();
14396 
14397   int FirstElem = Ext1Op->getZExtValue();
14398   int SecondElem = Ext2Op->getZExtValue();
14399   int SubvecIdx;
14400   if (FirstElem == 0 && SecondElem == 1)
14401     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14402   else if (FirstElem == 2 && SecondElem == 3)
14403     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14404   else
14405     return SDValue();
14406 
14407   SDValue SrcVec = Ext1.getOperand(0);
14408   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14409     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14410   return DAG.getNode(NodeType, dl, MVT::v2f64,
14411                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14412 }
14413 
14414 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14415                                               DAGCombinerInfo &DCI) const {
14416   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14417           N->getOpcode() == ISD::UINT_TO_FP) &&
14418          "Need an int -> FP conversion node here");
14419 
14420   if (useSoftFloat() || !Subtarget.has64BitSupport())
14421     return SDValue();
14422 
14423   SelectionDAG &DAG = DCI.DAG;
14424   SDLoc dl(N);
14425   SDValue Op(N, 0);
14426 
14427   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14428   // from the hardware.
14429   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14430     return SDValue();
14431   if (!Op.getOperand(0).getValueType().isSimple())
14432     return SDValue();
14433   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14434       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14435     return SDValue();
14436 
14437   SDValue FirstOperand(Op.getOperand(0));
14438   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14439     (FirstOperand.getValueType() == MVT::i8 ||
14440      FirstOperand.getValueType() == MVT::i16);
14441   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14442     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14443     bool DstDouble = Op.getValueType() == MVT::f64;
14444     unsigned ConvOp = Signed ?
14445       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14446       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14447     SDValue WidthConst =
14448       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14449                             dl, false);
14450     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14451     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14452     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14453                                          DAG.getVTList(MVT::f64, MVT::Other),
14454                                          Ops, MVT::i8, LDN->getMemOperand());
14455 
14456     // For signed conversion, we need to sign-extend the value in the VSR
14457     if (Signed) {
14458       SDValue ExtOps[] = { Ld, WidthConst };
14459       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14460       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14461     } else
14462       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14463   }
14464 
14465 
14466   // For i32 intermediate values, unfortunately, the conversion functions
14467   // leave the upper 32 bits of the value are undefined. Within the set of
14468   // scalar instructions, we have no method for zero- or sign-extending the
14469   // value. Thus, we cannot handle i32 intermediate values here.
14470   if (Op.getOperand(0).getValueType() == MVT::i32)
14471     return SDValue();
14472 
14473   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14474          "UINT_TO_FP is supported only with FPCVT");
14475 
14476   // If we have FCFIDS, then use it when converting to single-precision.
14477   // Otherwise, convert to double-precision and then round.
14478   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14479                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14480                                                             : PPCISD::FCFIDS)
14481                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14482                                                             : PPCISD::FCFID);
14483   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14484                   ? MVT::f32
14485                   : MVT::f64;
14486 
14487   // If we're converting from a float, to an int, and back to a float again,
14488   // then we don't need the store/load pair at all.
14489   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14490        Subtarget.hasFPCVT()) ||
14491       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14492     SDValue Src = Op.getOperand(0).getOperand(0);
14493     if (Src.getValueType() == MVT::f32) {
14494       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14495       DCI.AddToWorklist(Src.getNode());
14496     } else if (Src.getValueType() != MVT::f64) {
14497       // Make sure that we don't pick up a ppc_fp128 source value.
14498       return SDValue();
14499     }
14500 
14501     unsigned FCTOp =
14502       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14503                                                         PPCISD::FCTIDUZ;
14504 
14505     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14506     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14507 
14508     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14509       FP = DAG.getNode(ISD::FP_ROUND, dl,
14510                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14511       DCI.AddToWorklist(FP.getNode());
14512     }
14513 
14514     return FP;
14515   }
14516 
14517   return SDValue();
14518 }
14519 
14520 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14521 // builtins) into loads with swaps.
14522 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14523                                               DAGCombinerInfo &DCI) const {
14524   SelectionDAG &DAG = DCI.DAG;
14525   SDLoc dl(N);
14526   SDValue Chain;
14527   SDValue Base;
14528   MachineMemOperand *MMO;
14529 
14530   switch (N->getOpcode()) {
14531   default:
14532     llvm_unreachable("Unexpected opcode for little endian VSX load");
14533   case ISD::LOAD: {
14534     LoadSDNode *LD = cast<LoadSDNode>(N);
14535     Chain = LD->getChain();
14536     Base = LD->getBasePtr();
14537     MMO = LD->getMemOperand();
14538     // If the MMO suggests this isn't a load of a full vector, leave
14539     // things alone.  For a built-in, we have to make the change for
14540     // correctness, so if there is a size problem that will be a bug.
14541     if (MMO->getSize() < 16)
14542       return SDValue();
14543     break;
14544   }
14545   case ISD::INTRINSIC_W_CHAIN: {
14546     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14547     Chain = Intrin->getChain();
14548     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14549     // us what we want. Get operand 2 instead.
14550     Base = Intrin->getOperand(2);
14551     MMO = Intrin->getMemOperand();
14552     break;
14553   }
14554   }
14555 
14556   MVT VecTy = N->getValueType(0).getSimpleVT();
14557 
14558   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14559   // aligned and the type is a vector with elements up to 4 bytes
14560   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14561       VecTy.getScalarSizeInBits() <= 32) {
14562     return SDValue();
14563   }
14564 
14565   SDValue LoadOps[] = { Chain, Base };
14566   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14567                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14568                                          LoadOps, MVT::v2f64, MMO);
14569 
14570   DCI.AddToWorklist(Load.getNode());
14571   Chain = Load.getValue(1);
14572   SDValue Swap = DAG.getNode(
14573       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14574   DCI.AddToWorklist(Swap.getNode());
14575 
14576   // Add a bitcast if the resulting load type doesn't match v2f64.
14577   if (VecTy != MVT::v2f64) {
14578     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14579     DCI.AddToWorklist(N.getNode());
14580     // Package {bitcast value, swap's chain} to match Load's shape.
14581     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14582                        N, Swap.getValue(1));
14583   }
14584 
14585   return Swap;
14586 }
14587 
14588 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14589 // builtins) into stores with swaps.
14590 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14591                                                DAGCombinerInfo &DCI) const {
14592   SelectionDAG &DAG = DCI.DAG;
14593   SDLoc dl(N);
14594   SDValue Chain;
14595   SDValue Base;
14596   unsigned SrcOpnd;
14597   MachineMemOperand *MMO;
14598 
14599   switch (N->getOpcode()) {
14600   default:
14601     llvm_unreachable("Unexpected opcode for little endian VSX store");
14602   case ISD::STORE: {
14603     StoreSDNode *ST = cast<StoreSDNode>(N);
14604     Chain = ST->getChain();
14605     Base = ST->getBasePtr();
14606     MMO = ST->getMemOperand();
14607     SrcOpnd = 1;
14608     // If the MMO suggests this isn't a store of a full vector, leave
14609     // things alone.  For a built-in, we have to make the change for
14610     // correctness, so if there is a size problem that will be a bug.
14611     if (MMO->getSize() < 16)
14612       return SDValue();
14613     break;
14614   }
14615   case ISD::INTRINSIC_VOID: {
14616     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14617     Chain = Intrin->getChain();
14618     // Intrin->getBasePtr() oddly does not get what we want.
14619     Base = Intrin->getOperand(3);
14620     MMO = Intrin->getMemOperand();
14621     SrcOpnd = 2;
14622     break;
14623   }
14624   }
14625 
14626   SDValue Src = N->getOperand(SrcOpnd);
14627   MVT VecTy = Src.getValueType().getSimpleVT();
14628 
14629   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14630   // aligned and the type is a vector with elements up to 4 bytes
14631   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14632       VecTy.getScalarSizeInBits() <= 32) {
14633     return SDValue();
14634   }
14635 
14636   // All stores are done as v2f64 and possible bit cast.
14637   if (VecTy != MVT::v2f64) {
14638     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14639     DCI.AddToWorklist(Src.getNode());
14640   }
14641 
14642   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14643                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14644   DCI.AddToWorklist(Swap.getNode());
14645   Chain = Swap.getValue(1);
14646   SDValue StoreOps[] = { Chain, Swap, Base };
14647   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14648                                           DAG.getVTList(MVT::Other),
14649                                           StoreOps, VecTy, MMO);
14650   DCI.AddToWorklist(Store.getNode());
14651   return Store;
14652 }
14653 
14654 // Handle DAG combine for STORE (FP_TO_INT F).
14655 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14656                                                DAGCombinerInfo &DCI) const {
14657 
14658   SelectionDAG &DAG = DCI.DAG;
14659   SDLoc dl(N);
14660   unsigned Opcode = N->getOperand(1).getOpcode();
14661 
14662   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14663          && "Not a FP_TO_INT Instruction!");
14664 
14665   SDValue Val = N->getOperand(1).getOperand(0);
14666   EVT Op1VT = N->getOperand(1).getValueType();
14667   EVT ResVT = Val.getValueType();
14668 
14669   if (!isTypeLegal(ResVT))
14670     return SDValue();
14671 
14672   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14673   bool ValidTypeForStoreFltAsInt =
14674         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14675          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14676 
14677   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14678     return SDValue();
14679 
14680   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14681       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14682     return SDValue();
14683 
14684   // Extend f32 values to f64
14685   if (ResVT.getScalarSizeInBits() == 32) {
14686     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14687     DCI.AddToWorklist(Val.getNode());
14688   }
14689 
14690   // Set signed or unsigned conversion opcode.
14691   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14692                           PPCISD::FP_TO_SINT_IN_VSR :
14693                           PPCISD::FP_TO_UINT_IN_VSR;
14694 
14695   Val = DAG.getNode(ConvOpcode,
14696                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14697   DCI.AddToWorklist(Val.getNode());
14698 
14699   // Set number of bytes being converted.
14700   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14701   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14702                     DAG.getIntPtrConstant(ByteSize, dl, false),
14703                     DAG.getValueType(Op1VT) };
14704 
14705   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14706           DAG.getVTList(MVT::Other), Ops,
14707           cast<StoreSDNode>(N)->getMemoryVT(),
14708           cast<StoreSDNode>(N)->getMemOperand());
14709 
14710   DCI.AddToWorklist(Val.getNode());
14711   return Val;
14712 }
14713 
14714 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14715   // Check that the source of the element keeps flipping
14716   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14717   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14718   for (int i = 1, e = Mask.size(); i < e; i++) {
14719     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14720       return false;
14721     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14722       return false;
14723     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14724   }
14725   return true;
14726 }
14727 
14728 static bool isSplatBV(SDValue Op) {
14729   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14730     return false;
14731   SDValue FirstOp;
14732 
14733   // Find first non-undef input.
14734   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14735     FirstOp = Op.getOperand(i);
14736     if (!FirstOp.isUndef())
14737       break;
14738   }
14739 
14740   // All inputs are undef or the same as the first non-undef input.
14741   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14742     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14743       return false;
14744   return true;
14745 }
14746 
14747 static SDValue isScalarToVec(SDValue Op) {
14748   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14749     return Op;
14750   if (Op.getOpcode() != ISD::BITCAST)
14751     return SDValue();
14752   Op = Op.getOperand(0);
14753   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14754     return Op;
14755   return SDValue();
14756 }
14757 
14758 // Fix up the shuffle mask to account for the fact that the result of
14759 // scalar_to_vector is not in lane zero. This just takes all values in
14760 // the ranges specified by the min/max indices and adds the number of
14761 // elements required to ensure each element comes from the respective
14762 // position in the valid lane.
14763 // On little endian, that's just the corresponding element in the other
14764 // half of the vector. On big endian, it is in the same half but right
14765 // justified rather than left justified in that half.
14766 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14767                                             int LHSMaxIdx, int RHSMinIdx,
14768                                             int RHSMaxIdx, int HalfVec,
14769                                             unsigned ValidLaneWidth,
14770                                             const PPCSubtarget &Subtarget) {
14771   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14772     int Idx = ShuffV[i];
14773     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14774       ShuffV[i] +=
14775           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14776   }
14777 }
14778 
14779 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14780 // the original is:
14781 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14782 // In such a case, just change the shuffle mask to extract the element
14783 // from the permuted index.
14784 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14785                                const PPCSubtarget &Subtarget) {
14786   SDLoc dl(OrigSToV);
14787   EVT VT = OrigSToV.getValueType();
14788   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14789          "Expecting a SCALAR_TO_VECTOR here");
14790   SDValue Input = OrigSToV.getOperand(0);
14791 
14792   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14793     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14794     SDValue OrigVector = Input.getOperand(0);
14795 
14796     // Can't handle non-const element indices or different vector types
14797     // for the input to the extract and the output of the scalar_to_vector.
14798     if (Idx && VT == OrigVector.getValueType()) {
14799       unsigned NumElts = VT.getVectorNumElements();
14800       assert(
14801           NumElts > 1 &&
14802           "Cannot produce a permuted scalar_to_vector for one element vector");
14803       SmallVector<int, 16> NewMask(NumElts, -1);
14804       unsigned ResultInElt = NumElts / 2;
14805       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14806       NewMask[ResultInElt] = Idx->getZExtValue();
14807       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14808     }
14809   }
14810   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14811                      OrigSToV.getOperand(0));
14812 }
14813 
14814 // On little endian subtargets, combine shuffles such as:
14815 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14816 // into:
14817 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14818 // because the latter can be matched to a single instruction merge.
14819 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14820 // to put the value into element zero. Adjust the shuffle mask so that the
14821 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14822 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14823 // nodes with elements smaller than doubleword because all the ways
14824 // of getting scalar data into a vector register put the value in the
14825 // rightmost element of the left half of the vector.
14826 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14827                                                 SelectionDAG &DAG) const {
14828   SDValue LHS = SVN->getOperand(0);
14829   SDValue RHS = SVN->getOperand(1);
14830   auto Mask = SVN->getMask();
14831   int NumElts = LHS.getValueType().getVectorNumElements();
14832   SDValue Res(SVN, 0);
14833   SDLoc dl(SVN);
14834   bool IsLittleEndian = Subtarget.isLittleEndian();
14835 
14836   // On big endian targets this is only useful for subtargets with direct moves.
14837   // On little endian targets it would be useful for all subtargets with VSX.
14838   // However adding special handling for LE subtargets without direct moves
14839   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14840   // which includes direct moves.
14841   if (!Subtarget.hasDirectMove())
14842     return Res;
14843 
14844   // If this is not a shuffle of a shuffle and the first element comes from
14845   // the second vector, canonicalize to the commuted form. This will make it
14846   // more likely to match one of the single instruction patterns.
14847   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14848       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14849     std::swap(LHS, RHS);
14850     Res = DAG.getCommutedVectorShuffle(*SVN);
14851     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14852   }
14853 
14854   // Adjust the shuffle mask if either input vector comes from a
14855   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14856   // form (to prevent the need for a swap).
14857   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14858   SDValue SToVLHS = isScalarToVec(LHS);
14859   SDValue SToVRHS = isScalarToVec(RHS);
14860   if (SToVLHS || SToVRHS) {
14861     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14862                             : SToVRHS.getValueType().getVectorNumElements();
14863     int NumEltsOut = ShuffV.size();
14864     // The width of the "valid lane" (i.e. the lane that contains the value that
14865     // is vectorized) needs to be expressed in terms of the number of elements
14866     // of the shuffle. It is thereby the ratio of the values before and after
14867     // any bitcast.
14868     unsigned ValidLaneWidth =
14869         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14870                       LHS.getValueType().getScalarSizeInBits()
14871                 : SToVRHS.getValueType().getScalarSizeInBits() /
14872                       RHS.getValueType().getScalarSizeInBits();
14873 
14874     // Initially assume that neither input is permuted. These will be adjusted
14875     // accordingly if either input is.
14876     int LHSMaxIdx = -1;
14877     int RHSMinIdx = -1;
14878     int RHSMaxIdx = -1;
14879     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14880 
14881     // Get the permuted scalar to vector nodes for the source(s) that come from
14882     // ISD::SCALAR_TO_VECTOR.
14883     // On big endian systems, this only makes sense for element sizes smaller
14884     // than 64 bits since for 64-bit elements, all instructions already put
14885     // the value into element zero. Since scalar size of LHS and RHS may differ
14886     // after isScalarToVec, this should be checked using their own sizes.
14887     if (SToVLHS) {
14888       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14889         return Res;
14890       // Set up the values for the shuffle vector fixup.
14891       LHSMaxIdx = NumEltsOut / NumEltsIn;
14892       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14893       if (SToVLHS.getValueType() != LHS.getValueType())
14894         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14895       LHS = SToVLHS;
14896     }
14897     if (SToVRHS) {
14898       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14899         return Res;
14900       RHSMinIdx = NumEltsOut;
14901       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14902       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14903       if (SToVRHS.getValueType() != RHS.getValueType())
14904         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14905       RHS = SToVRHS;
14906     }
14907 
14908     // Fix up the shuffle mask to reflect where the desired element actually is.
14909     // The minimum and maximum indices that correspond to element zero for both
14910     // the LHS and RHS are computed and will control which shuffle mask entries
14911     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14912     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14913     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14914                                     HalfVec, ValidLaneWidth, Subtarget);
14915     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14916 
14917     // We may have simplified away the shuffle. We won't be able to do anything
14918     // further with it here.
14919     if (!isa<ShuffleVectorSDNode>(Res))
14920       return Res;
14921     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14922   }
14923 
14924   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14925   // The common case after we commuted the shuffle is that the RHS is a splat
14926   // and we have elements coming in from the splat at indices that are not
14927   // conducive to using a merge.
14928   // Example:
14929   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14930   if (!isSplatBV(TheSplat))
14931     return Res;
14932 
14933   // We are looking for a mask such that all even elements are from
14934   // one vector and all odd elements from the other.
14935   if (!isAlternatingShuffMask(Mask, NumElts))
14936     return Res;
14937 
14938   // Adjust the mask so we are pulling in the same index from the splat
14939   // as the index from the interesting vector in consecutive elements.
14940   if (IsLittleEndian) {
14941     // Example (even elements from first vector):
14942     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14943     if (Mask[0] < NumElts)
14944       for (int i = 1, e = Mask.size(); i < e; i += 2)
14945         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14946     // Example (odd elements from first vector):
14947     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14948     else
14949       for (int i = 0, e = Mask.size(); i < e; i += 2)
14950         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14951   } else {
14952     // Example (even elements from first vector):
14953     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14954     if (Mask[0] < NumElts)
14955       for (int i = 0, e = Mask.size(); i < e; i += 2)
14956         ShuffV[i] = ShuffV[i + 1] - NumElts;
14957     // Example (odd elements from first vector):
14958     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14959     else
14960       for (int i = 1, e = Mask.size(); i < e; i += 2)
14961         ShuffV[i] = ShuffV[i - 1] - NumElts;
14962   }
14963 
14964   // If the RHS has undefs, we need to remove them since we may have created
14965   // a shuffle that adds those instead of the splat value.
14966   SDValue SplatVal =
14967       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14968   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14969 
14970   if (IsLittleEndian)
14971     RHS = TheSplat;
14972   else
14973     LHS = TheSplat;
14974   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14975 }
14976 
14977 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14978                                                 LSBaseSDNode *LSBase,
14979                                                 DAGCombinerInfo &DCI) const {
14980   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14981         "Not a reverse memop pattern!");
14982 
14983   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14984     auto Mask = SVN->getMask();
14985     int i = 0;
14986     auto I = Mask.rbegin();
14987     auto E = Mask.rend();
14988 
14989     for (; I != E; ++I) {
14990       if (*I != i)
14991         return false;
14992       i++;
14993     }
14994     return true;
14995   };
14996 
14997   SelectionDAG &DAG = DCI.DAG;
14998   EVT VT = SVN->getValueType(0);
14999 
15000   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
15001     return SDValue();
15002 
15003   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
15004   // See comment in PPCVSXSwapRemoval.cpp.
15005   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
15006   if (!Subtarget.hasP9Vector())
15007     return SDValue();
15008 
15009   if(!IsElementReverse(SVN))
15010     return SDValue();
15011 
15012   if (LSBase->getOpcode() == ISD::LOAD) {
15013     // If the load return value 0 has more than one user except the
15014     // shufflevector instruction, it is not profitable to replace the
15015     // shufflevector with a reverse load.
15016     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
15017          UI != UE; ++UI)
15018       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
15019         return SDValue();
15020 
15021     SDLoc dl(LSBase);
15022     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
15023     return DAG.getMemIntrinsicNode(
15024         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
15025         LSBase->getMemoryVT(), LSBase->getMemOperand());
15026   }
15027 
15028   if (LSBase->getOpcode() == ISD::STORE) {
15029     // If there are other uses of the shuffle, the swap cannot be avoided.
15030     // Forcing the use of an X-Form (since swapped stores only have
15031     // X-Forms) without removing the swap is unprofitable.
15032     if (!SVN->hasOneUse())
15033       return SDValue();
15034 
15035     SDLoc dl(LSBase);
15036     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
15037                           LSBase->getBasePtr()};
15038     return DAG.getMemIntrinsicNode(
15039         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
15040         LSBase->getMemoryVT(), LSBase->getMemOperand());
15041   }
15042 
15043   llvm_unreachable("Expected a load or store node here");
15044 }
15045 
15046 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
15047                                              DAGCombinerInfo &DCI) const {
15048   SelectionDAG &DAG = DCI.DAG;
15049   SDLoc dl(N);
15050   switch (N->getOpcode()) {
15051   default: break;
15052   case ISD::ADD:
15053     return combineADD(N, DCI);
15054   case ISD::SHL:
15055     return combineSHL(N, DCI);
15056   case ISD::SRA:
15057     return combineSRA(N, DCI);
15058   case ISD::SRL:
15059     return combineSRL(N, DCI);
15060   case ISD::MUL:
15061     return combineMUL(N, DCI);
15062   case ISD::FMA:
15063   case PPCISD::FNMSUB:
15064     return combineFMALike(N, DCI);
15065   case PPCISD::SHL:
15066     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
15067         return N->getOperand(0);
15068     break;
15069   case PPCISD::SRL:
15070     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15071         return N->getOperand(0);
15072     break;
15073   case PPCISD::SRA:
15074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15075       if (C->isZero() ||  //  0 >>s V -> 0.
15076           C->isAllOnes()) // -1 >>s V -> -1.
15077         return N->getOperand(0);
15078     }
15079     break;
15080   case ISD::SIGN_EXTEND:
15081   case ISD::ZERO_EXTEND:
15082   case ISD::ANY_EXTEND:
15083     return DAGCombineExtBoolTrunc(N, DCI);
15084   case ISD::TRUNCATE:
15085     return combineTRUNCATE(N, DCI);
15086   case ISD::SETCC:
15087     if (SDValue CSCC = combineSetCC(N, DCI))
15088       return CSCC;
15089     LLVM_FALLTHROUGH;
15090   case ISD::SELECT_CC:
15091     return DAGCombineTruncBoolExt(N, DCI);
15092   case ISD::SINT_TO_FP:
15093   case ISD::UINT_TO_FP:
15094     return combineFPToIntToFP(N, DCI);
15095   case ISD::VECTOR_SHUFFLE:
15096     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15097       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15098       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15099     }
15100     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15101   case ISD::STORE: {
15102 
15103     EVT Op1VT = N->getOperand(1).getValueType();
15104     unsigned Opcode = N->getOperand(1).getOpcode();
15105 
15106     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15107       SDValue Val= combineStoreFPToInt(N, DCI);
15108       if (Val)
15109         return Val;
15110     }
15111 
15112     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15113       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15114       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15115       if (Val)
15116         return Val;
15117     }
15118 
15119     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15120     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15121         N->getOperand(1).getNode()->hasOneUse() &&
15122         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15123          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15124 
15125       // STBRX can only handle simple types and it makes no sense to store less
15126       // two bytes in byte-reversed order.
15127       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15128       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15129         break;
15130 
15131       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15132       // Do an any-extend to 32-bits if this is a half-word input.
15133       if (BSwapOp.getValueType() == MVT::i16)
15134         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15135 
15136       // If the type of BSWAP operand is wider than stored memory width
15137       // it need to be shifted to the right side before STBRX.
15138       if (Op1VT.bitsGT(mVT)) {
15139         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15140         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15141                               DAG.getConstant(Shift, dl, MVT::i32));
15142         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15143         if (Op1VT == MVT::i64)
15144           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15145       }
15146 
15147       SDValue Ops[] = {
15148         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15149       };
15150       return
15151         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15152                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15153                                 cast<StoreSDNode>(N)->getMemOperand());
15154     }
15155 
15156     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15157     // So it can increase the chance of CSE constant construction.
15158     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15159         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15160       // Need to sign-extended to 64-bits to handle negative values.
15161       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15162       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15163                                     MemVT.getSizeInBits());
15164       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15165 
15166       // DAG.getTruncStore() can't be used here because it doesn't accept
15167       // the general (base + offset) addressing mode.
15168       // So we use UpdateNodeOperands and setTruncatingStore instead.
15169       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15170                              N->getOperand(3));
15171       cast<StoreSDNode>(N)->setTruncatingStore(true);
15172       return SDValue(N, 0);
15173     }
15174 
15175     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15176     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15177     if (Op1VT.isSimple()) {
15178       MVT StoreVT = Op1VT.getSimpleVT();
15179       if (Subtarget.needsSwapsForVSXMemOps() &&
15180           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15181            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15182         return expandVSXStoreForLE(N, DCI);
15183     }
15184     break;
15185   }
15186   case ISD::LOAD: {
15187     LoadSDNode *LD = cast<LoadSDNode>(N);
15188     EVT VT = LD->getValueType(0);
15189 
15190     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15191     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15192     if (VT.isSimple()) {
15193       MVT LoadVT = VT.getSimpleVT();
15194       if (Subtarget.needsSwapsForVSXMemOps() &&
15195           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15196            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15197         return expandVSXLoadForLE(N, DCI);
15198     }
15199 
15200     // We sometimes end up with a 64-bit integer load, from which we extract
15201     // two single-precision floating-point numbers. This happens with
15202     // std::complex<float>, and other similar structures, because of the way we
15203     // canonicalize structure copies. However, if we lack direct moves,
15204     // then the final bitcasts from the extracted integer values to the
15205     // floating-point numbers turn into store/load pairs. Even with direct moves,
15206     // just loading the two floating-point numbers is likely better.
15207     auto ReplaceTwoFloatLoad = [&]() {
15208       if (VT != MVT::i64)
15209         return false;
15210 
15211       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15212           LD->isVolatile())
15213         return false;
15214 
15215       //  We're looking for a sequence like this:
15216       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15217       //      t16: i64 = srl t13, Constant:i32<32>
15218       //    t17: i32 = truncate t16
15219       //  t18: f32 = bitcast t17
15220       //    t19: i32 = truncate t13
15221       //  t20: f32 = bitcast t19
15222 
15223       if (!LD->hasNUsesOfValue(2, 0))
15224         return false;
15225 
15226       auto UI = LD->use_begin();
15227       while (UI.getUse().getResNo() != 0) ++UI;
15228       SDNode *Trunc = *UI++;
15229       while (UI.getUse().getResNo() != 0) ++UI;
15230       SDNode *RightShift = *UI;
15231       if (Trunc->getOpcode() != ISD::TRUNCATE)
15232         std::swap(Trunc, RightShift);
15233 
15234       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15235           Trunc->getValueType(0) != MVT::i32 ||
15236           !Trunc->hasOneUse())
15237         return false;
15238       if (RightShift->getOpcode() != ISD::SRL ||
15239           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15240           RightShift->getConstantOperandVal(1) != 32 ||
15241           !RightShift->hasOneUse())
15242         return false;
15243 
15244       SDNode *Trunc2 = *RightShift->use_begin();
15245       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15246           Trunc2->getValueType(0) != MVT::i32 ||
15247           !Trunc2->hasOneUse())
15248         return false;
15249 
15250       SDNode *Bitcast = *Trunc->use_begin();
15251       SDNode *Bitcast2 = *Trunc2->use_begin();
15252 
15253       if (Bitcast->getOpcode() != ISD::BITCAST ||
15254           Bitcast->getValueType(0) != MVT::f32)
15255         return false;
15256       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15257           Bitcast2->getValueType(0) != MVT::f32)
15258         return false;
15259 
15260       if (Subtarget.isLittleEndian())
15261         std::swap(Bitcast, Bitcast2);
15262 
15263       // Bitcast has the second float (in memory-layout order) and Bitcast2
15264       // has the first one.
15265 
15266       SDValue BasePtr = LD->getBasePtr();
15267       if (LD->isIndexed()) {
15268         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15269                "Non-pre-inc AM on PPC?");
15270         BasePtr =
15271           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15272                       LD->getOffset());
15273       }
15274 
15275       auto MMOFlags =
15276           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15277       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15278                                       LD->getPointerInfo(), LD->getAlignment(),
15279                                       MMOFlags, LD->getAAInfo());
15280       SDValue AddPtr =
15281         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15282                     BasePtr, DAG.getIntPtrConstant(4, dl));
15283       SDValue FloatLoad2 = DAG.getLoad(
15284           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15285           LD->getPointerInfo().getWithOffset(4),
15286           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15287 
15288       if (LD->isIndexed()) {
15289         // Note that DAGCombine should re-form any pre-increment load(s) from
15290         // what is produced here if that makes sense.
15291         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15292       }
15293 
15294       DCI.CombineTo(Bitcast2, FloatLoad);
15295       DCI.CombineTo(Bitcast, FloatLoad2);
15296 
15297       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15298                                     SDValue(FloatLoad2.getNode(), 1));
15299       return true;
15300     };
15301 
15302     if (ReplaceTwoFloatLoad())
15303       return SDValue(N, 0);
15304 
15305     EVT MemVT = LD->getMemoryVT();
15306     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15307     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15308     if (LD->isUnindexed() && VT.isVector() &&
15309         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15310           // P8 and later hardware should just use LOAD.
15311           !Subtarget.hasP8Vector() &&
15312           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15313            VT == MVT::v4f32))) &&
15314         LD->getAlign() < ABIAlignment) {
15315       // This is a type-legal unaligned Altivec load.
15316       SDValue Chain = LD->getChain();
15317       SDValue Ptr = LD->getBasePtr();
15318       bool isLittleEndian = Subtarget.isLittleEndian();
15319 
15320       // This implements the loading of unaligned vectors as described in
15321       // the venerable Apple Velocity Engine overview. Specifically:
15322       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15323       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15324       //
15325       // The general idea is to expand a sequence of one or more unaligned
15326       // loads into an alignment-based permutation-control instruction (lvsl
15327       // or lvsr), a series of regular vector loads (which always truncate
15328       // their input address to an aligned address), and a series of
15329       // permutations.  The results of these permutations are the requested
15330       // loaded values.  The trick is that the last "extra" load is not taken
15331       // from the address you might suspect (sizeof(vector) bytes after the
15332       // last requested load), but rather sizeof(vector) - 1 bytes after the
15333       // last requested vector. The point of this is to avoid a page fault if
15334       // the base address happened to be aligned. This works because if the
15335       // base address is aligned, then adding less than a full vector length
15336       // will cause the last vector in the sequence to be (re)loaded.
15337       // Otherwise, the next vector will be fetched as you might suspect was
15338       // necessary.
15339 
15340       // We might be able to reuse the permutation generation from
15341       // a different base address offset from this one by an aligned amount.
15342       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15343       // optimization later.
15344       Intrinsic::ID Intr, IntrLD, IntrPerm;
15345       MVT PermCntlTy, PermTy, LDTy;
15346       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15347                             : Intrinsic::ppc_altivec_lvsl;
15348       IntrLD = Intrinsic::ppc_altivec_lvx;
15349       IntrPerm = Intrinsic::ppc_altivec_vperm;
15350       PermCntlTy = MVT::v16i8;
15351       PermTy = MVT::v4i32;
15352       LDTy = MVT::v4i32;
15353 
15354       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15355 
15356       // Create the new MMO for the new base load. It is like the original MMO,
15357       // but represents an area in memory almost twice the vector size centered
15358       // on the original address. If the address is unaligned, we might start
15359       // reading up to (sizeof(vector)-1) bytes below the address of the
15360       // original unaligned load.
15361       MachineFunction &MF = DAG.getMachineFunction();
15362       MachineMemOperand *BaseMMO =
15363         MF.getMachineMemOperand(LD->getMemOperand(),
15364                                 -(long)MemVT.getStoreSize()+1,
15365                                 2*MemVT.getStoreSize()-1);
15366 
15367       // Create the new base load.
15368       SDValue LDXIntID =
15369           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15370       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15371       SDValue BaseLoad =
15372         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15373                                 DAG.getVTList(PermTy, MVT::Other),
15374                                 BaseLoadOps, LDTy, BaseMMO);
15375 
15376       // Note that the value of IncOffset (which is provided to the next
15377       // load's pointer info offset value, and thus used to calculate the
15378       // alignment), and the value of IncValue (which is actually used to
15379       // increment the pointer value) are different! This is because we
15380       // require the next load to appear to be aligned, even though it
15381       // is actually offset from the base pointer by a lesser amount.
15382       int IncOffset = VT.getSizeInBits() / 8;
15383       int IncValue = IncOffset;
15384 
15385       // Walk (both up and down) the chain looking for another load at the real
15386       // (aligned) offset (the alignment of the other load does not matter in
15387       // this case). If found, then do not use the offset reduction trick, as
15388       // that will prevent the loads from being later combined (as they would
15389       // otherwise be duplicates).
15390       if (!findConsecutiveLoad(LD, DAG))
15391         --IncValue;
15392 
15393       SDValue Increment =
15394           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15395       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15396 
15397       MachineMemOperand *ExtraMMO =
15398         MF.getMachineMemOperand(LD->getMemOperand(),
15399                                 1, 2*MemVT.getStoreSize()-1);
15400       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15401       SDValue ExtraLoad =
15402         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15403                                 DAG.getVTList(PermTy, MVT::Other),
15404                                 ExtraLoadOps, LDTy, ExtraMMO);
15405 
15406       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15407         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15408 
15409       // Because vperm has a big-endian bias, we must reverse the order
15410       // of the input vectors and complement the permute control vector
15411       // when generating little endian code.  We have already handled the
15412       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15413       // and ExtraLoad here.
15414       SDValue Perm;
15415       if (isLittleEndian)
15416         Perm = BuildIntrinsicOp(IntrPerm,
15417                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15418       else
15419         Perm = BuildIntrinsicOp(IntrPerm,
15420                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15421 
15422       if (VT != PermTy)
15423         Perm = Subtarget.hasAltivec()
15424                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15425                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15426                                  DAG.getTargetConstant(1, dl, MVT::i64));
15427                                // second argument is 1 because this rounding
15428                                // is always exact.
15429 
15430       // The output of the permutation is our loaded result, the TokenFactor is
15431       // our new chain.
15432       DCI.CombineTo(N, Perm, TF);
15433       return SDValue(N, 0);
15434     }
15435     }
15436     break;
15437     case ISD::INTRINSIC_WO_CHAIN: {
15438       bool isLittleEndian = Subtarget.isLittleEndian();
15439       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15440       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15441                                            : Intrinsic::ppc_altivec_lvsl);
15442       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15443         SDValue Add = N->getOperand(1);
15444 
15445         int Bits = 4 /* 16 byte alignment */;
15446 
15447         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15448                                   APInt::getAllOnes(Bits /* alignment */)
15449                                       .zext(Add.getScalarValueSizeInBits()))) {
15450           SDNode *BasePtr = Add->getOperand(0).getNode();
15451           for (SDNode *U : BasePtr->uses()) {
15452             if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15453                 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15454               // We've found another LVSL/LVSR, and this address is an aligned
15455               // multiple of that one. The results will be the same, so use the
15456               // one we've just found instead.
15457 
15458               return SDValue(U, 0);
15459             }
15460           }
15461         }
15462 
15463         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15464           SDNode *BasePtr = Add->getOperand(0).getNode();
15465           for (SDNode *U : BasePtr->uses()) {
15466             if (U->getOpcode() == ISD::ADD &&
15467                 isa<ConstantSDNode>(U->getOperand(1)) &&
15468                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15469                  cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15470                         (1ULL << Bits) ==
15471                     0) {
15472               SDNode *OtherAdd = U;
15473               for (SDNode *V : OtherAdd->uses()) {
15474                 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15475                     cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15476                         IID) {
15477                   return SDValue(V, 0);
15478                 }
15479               }
15480             }
15481           }
15482         }
15483       }
15484 
15485       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15486       // Expose the vabsduw/h/b opportunity for down stream
15487       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15488           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15489            IID == Intrinsic::ppc_altivec_vmaxsh ||
15490            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15491         SDValue V1 = N->getOperand(1);
15492         SDValue V2 = N->getOperand(2);
15493         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15494              V1.getSimpleValueType() == MVT::v8i16 ||
15495              V1.getSimpleValueType() == MVT::v16i8) &&
15496             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15497           // (0-a, a)
15498           if (V1.getOpcode() == ISD::SUB &&
15499               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15500               V1.getOperand(1) == V2) {
15501             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15502           }
15503           // (a, 0-a)
15504           if (V2.getOpcode() == ISD::SUB &&
15505               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15506               V2.getOperand(1) == V1) {
15507             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15508           }
15509           // (x-y, y-x)
15510           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15511               V1.getOperand(0) == V2.getOperand(1) &&
15512               V1.getOperand(1) == V2.getOperand(0)) {
15513             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15514           }
15515         }
15516       }
15517     }
15518 
15519     break;
15520   case ISD::INTRINSIC_W_CHAIN:
15521     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15522     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15523     if (Subtarget.needsSwapsForVSXMemOps()) {
15524       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15525       default:
15526         break;
15527       case Intrinsic::ppc_vsx_lxvw4x:
15528       case Intrinsic::ppc_vsx_lxvd2x:
15529         return expandVSXLoadForLE(N, DCI);
15530       }
15531     }
15532     break;
15533   case ISD::INTRINSIC_VOID:
15534     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15535     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15536     if (Subtarget.needsSwapsForVSXMemOps()) {
15537       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15538       default:
15539         break;
15540       case Intrinsic::ppc_vsx_stxvw4x:
15541       case Intrinsic::ppc_vsx_stxvd2x:
15542         return expandVSXStoreForLE(N, DCI);
15543       }
15544     }
15545     break;
15546   case ISD::BSWAP: {
15547     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15548     // For subtargets without LDBRX, we can still do better than the default
15549     // expansion even for 64-bit BSWAP (LOAD).
15550     bool Is64BitBswapOn64BitTgt =
15551         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15552     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15553                                N->getOperand(0).hasOneUse();
15554     if (IsSingleUseNormalLd &&
15555         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15556          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15557       SDValue Load = N->getOperand(0);
15558       LoadSDNode *LD = cast<LoadSDNode>(Load);
15559       // Create the byte-swapping load.
15560       SDValue Ops[] = {
15561         LD->getChain(),    // Chain
15562         LD->getBasePtr(),  // Ptr
15563         DAG.getValueType(N->getValueType(0)) // VT
15564       };
15565       SDValue BSLoad =
15566         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15567                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15568                                               MVT::i64 : MVT::i32, MVT::Other),
15569                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15570 
15571       // If this is an i16 load, insert the truncate.
15572       SDValue ResVal = BSLoad;
15573       if (N->getValueType(0) == MVT::i16)
15574         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15575 
15576       // First, combine the bswap away.  This makes the value produced by the
15577       // load dead.
15578       DCI.CombineTo(N, ResVal);
15579 
15580       // Next, combine the load away, we give it a bogus result value but a real
15581       // chain result.  The result value is dead because the bswap is dead.
15582       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15583 
15584       // Return N so it doesn't get rechecked!
15585       return SDValue(N, 0);
15586     }
15587     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15588     // before legalization so that the BUILD_PAIR is handled correctly.
15589     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15590         !IsSingleUseNormalLd)
15591       return SDValue();
15592     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15593 
15594     // Can't split volatile or atomic loads.
15595     if (!LD->isSimple())
15596       return SDValue();
15597     SDValue BasePtr = LD->getBasePtr();
15598     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15599                              LD->getPointerInfo(), LD->getAlignment());
15600     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15601     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15602                           DAG.getIntPtrConstant(4, dl));
15603     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15604         LD->getMemOperand(), 4, 4);
15605     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15606     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15607     SDValue Res;
15608     if (Subtarget.isLittleEndian())
15609       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15610     else
15611       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15612     SDValue TF =
15613         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15614                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15615     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15616     return Res;
15617   }
15618   case PPCISD::VCMP:
15619     // If a VCMP_rec node already exists with exactly the same operands as this
15620     // node, use its result instead of this node (VCMP_rec computes both a CR6
15621     // and a normal output).
15622     //
15623     if (!N->getOperand(0).hasOneUse() &&
15624         !N->getOperand(1).hasOneUse() &&
15625         !N->getOperand(2).hasOneUse()) {
15626 
15627       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15628       SDNode *VCMPrecNode = nullptr;
15629 
15630       SDNode *LHSN = N->getOperand(0).getNode();
15631       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15632            UI != E; ++UI)
15633         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15634             UI->getOperand(1) == N->getOperand(1) &&
15635             UI->getOperand(2) == N->getOperand(2) &&
15636             UI->getOperand(0) == N->getOperand(0)) {
15637           VCMPrecNode = *UI;
15638           break;
15639         }
15640 
15641       // If there is no VCMP_rec node, or if the flag value has a single use,
15642       // don't transform this.
15643       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15644         break;
15645 
15646       // Look at the (necessarily single) use of the flag value.  If it has a
15647       // chain, this transformation is more complex.  Note that multiple things
15648       // could use the value result, which we should ignore.
15649       SDNode *FlagUser = nullptr;
15650       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15651            FlagUser == nullptr; ++UI) {
15652         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15653         SDNode *User = *UI;
15654         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15655           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15656             FlagUser = User;
15657             break;
15658           }
15659         }
15660       }
15661 
15662       // If the user is a MFOCRF instruction, we know this is safe.
15663       // Otherwise we give up for right now.
15664       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15665         return SDValue(VCMPrecNode, 0);
15666     }
15667     break;
15668   case ISD::BRCOND: {
15669     SDValue Cond = N->getOperand(1);
15670     SDValue Target = N->getOperand(2);
15671 
15672     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15673         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15674           Intrinsic::loop_decrement) {
15675 
15676       // We now need to make the intrinsic dead (it cannot be instruction
15677       // selected).
15678       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15679       assert(Cond.getNode()->hasOneUse() &&
15680              "Counter decrement has more than one use");
15681 
15682       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15683                          N->getOperand(0), Target);
15684     }
15685   }
15686   break;
15687   case ISD::BR_CC: {
15688     // If this is a branch on an altivec predicate comparison, lower this so
15689     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15690     // lowering is done pre-legalize, because the legalizer lowers the predicate
15691     // compare down to code that is difficult to reassemble.
15692     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15693     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15694 
15695     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15696     // value. If so, pass-through the AND to get to the intrinsic.
15697     if (LHS.getOpcode() == ISD::AND &&
15698         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15699         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15700           Intrinsic::loop_decrement &&
15701         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15702         !isNullConstant(LHS.getOperand(1)))
15703       LHS = LHS.getOperand(0);
15704 
15705     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15706         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15707           Intrinsic::loop_decrement &&
15708         isa<ConstantSDNode>(RHS)) {
15709       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15710              "Counter decrement comparison is not EQ or NE");
15711 
15712       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15713       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15714                     (CC == ISD::SETNE && !Val);
15715 
15716       // We now need to make the intrinsic dead (it cannot be instruction
15717       // selected).
15718       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15719       assert(LHS.getNode()->hasOneUse() &&
15720              "Counter decrement has more than one use");
15721 
15722       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15723                          N->getOperand(0), N->getOperand(4));
15724     }
15725 
15726     int CompareOpc;
15727     bool isDot;
15728 
15729     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15730         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15731         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15732       assert(isDot && "Can't compare against a vector result!");
15733 
15734       // If this is a comparison against something other than 0/1, then we know
15735       // that the condition is never/always true.
15736       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15737       if (Val != 0 && Val != 1) {
15738         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15739           return N->getOperand(0);
15740         // Always !=, turn it into an unconditional branch.
15741         return DAG.getNode(ISD::BR, dl, MVT::Other,
15742                            N->getOperand(0), N->getOperand(4));
15743       }
15744 
15745       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15746 
15747       // Create the PPCISD altivec 'dot' comparison node.
15748       SDValue Ops[] = {
15749         LHS.getOperand(2),  // LHS of compare
15750         LHS.getOperand(3),  // RHS of compare
15751         DAG.getConstant(CompareOpc, dl, MVT::i32)
15752       };
15753       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15754       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15755 
15756       // Unpack the result based on how the target uses it.
15757       PPC::Predicate CompOpc;
15758       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15759       default:  // Can't happen, don't crash on invalid number though.
15760       case 0:   // Branch on the value of the EQ bit of CR6.
15761         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15762         break;
15763       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15764         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15765         break;
15766       case 2:   // Branch on the value of the LT bit of CR6.
15767         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15768         break;
15769       case 3:   // Branch on the inverted value of the LT bit of CR6.
15770         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15771         break;
15772       }
15773 
15774       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15775                          DAG.getConstant(CompOpc, dl, MVT::i32),
15776                          DAG.getRegister(PPC::CR6, MVT::i32),
15777                          N->getOperand(4), CompNode.getValue(1));
15778     }
15779     break;
15780   }
15781   case ISD::BUILD_VECTOR:
15782     return DAGCombineBuildVector(N, DCI);
15783   case ISD::ABS:
15784     return combineABS(N, DCI);
15785   case ISD::VSELECT:
15786     return combineVSelect(N, DCI);
15787   }
15788 
15789   return SDValue();
15790 }
15791 
15792 SDValue
15793 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15794                                  SelectionDAG &DAG,
15795                                  SmallVectorImpl<SDNode *> &Created) const {
15796   // fold (sdiv X, pow2)
15797   EVT VT = N->getValueType(0);
15798   if (VT == MVT::i64 && !Subtarget.isPPC64())
15799     return SDValue();
15800   if ((VT != MVT::i32 && VT != MVT::i64) ||
15801       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15802     return SDValue();
15803 
15804   SDLoc DL(N);
15805   SDValue N0 = N->getOperand(0);
15806 
15807   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15808   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15809   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15810 
15811   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15812   Created.push_back(Op.getNode());
15813 
15814   if (IsNegPow2) {
15815     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15816     Created.push_back(Op.getNode());
15817   }
15818 
15819   return Op;
15820 }
15821 
15822 //===----------------------------------------------------------------------===//
15823 // Inline Assembly Support
15824 //===----------------------------------------------------------------------===//
15825 
15826 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15827                                                       KnownBits &Known,
15828                                                       const APInt &DemandedElts,
15829                                                       const SelectionDAG &DAG,
15830                                                       unsigned Depth) const {
15831   Known.resetAll();
15832   switch (Op.getOpcode()) {
15833   default: break;
15834   case PPCISD::LBRX: {
15835     // lhbrx is known to have the top bits cleared out.
15836     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15837       Known.Zero = 0xFFFF0000;
15838     break;
15839   }
15840   case ISD::INTRINSIC_WO_CHAIN: {
15841     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15842     default: break;
15843     case Intrinsic::ppc_altivec_vcmpbfp_p:
15844     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15845     case Intrinsic::ppc_altivec_vcmpequb_p:
15846     case Intrinsic::ppc_altivec_vcmpequh_p:
15847     case Intrinsic::ppc_altivec_vcmpequw_p:
15848     case Intrinsic::ppc_altivec_vcmpequd_p:
15849     case Intrinsic::ppc_altivec_vcmpequq_p:
15850     case Intrinsic::ppc_altivec_vcmpgefp_p:
15851     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15852     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15853     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15854     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15855     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15856     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15857     case Intrinsic::ppc_altivec_vcmpgtub_p:
15858     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15859     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15860     case Intrinsic::ppc_altivec_vcmpgtud_p:
15861     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15862       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15863       break;
15864     }
15865     break;
15866   }
15867   case ISD::INTRINSIC_W_CHAIN: {
15868     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15869     default:
15870       break;
15871     case Intrinsic::ppc_load2r:
15872       // Top bits are cleared for load2r (which is the same as lhbrx).
15873       Known.Zero = 0xFFFF0000;
15874       break;
15875     }
15876     break;
15877   }
15878   }
15879 }
15880 
15881 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15882   switch (Subtarget.getCPUDirective()) {
15883   default: break;
15884   case PPC::DIR_970:
15885   case PPC::DIR_PWR4:
15886   case PPC::DIR_PWR5:
15887   case PPC::DIR_PWR5X:
15888   case PPC::DIR_PWR6:
15889   case PPC::DIR_PWR6X:
15890   case PPC::DIR_PWR7:
15891   case PPC::DIR_PWR8:
15892   case PPC::DIR_PWR9:
15893   case PPC::DIR_PWR10:
15894   case PPC::DIR_PWR_FUTURE: {
15895     if (!ML)
15896       break;
15897 
15898     if (!DisableInnermostLoopAlign32) {
15899       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15900       // so that we can decrease cache misses and branch-prediction misses.
15901       // Actual alignment of the loop will depend on the hotness check and other
15902       // logic in alignBlocks.
15903       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15904         return Align(32);
15905     }
15906 
15907     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15908 
15909     // For small loops (between 5 and 8 instructions), align to a 32-byte
15910     // boundary so that the entire loop fits in one instruction-cache line.
15911     uint64_t LoopSize = 0;
15912     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15913       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15914         LoopSize += TII->getInstSizeInBytes(*J);
15915         if (LoopSize > 32)
15916           break;
15917       }
15918 
15919     if (LoopSize > 16 && LoopSize <= 32)
15920       return Align(32);
15921 
15922     break;
15923   }
15924   }
15925 
15926   return TargetLowering::getPrefLoopAlignment(ML);
15927 }
15928 
15929 /// getConstraintType - Given a constraint, return the type of
15930 /// constraint it is for this target.
15931 PPCTargetLowering::ConstraintType
15932 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15933   if (Constraint.size() == 1) {
15934     switch (Constraint[0]) {
15935     default: break;
15936     case 'b':
15937     case 'r':
15938     case 'f':
15939     case 'd':
15940     case 'v':
15941     case 'y':
15942       return C_RegisterClass;
15943     case 'Z':
15944       // FIXME: While Z does indicate a memory constraint, it specifically
15945       // indicates an r+r address (used in conjunction with the 'y' modifier
15946       // in the replacement string). Currently, we're forcing the base
15947       // register to be r0 in the asm printer (which is interpreted as zero)
15948       // and forming the complete address in the second register. This is
15949       // suboptimal.
15950       return C_Memory;
15951     }
15952   } else if (Constraint == "wc") { // individual CR bits.
15953     return C_RegisterClass;
15954   } else if (Constraint == "wa" || Constraint == "wd" ||
15955              Constraint == "wf" || Constraint == "ws" ||
15956              Constraint == "wi" || Constraint == "ww") {
15957     return C_RegisterClass; // VSX registers.
15958   }
15959   return TargetLowering::getConstraintType(Constraint);
15960 }
15961 
15962 /// Examine constraint type and operand type and determine a weight value.
15963 /// This object must already have been set up with the operand type
15964 /// and the current alternative constraint selected.
15965 TargetLowering::ConstraintWeight
15966 PPCTargetLowering::getSingleConstraintMatchWeight(
15967     AsmOperandInfo &info, const char *constraint) const {
15968   ConstraintWeight weight = CW_Invalid;
15969   Value *CallOperandVal = info.CallOperandVal;
15970     // If we don't have a value, we can't do a match,
15971     // but allow it at the lowest weight.
15972   if (!CallOperandVal)
15973     return CW_Default;
15974   Type *type = CallOperandVal->getType();
15975 
15976   // Look at the constraint type.
15977   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15978     return CW_Register; // an individual CR bit.
15979   else if ((StringRef(constraint) == "wa" ||
15980             StringRef(constraint) == "wd" ||
15981             StringRef(constraint) == "wf") &&
15982            type->isVectorTy())
15983     return CW_Register;
15984   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15985     return CW_Register; // just hold 64-bit integers data.
15986   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15987     return CW_Register;
15988   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15989     return CW_Register;
15990 
15991   switch (*constraint) {
15992   default:
15993     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15994     break;
15995   case 'b':
15996     if (type->isIntegerTy())
15997       weight = CW_Register;
15998     break;
15999   case 'f':
16000     if (type->isFloatTy())
16001       weight = CW_Register;
16002     break;
16003   case 'd':
16004     if (type->isDoubleTy())
16005       weight = CW_Register;
16006     break;
16007   case 'v':
16008     if (type->isVectorTy())
16009       weight = CW_Register;
16010     break;
16011   case 'y':
16012     weight = CW_Register;
16013     break;
16014   case 'Z':
16015     weight = CW_Memory;
16016     break;
16017   }
16018   return weight;
16019 }
16020 
16021 std::pair<unsigned, const TargetRegisterClass *>
16022 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
16023                                                 StringRef Constraint,
16024                                                 MVT VT) const {
16025   if (Constraint.size() == 1) {
16026     // GCC RS6000 Constraint Letters
16027     switch (Constraint[0]) {
16028     case 'b':   // R1-R31
16029       if (VT == MVT::i64 && Subtarget.isPPC64())
16030         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
16031       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
16032     case 'r':   // R0-R31
16033       if (VT == MVT::i64 && Subtarget.isPPC64())
16034         return std::make_pair(0U, &PPC::G8RCRegClass);
16035       return std::make_pair(0U, &PPC::GPRCRegClass);
16036     // 'd' and 'f' constraints are both defined to be "the floating point
16037     // registers", where one is for 32-bit and the other for 64-bit. We don't
16038     // really care overly much here so just give them all the same reg classes.
16039     case 'd':
16040     case 'f':
16041       if (Subtarget.hasSPE()) {
16042         if (VT == MVT::f32 || VT == MVT::i32)
16043           return std::make_pair(0U, &PPC::GPRCRegClass);
16044         if (VT == MVT::f64 || VT == MVT::i64)
16045           return std::make_pair(0U, &PPC::SPERCRegClass);
16046       } else {
16047         if (VT == MVT::f32 || VT == MVT::i32)
16048           return std::make_pair(0U, &PPC::F4RCRegClass);
16049         if (VT == MVT::f64 || VT == MVT::i64)
16050           return std::make_pair(0U, &PPC::F8RCRegClass);
16051       }
16052       break;
16053     case 'v':
16054       if (Subtarget.hasAltivec() && VT.isVector())
16055         return std::make_pair(0U, &PPC::VRRCRegClass);
16056       else if (Subtarget.hasVSX())
16057         // Scalars in Altivec registers only make sense with VSX.
16058         return std::make_pair(0U, &PPC::VFRCRegClass);
16059       break;
16060     case 'y':   // crrc
16061       return std::make_pair(0U, &PPC::CRRCRegClass);
16062     }
16063   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
16064     // An individual CR bit.
16065     return std::make_pair(0U, &PPC::CRBITRCRegClass);
16066   } else if ((Constraint == "wa" || Constraint == "wd" ||
16067              Constraint == "wf" || Constraint == "wi") &&
16068              Subtarget.hasVSX()) {
16069     // A VSX register for either a scalar (FP) or vector. There is no
16070     // support for single precision scalars on subtargets prior to Power8.
16071     if (VT.isVector())
16072       return std::make_pair(0U, &PPC::VSRCRegClass);
16073     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16074       return std::make_pair(0U, &PPC::VSSRCRegClass);
16075     return std::make_pair(0U, &PPC::VSFRCRegClass);
16076   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16077     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16078       return std::make_pair(0U, &PPC::VSSRCRegClass);
16079     else
16080       return std::make_pair(0U, &PPC::VSFRCRegClass);
16081   } else if (Constraint == "lr") {
16082     if (VT == MVT::i64)
16083       return std::make_pair(0U, &PPC::LR8RCRegClass);
16084     else
16085       return std::make_pair(0U, &PPC::LRRCRegClass);
16086   }
16087 
16088   // Handle special cases of physical registers that are not properly handled
16089   // by the base class.
16090   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16091     // If we name a VSX register, we can't defer to the base class because it
16092     // will not recognize the correct register (their names will be VSL{0-31}
16093     // and V{0-31} so they won't match). So we match them here.
16094     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16095       int VSNum = atoi(Constraint.data() + 3);
16096       assert(VSNum >= 0 && VSNum <= 63 &&
16097              "Attempted to access a vsr out of range");
16098       if (VSNum < 32)
16099         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16100       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16101     }
16102 
16103     // For float registers, we can't defer to the base class as it will match
16104     // the SPILLTOVSRRC class.
16105     if (Constraint.size() > 3 && Constraint[1] == 'f') {
16106       int RegNum = atoi(Constraint.data() + 2);
16107       if (RegNum > 31 || RegNum < 0)
16108         report_fatal_error("Invalid floating point register number");
16109       if (VT == MVT::f32 || VT == MVT::i32)
16110         return Subtarget.hasSPE()
16111                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16112                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16113       if (VT == MVT::f64 || VT == MVT::i64)
16114         return Subtarget.hasSPE()
16115                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16116                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16117     }
16118   }
16119 
16120   std::pair<unsigned, const TargetRegisterClass *> R =
16121       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16122 
16123   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16124   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16125   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16126   // register.
16127   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16128   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16129   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16130       PPC::GPRCRegClass.contains(R.first))
16131     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16132                             PPC::sub_32, &PPC::G8RCRegClass),
16133                           &PPC::G8RCRegClass);
16134 
16135   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16136   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16137     R.first = PPC::CR0;
16138     R.second = &PPC::CRRCRegClass;
16139   }
16140   // FIXME: This warning should ideally be emitted in the front end.
16141   const auto &TM = getTargetMachine();
16142   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16143     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16144          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16145         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16146       errs() << "warning: vector registers 20 to 32 are reserved in the "
16147                 "default AIX AltiVec ABI and cannot be used\n";
16148   }
16149 
16150   return R;
16151 }
16152 
16153 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16154 /// vector.  If it is invalid, don't add anything to Ops.
16155 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16156                                                      std::string &Constraint,
16157                                                      std::vector<SDValue>&Ops,
16158                                                      SelectionDAG &DAG) const {
16159   SDValue Result;
16160 
16161   // Only support length 1 constraints.
16162   if (Constraint.length() > 1) return;
16163 
16164   char Letter = Constraint[0];
16165   switch (Letter) {
16166   default: break;
16167   case 'I':
16168   case 'J':
16169   case 'K':
16170   case 'L':
16171   case 'M':
16172   case 'N':
16173   case 'O':
16174   case 'P': {
16175     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16176     if (!CST) return; // Must be an immediate to match.
16177     SDLoc dl(Op);
16178     int64_t Value = CST->getSExtValue();
16179     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16180                          // numbers are printed as such.
16181     switch (Letter) {
16182     default: llvm_unreachable("Unknown constraint letter!");
16183     case 'I':  // "I" is a signed 16-bit constant.
16184       if (isInt<16>(Value))
16185         Result = DAG.getTargetConstant(Value, dl, TCVT);
16186       break;
16187     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16188       if (isShiftedUInt<16, 16>(Value))
16189         Result = DAG.getTargetConstant(Value, dl, TCVT);
16190       break;
16191     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16192       if (isShiftedInt<16, 16>(Value))
16193         Result = DAG.getTargetConstant(Value, dl, TCVT);
16194       break;
16195     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16196       if (isUInt<16>(Value))
16197         Result = DAG.getTargetConstant(Value, dl, TCVT);
16198       break;
16199     case 'M':  // "M" is a constant that is greater than 31.
16200       if (Value > 31)
16201         Result = DAG.getTargetConstant(Value, dl, TCVT);
16202       break;
16203     case 'N':  // "N" is a positive constant that is an exact power of two.
16204       if (Value > 0 && isPowerOf2_64(Value))
16205         Result = DAG.getTargetConstant(Value, dl, TCVT);
16206       break;
16207     case 'O':  // "O" is the constant zero.
16208       if (Value == 0)
16209         Result = DAG.getTargetConstant(Value, dl, TCVT);
16210       break;
16211     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16212       if (isInt<16>(-Value))
16213         Result = DAG.getTargetConstant(Value, dl, TCVT);
16214       break;
16215     }
16216     break;
16217   }
16218   }
16219 
16220   if (Result.getNode()) {
16221     Ops.push_back(Result);
16222     return;
16223   }
16224 
16225   // Handle standard constraint letters.
16226   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16227 }
16228 
16229 // isLegalAddressingMode - Return true if the addressing mode represented
16230 // by AM is legal for this target, for a load/store of the specified type.
16231 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16232                                               const AddrMode &AM, Type *Ty,
16233                                               unsigned AS,
16234                                               Instruction *I) const {
16235   // Vector type r+i form is supported since power9 as DQ form. We don't check
16236   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16237   // imm form is preferred and the offset can be adjusted to use imm form later
16238   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16239   // max offset to check legal addressing mode, we should be a little aggressive
16240   // to contain other offsets for that LSRUse.
16241   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16242     return false;
16243 
16244   // PPC allows a sign-extended 16-bit immediate field.
16245   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16246     return false;
16247 
16248   // No global is ever allowed as a base.
16249   if (AM.BaseGV)
16250     return false;
16251 
16252   // PPC only support r+r,
16253   switch (AM.Scale) {
16254   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16255     break;
16256   case 1:
16257     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16258       return false;
16259     // Otherwise we have r+r or r+i.
16260     break;
16261   case 2:
16262     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16263       return false;
16264     // Allow 2*r as r+r.
16265     break;
16266   default:
16267     // No other scales are supported.
16268     return false;
16269   }
16270 
16271   return true;
16272 }
16273 
16274 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16275                                            SelectionDAG &DAG) const {
16276   MachineFunction &MF = DAG.getMachineFunction();
16277   MachineFrameInfo &MFI = MF.getFrameInfo();
16278   MFI.setReturnAddressIsTaken(true);
16279 
16280   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16281     return SDValue();
16282 
16283   SDLoc dl(Op);
16284   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16285 
16286   // Make sure the function does not optimize away the store of the RA to
16287   // the stack.
16288   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16289   FuncInfo->setLRStoreRequired();
16290   bool isPPC64 = Subtarget.isPPC64();
16291   auto PtrVT = getPointerTy(MF.getDataLayout());
16292 
16293   if (Depth > 0) {
16294     // The link register (return address) is saved in the caller's frame
16295     // not the callee's stack frame. So we must get the caller's frame
16296     // address and load the return address at the LR offset from there.
16297     SDValue FrameAddr =
16298         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16299                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16300     SDValue Offset =
16301         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16302                         isPPC64 ? MVT::i64 : MVT::i32);
16303     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16304                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16305                        MachinePointerInfo());
16306   }
16307 
16308   // Just load the return address off the stack.
16309   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16310   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16311                      MachinePointerInfo());
16312 }
16313 
16314 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16315                                           SelectionDAG &DAG) const {
16316   SDLoc dl(Op);
16317   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16318 
16319   MachineFunction &MF = DAG.getMachineFunction();
16320   MachineFrameInfo &MFI = MF.getFrameInfo();
16321   MFI.setFrameAddressIsTaken(true);
16322 
16323   EVT PtrVT = getPointerTy(MF.getDataLayout());
16324   bool isPPC64 = PtrVT == MVT::i64;
16325 
16326   // Naked functions never have a frame pointer, and so we use r1. For all
16327   // other functions, this decision must be delayed until during PEI.
16328   unsigned FrameReg;
16329   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16330     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16331   else
16332     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16333 
16334   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16335                                          PtrVT);
16336   while (Depth--)
16337     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16338                             FrameAddr, MachinePointerInfo());
16339   return FrameAddr;
16340 }
16341 
16342 // FIXME? Maybe this could be a TableGen attribute on some registers and
16343 // this table could be generated automatically from RegInfo.
16344 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16345                                               const MachineFunction &MF) const {
16346   bool isPPC64 = Subtarget.isPPC64();
16347 
16348   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16349   if (!is64Bit && VT != LLT::scalar(32))
16350     report_fatal_error("Invalid register global variable type");
16351 
16352   Register Reg = StringSwitch<Register>(RegName)
16353                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16354                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16355                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16356                      .Default(Register());
16357 
16358   if (Reg)
16359     return Reg;
16360   report_fatal_error("Invalid register name global variable");
16361 }
16362 
16363 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16364   // 32-bit SVR4 ABI access everything as got-indirect.
16365   if (Subtarget.is32BitELFABI())
16366     return true;
16367 
16368   // AIX accesses everything indirectly through the TOC, which is similar to
16369   // the GOT.
16370   if (Subtarget.isAIXABI())
16371     return true;
16372 
16373   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16374   // If it is small or large code model, module locals are accessed
16375   // indirectly by loading their address from .toc/.got.
16376   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16377     return true;
16378 
16379   // JumpTable and BlockAddress are accessed as got-indirect.
16380   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16381     return true;
16382 
16383   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16384     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16385 
16386   return false;
16387 }
16388 
16389 bool
16390 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16391   // The PowerPC target isn't yet aware of offsets.
16392   return false;
16393 }
16394 
16395 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16396                                            const CallInst &I,
16397                                            MachineFunction &MF,
16398                                            unsigned Intrinsic) const {
16399   switch (Intrinsic) {
16400   case Intrinsic::ppc_atomicrmw_xchg_i128:
16401   case Intrinsic::ppc_atomicrmw_add_i128:
16402   case Intrinsic::ppc_atomicrmw_sub_i128:
16403   case Intrinsic::ppc_atomicrmw_nand_i128:
16404   case Intrinsic::ppc_atomicrmw_and_i128:
16405   case Intrinsic::ppc_atomicrmw_or_i128:
16406   case Intrinsic::ppc_atomicrmw_xor_i128:
16407   case Intrinsic::ppc_cmpxchg_i128:
16408     Info.opc = ISD::INTRINSIC_W_CHAIN;
16409     Info.memVT = MVT::i128;
16410     Info.ptrVal = I.getArgOperand(0);
16411     Info.offset = 0;
16412     Info.align = Align(16);
16413     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16414                  MachineMemOperand::MOVolatile;
16415     return true;
16416   case Intrinsic::ppc_atomic_load_i128:
16417     Info.opc = ISD::INTRINSIC_W_CHAIN;
16418     Info.memVT = MVT::i128;
16419     Info.ptrVal = I.getArgOperand(0);
16420     Info.offset = 0;
16421     Info.align = Align(16);
16422     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16423     return true;
16424   case Intrinsic::ppc_atomic_store_i128:
16425     Info.opc = ISD::INTRINSIC_VOID;
16426     Info.memVT = MVT::i128;
16427     Info.ptrVal = I.getArgOperand(2);
16428     Info.offset = 0;
16429     Info.align = Align(16);
16430     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16431     return true;
16432   case Intrinsic::ppc_altivec_lvx:
16433   case Intrinsic::ppc_altivec_lvxl:
16434   case Intrinsic::ppc_altivec_lvebx:
16435   case Intrinsic::ppc_altivec_lvehx:
16436   case Intrinsic::ppc_altivec_lvewx:
16437   case Intrinsic::ppc_vsx_lxvd2x:
16438   case Intrinsic::ppc_vsx_lxvw4x:
16439   case Intrinsic::ppc_vsx_lxvd2x_be:
16440   case Intrinsic::ppc_vsx_lxvw4x_be:
16441   case Intrinsic::ppc_vsx_lxvl:
16442   case Intrinsic::ppc_vsx_lxvll: {
16443     EVT VT;
16444     switch (Intrinsic) {
16445     case Intrinsic::ppc_altivec_lvebx:
16446       VT = MVT::i8;
16447       break;
16448     case Intrinsic::ppc_altivec_lvehx:
16449       VT = MVT::i16;
16450       break;
16451     case Intrinsic::ppc_altivec_lvewx:
16452       VT = MVT::i32;
16453       break;
16454     case Intrinsic::ppc_vsx_lxvd2x:
16455     case Intrinsic::ppc_vsx_lxvd2x_be:
16456       VT = MVT::v2f64;
16457       break;
16458     default:
16459       VT = MVT::v4i32;
16460       break;
16461     }
16462 
16463     Info.opc = ISD::INTRINSIC_W_CHAIN;
16464     Info.memVT = VT;
16465     Info.ptrVal = I.getArgOperand(0);
16466     Info.offset = -VT.getStoreSize()+1;
16467     Info.size = 2*VT.getStoreSize()-1;
16468     Info.align = Align(1);
16469     Info.flags = MachineMemOperand::MOLoad;
16470     return true;
16471   }
16472   case Intrinsic::ppc_altivec_stvx:
16473   case Intrinsic::ppc_altivec_stvxl:
16474   case Intrinsic::ppc_altivec_stvebx:
16475   case Intrinsic::ppc_altivec_stvehx:
16476   case Intrinsic::ppc_altivec_stvewx:
16477   case Intrinsic::ppc_vsx_stxvd2x:
16478   case Intrinsic::ppc_vsx_stxvw4x:
16479   case Intrinsic::ppc_vsx_stxvd2x_be:
16480   case Intrinsic::ppc_vsx_stxvw4x_be:
16481   case Intrinsic::ppc_vsx_stxvl:
16482   case Intrinsic::ppc_vsx_stxvll: {
16483     EVT VT;
16484     switch (Intrinsic) {
16485     case Intrinsic::ppc_altivec_stvebx:
16486       VT = MVT::i8;
16487       break;
16488     case Intrinsic::ppc_altivec_stvehx:
16489       VT = MVT::i16;
16490       break;
16491     case Intrinsic::ppc_altivec_stvewx:
16492       VT = MVT::i32;
16493       break;
16494     case Intrinsic::ppc_vsx_stxvd2x:
16495     case Intrinsic::ppc_vsx_stxvd2x_be:
16496       VT = MVT::v2f64;
16497       break;
16498     default:
16499       VT = MVT::v4i32;
16500       break;
16501     }
16502 
16503     Info.opc = ISD::INTRINSIC_VOID;
16504     Info.memVT = VT;
16505     Info.ptrVal = I.getArgOperand(1);
16506     Info.offset = -VT.getStoreSize()+1;
16507     Info.size = 2*VT.getStoreSize()-1;
16508     Info.align = Align(1);
16509     Info.flags = MachineMemOperand::MOStore;
16510     return true;
16511   }
16512   default:
16513     break;
16514   }
16515 
16516   return false;
16517 }
16518 
16519 /// It returns EVT::Other if the type should be determined using generic
16520 /// target-independent logic.
16521 EVT PPCTargetLowering::getOptimalMemOpType(
16522     const MemOp &Op, const AttributeList &FuncAttributes) const {
16523   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16524     // We should use Altivec/VSX loads and stores when available. For unaligned
16525     // addresses, unaligned VSX loads are only fast starting with the P8.
16526     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16527         (Op.isAligned(Align(16)) ||
16528          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16529       return MVT::v4i32;
16530   }
16531 
16532   if (Subtarget.isPPC64()) {
16533     return MVT::i64;
16534   }
16535 
16536   return MVT::i32;
16537 }
16538 
16539 /// Returns true if it is beneficial to convert a load of a constant
16540 /// to just the constant itself.
16541 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16542                                                           Type *Ty) const {
16543   assert(Ty->isIntegerTy());
16544 
16545   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16546   return !(BitSize == 0 || BitSize > 64);
16547 }
16548 
16549 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16550   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16551     return false;
16552   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16553   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16554   return NumBits1 == 64 && NumBits2 == 32;
16555 }
16556 
16557 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16558   if (!VT1.isInteger() || !VT2.isInteger())
16559     return false;
16560   unsigned NumBits1 = VT1.getSizeInBits();
16561   unsigned NumBits2 = VT2.getSizeInBits();
16562   return NumBits1 == 64 && NumBits2 == 32;
16563 }
16564 
16565 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16566   // Generally speaking, zexts are not free, but they are free when they can be
16567   // folded with other operations.
16568   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16569     EVT MemVT = LD->getMemoryVT();
16570     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16571          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16572         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16573          LD->getExtensionType() == ISD::ZEXTLOAD))
16574       return true;
16575   }
16576 
16577   // FIXME: Add other cases...
16578   //  - 32-bit shifts with a zext to i64
16579   //  - zext after ctlz, bswap, etc.
16580   //  - zext after and by a constant mask
16581 
16582   return TargetLowering::isZExtFree(Val, VT2);
16583 }
16584 
16585 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16586   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16587          "invalid fpext types");
16588   // Extending to float128 is not free.
16589   if (DestVT == MVT::f128)
16590     return false;
16591   return true;
16592 }
16593 
16594 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16595   return isInt<16>(Imm) || isUInt<16>(Imm);
16596 }
16597 
16598 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16599   return isInt<16>(Imm) || isUInt<16>(Imm);
16600 }
16601 
16602 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16603                                                        MachineMemOperand::Flags,
16604                                                        bool *Fast) const {
16605   if (DisablePPCUnaligned)
16606     return false;
16607 
16608   // PowerPC supports unaligned memory access for simple non-vector types.
16609   // Although accessing unaligned addresses is not as efficient as accessing
16610   // aligned addresses, it is generally more efficient than manual expansion,
16611   // and generally only traps for software emulation when crossing page
16612   // boundaries.
16613 
16614   if (!VT.isSimple())
16615     return false;
16616 
16617   if (VT.isFloatingPoint() && !VT.isVector() &&
16618       !Subtarget.allowsUnalignedFPAccess())
16619     return false;
16620 
16621   if (VT.getSimpleVT().isVector()) {
16622     if (Subtarget.hasVSX()) {
16623       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16624           VT != MVT::v4f32 && VT != MVT::v4i32)
16625         return false;
16626     } else {
16627       return false;
16628     }
16629   }
16630 
16631   if (VT == MVT::ppcf128)
16632     return false;
16633 
16634   if (Fast)
16635     *Fast = true;
16636 
16637   return true;
16638 }
16639 
16640 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16641                                                SDValue C) const {
16642   // Check integral scalar types.
16643   if (!VT.isScalarInteger())
16644     return false;
16645   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16646     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16647       return false;
16648     // This transformation will generate >= 2 operations. But the following
16649     // cases will generate <= 2 instructions during ISEL. So exclude them.
16650     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16651     // HW instruction, ie. MULLI
16652     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16653     // instruction is needed than case 1, ie. MULLI and RLDICR
16654     int64_t Imm = ConstNode->getSExtValue();
16655     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16656     Imm >>= Shift;
16657     if (isInt<16>(Imm))
16658       return false;
16659     uint64_t UImm = static_cast<uint64_t>(Imm);
16660     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16661         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16662       return true;
16663   }
16664   return false;
16665 }
16666 
16667 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16668                                                    EVT VT) const {
16669   return isFMAFasterThanFMulAndFAdd(
16670       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16671 }
16672 
16673 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16674                                                    Type *Ty) const {
16675   switch (Ty->getScalarType()->getTypeID()) {
16676   case Type::FloatTyID:
16677   case Type::DoubleTyID:
16678     return true;
16679   case Type::FP128TyID:
16680     return Subtarget.hasP9Vector();
16681   default:
16682     return false;
16683   }
16684 }
16685 
16686 // FIXME: add more patterns which are not profitable to hoist.
16687 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16688   if (!I->hasOneUse())
16689     return true;
16690 
16691   Instruction *User = I->user_back();
16692   assert(User && "A single use instruction with no uses.");
16693 
16694   switch (I->getOpcode()) {
16695   case Instruction::FMul: {
16696     // Don't break FMA, PowerPC prefers FMA.
16697     if (User->getOpcode() != Instruction::FSub &&
16698         User->getOpcode() != Instruction::FAdd)
16699       return true;
16700 
16701     const TargetOptions &Options = getTargetMachine().Options;
16702     const Function *F = I->getFunction();
16703     const DataLayout &DL = F->getParent()->getDataLayout();
16704     Type *Ty = User->getOperand(0)->getType();
16705 
16706     return !(
16707         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16708         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16709         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16710   }
16711   case Instruction::Load: {
16712     // Don't break "store (load float*)" pattern, this pattern will be combined
16713     // to "store (load int32)" in later InstCombine pass. See function
16714     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16715     // cycles than loading a 32 bit integer.
16716     LoadInst *LI = cast<LoadInst>(I);
16717     // For the loads that combineLoadToOperationType does nothing, like
16718     // ordered load, it should be profitable to hoist them.
16719     // For swifterror load, it can only be used for pointer to pointer type, so
16720     // later type check should get rid of this case.
16721     if (!LI->isUnordered())
16722       return true;
16723 
16724     if (User->getOpcode() != Instruction::Store)
16725       return true;
16726 
16727     if (I->getType()->getTypeID() != Type::FloatTyID)
16728       return true;
16729 
16730     return false;
16731   }
16732   default:
16733     return true;
16734   }
16735   return true;
16736 }
16737 
16738 const MCPhysReg *
16739 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16740   // LR is a callee-save register, but we must treat it as clobbered by any call
16741   // site. Hence we include LR in the scratch registers, which are in turn added
16742   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16743   // to CTR, which is used by any indirect call.
16744   static const MCPhysReg ScratchRegs[] = {
16745     PPC::X12, PPC::LR8, PPC::CTR8, 0
16746   };
16747 
16748   return ScratchRegs;
16749 }
16750 
16751 Register PPCTargetLowering::getExceptionPointerRegister(
16752     const Constant *PersonalityFn) const {
16753   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16754 }
16755 
16756 Register PPCTargetLowering::getExceptionSelectorRegister(
16757     const Constant *PersonalityFn) const {
16758   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16759 }
16760 
16761 bool
16762 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16763                      EVT VT , unsigned DefinedValues) const {
16764   if (VT == MVT::v2i64)
16765     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16766 
16767   if (Subtarget.hasVSX())
16768     return true;
16769 
16770   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16771 }
16772 
16773 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16774   if (DisableILPPref || Subtarget.enableMachineScheduler())
16775     return TargetLowering::getSchedulingPreference(N);
16776 
16777   return Sched::ILP;
16778 }
16779 
16780 // Create a fast isel object.
16781 FastISel *
16782 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16783                                   const TargetLibraryInfo *LibInfo) const {
16784   return PPC::createFastISel(FuncInfo, LibInfo);
16785 }
16786 
16787 // 'Inverted' means the FMA opcode after negating one multiplicand.
16788 // For example, (fma -a b c) = (fnmsub a b c)
16789 static unsigned invertFMAOpcode(unsigned Opc) {
16790   switch (Opc) {
16791   default:
16792     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16793   case ISD::FMA:
16794     return PPCISD::FNMSUB;
16795   case PPCISD::FNMSUB:
16796     return ISD::FMA;
16797   }
16798 }
16799 
16800 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16801                                                 bool LegalOps, bool OptForSize,
16802                                                 NegatibleCost &Cost,
16803                                                 unsigned Depth) const {
16804   if (Depth > SelectionDAG::MaxRecursionDepth)
16805     return SDValue();
16806 
16807   unsigned Opc = Op.getOpcode();
16808   EVT VT = Op.getValueType();
16809   SDNodeFlags Flags = Op.getNode()->getFlags();
16810 
16811   switch (Opc) {
16812   case PPCISD::FNMSUB:
16813     if (!Op.hasOneUse() || !isTypeLegal(VT))
16814       break;
16815 
16816     const TargetOptions &Options = getTargetMachine().Options;
16817     SDValue N0 = Op.getOperand(0);
16818     SDValue N1 = Op.getOperand(1);
16819     SDValue N2 = Op.getOperand(2);
16820     SDLoc Loc(Op);
16821 
16822     NegatibleCost N2Cost = NegatibleCost::Expensive;
16823     SDValue NegN2 =
16824         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16825 
16826     if (!NegN2)
16827       return SDValue();
16828 
16829     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16830     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16831     // These transformations may change sign of zeroes. For example,
16832     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16833     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16834       // Try and choose the cheaper one to negate.
16835       NegatibleCost N0Cost = NegatibleCost::Expensive;
16836       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16837                                            N0Cost, Depth + 1);
16838 
16839       NegatibleCost N1Cost = NegatibleCost::Expensive;
16840       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16841                                            N1Cost, Depth + 1);
16842 
16843       if (NegN0 && N0Cost <= N1Cost) {
16844         Cost = std::min(N0Cost, N2Cost);
16845         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16846       } else if (NegN1) {
16847         Cost = std::min(N1Cost, N2Cost);
16848         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16849       }
16850     }
16851 
16852     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16853     if (isOperationLegal(ISD::FMA, VT)) {
16854       Cost = N2Cost;
16855       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16856     }
16857 
16858     break;
16859   }
16860 
16861   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16862                                               Cost, Depth);
16863 }
16864 
16865 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16866 bool PPCTargetLowering::useLoadStackGuardNode() const {
16867   if (!Subtarget.isTargetLinux())
16868     return TargetLowering::useLoadStackGuardNode();
16869   return true;
16870 }
16871 
16872 // Override to disable global variable loading on Linux and insert AIX canary
16873 // word declaration.
16874 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16875   if (Subtarget.isAIXABI()) {
16876     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16877                         Type::getInt8PtrTy(M.getContext()));
16878     return;
16879   }
16880   if (!Subtarget.isTargetLinux())
16881     return TargetLowering::insertSSPDeclarations(M);
16882 }
16883 
16884 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16885   if (Subtarget.isAIXABI())
16886     return M.getGlobalVariable(AIXSSPCanaryWordName);
16887   return TargetLowering::getSDagStackGuard(M);
16888 }
16889 
16890 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16891                                      bool ForCodeSize) const {
16892   if (!VT.isSimple() || !Subtarget.hasVSX())
16893     return false;
16894 
16895   switch(VT.getSimpleVT().SimpleTy) {
16896   default:
16897     // For FP types that are currently not supported by PPC backend, return
16898     // false. Examples: f16, f80.
16899     return false;
16900   case MVT::f32:
16901   case MVT::f64:
16902     if (Subtarget.hasPrefixInstrs()) {
16903       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16904       return true;
16905     }
16906     LLVM_FALLTHROUGH;
16907   case MVT::ppcf128:
16908     return Imm.isPosZero();
16909   }
16910 }
16911 
16912 // For vector shift operation op, fold
16913 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16914 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16915                                   SelectionDAG &DAG) {
16916   SDValue N0 = N->getOperand(0);
16917   SDValue N1 = N->getOperand(1);
16918   EVT VT = N0.getValueType();
16919   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16920   unsigned Opcode = N->getOpcode();
16921   unsigned TargetOpcode;
16922 
16923   switch (Opcode) {
16924   default:
16925     llvm_unreachable("Unexpected shift operation");
16926   case ISD::SHL:
16927     TargetOpcode = PPCISD::SHL;
16928     break;
16929   case ISD::SRL:
16930     TargetOpcode = PPCISD::SRL;
16931     break;
16932   case ISD::SRA:
16933     TargetOpcode = PPCISD::SRA;
16934     break;
16935   }
16936 
16937   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16938       N1->getOpcode() == ISD::AND)
16939     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16940       if (Mask->getZExtValue() == OpSizeInBits - 1)
16941         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16942 
16943   return SDValue();
16944 }
16945 
16946 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16947   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16948     return Value;
16949 
16950   SDValue N0 = N->getOperand(0);
16951   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16952   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16953       N0.getOpcode() != ISD::SIGN_EXTEND ||
16954       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16955       N->getValueType(0) != MVT::i64)
16956     return SDValue();
16957 
16958   // We can't save an operation here if the value is already extended, and
16959   // the existing shift is easier to combine.
16960   SDValue ExtsSrc = N0.getOperand(0);
16961   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16962       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16963     return SDValue();
16964 
16965   SDLoc DL(N0);
16966   SDValue ShiftBy = SDValue(CN1, 0);
16967   // We want the shift amount to be i32 on the extswli, but the shift could
16968   // have an i64.
16969   if (ShiftBy.getValueType() == MVT::i64)
16970     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16971 
16972   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16973                          ShiftBy);
16974 }
16975 
16976 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16977   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16978     return Value;
16979 
16980   return SDValue();
16981 }
16982 
16983 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16984   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16985     return Value;
16986 
16987   return SDValue();
16988 }
16989 
16990 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16991 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16992 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16993 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16994 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16995                                  const PPCSubtarget &Subtarget) {
16996   if (!Subtarget.isPPC64())
16997     return SDValue();
16998 
16999   SDValue LHS = N->getOperand(0);
17000   SDValue RHS = N->getOperand(1);
17001 
17002   auto isZextOfCompareWithConstant = [](SDValue Op) {
17003     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
17004         Op.getValueType() != MVT::i64)
17005       return false;
17006 
17007     SDValue Cmp = Op.getOperand(0);
17008     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
17009         Cmp.getOperand(0).getValueType() != MVT::i64)
17010       return false;
17011 
17012     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
17013       int64_t NegConstant = 0 - Constant->getSExtValue();
17014       // Due to the limitations of the addi instruction,
17015       // -C is required to be [-32768, 32767].
17016       return isInt<16>(NegConstant);
17017     }
17018 
17019     return false;
17020   };
17021 
17022   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
17023   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
17024 
17025   // If there is a pattern, canonicalize a zext operand to the RHS.
17026   if (LHSHasPattern && !RHSHasPattern)
17027     std::swap(LHS, RHS);
17028   else if (!LHSHasPattern && !RHSHasPattern)
17029     return SDValue();
17030 
17031   SDLoc DL(N);
17032   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
17033   SDValue Cmp = RHS.getOperand(0);
17034   SDValue Z = Cmp.getOperand(0);
17035   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
17036   int64_t NegConstant = 0 - Constant->getSExtValue();
17037 
17038   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
17039   default: break;
17040   case ISD::SETNE: {
17041     //                                 when C == 0
17042     //                             --> addze X, (addic Z, -1).carry
17043     //                            /
17044     // add X, (zext(setne Z, C))--
17045     //                            \    when -32768 <= -C <= 32767 && C != 0
17046     //                             --> addze X, (addic (addi Z, -C), -1).carry
17047     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17048                               DAG.getConstant(NegConstant, DL, MVT::i64));
17049     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17050     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17051                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
17052     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17053                        SDValue(Addc.getNode(), 1));
17054     }
17055   case ISD::SETEQ: {
17056     //                                 when C == 0
17057     //                             --> addze X, (subfic Z, 0).carry
17058     //                            /
17059     // add X, (zext(sete  Z, C))--
17060     //                            \    when -32768 <= -C <= 32767 && C != 0
17061     //                             --> addze X, (subfic (addi Z, -C), 0).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 Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17066                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
17067     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17068                        SDValue(Subc.getNode(), 1));
17069     }
17070   }
17071 
17072   return SDValue();
17073 }
17074 
17075 // Transform
17076 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17077 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17078 // In this case both C1 and C2 must be known constants.
17079 // C1+C2 must fit into a 34 bit signed integer.
17080 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17081                                           const PPCSubtarget &Subtarget) {
17082   if (!Subtarget.isUsingPCRelativeCalls())
17083     return SDValue();
17084 
17085   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17086   // If we find that node try to cast the Global Address and the Constant.
17087   SDValue LHS = N->getOperand(0);
17088   SDValue RHS = N->getOperand(1);
17089 
17090   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17091     std::swap(LHS, RHS);
17092 
17093   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17094     return SDValue();
17095 
17096   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17097   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17098   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17099 
17100   // Check that both casts succeeded.
17101   if (!GSDN || !ConstNode)
17102     return SDValue();
17103 
17104   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17105   SDLoc DL(GSDN);
17106 
17107   // The signed int offset needs to fit in 34 bits.
17108   if (!isInt<34>(NewOffset))
17109     return SDValue();
17110 
17111   // The new global address is a copy of the old global address except
17112   // that it has the updated Offset.
17113   SDValue GA =
17114       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17115                                  NewOffset, GSDN->getTargetFlags());
17116   SDValue MatPCRel =
17117       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17118   return MatPCRel;
17119 }
17120 
17121 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17122   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17123     return Value;
17124 
17125   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17126     return Value;
17127 
17128   return SDValue();
17129 }
17130 
17131 // Detect TRUNCATE operations on bitcasts of float128 values.
17132 // What we are looking for here is the situtation where we extract a subset
17133 // of bits from a 128 bit float.
17134 // This can be of two forms:
17135 // 1) BITCAST of f128 feeding TRUNCATE
17136 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17137 // The reason this is required is because we do not have a legal i128 type
17138 // and so we want to prevent having to store the f128 and then reload part
17139 // of it.
17140 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17141                                            DAGCombinerInfo &DCI) const {
17142   // If we are using CRBits then try that first.
17143   if (Subtarget.useCRBits()) {
17144     // Check if CRBits did anything and return that if it did.
17145     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17146       return CRTruncValue;
17147   }
17148 
17149   SDLoc dl(N);
17150   SDValue Op0 = N->getOperand(0);
17151 
17152   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17153   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17154     EVT VT = N->getValueType(0);
17155     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17156       return SDValue();
17157     SDValue Sub = Op0.getOperand(0);
17158     if (Sub.getOpcode() == ISD::SUB) {
17159       SDValue SubOp0 = Sub.getOperand(0);
17160       SDValue SubOp1 = Sub.getOperand(1);
17161       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17162           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17163         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17164                                SubOp1.getOperand(0),
17165                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17166       }
17167     }
17168   }
17169 
17170   // Looking for a truncate of i128 to i64.
17171   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17172     return SDValue();
17173 
17174   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17175 
17176   // SRL feeding TRUNCATE.
17177   if (Op0.getOpcode() == ISD::SRL) {
17178     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17179     // The right shift has to be by 64 bits.
17180     if (!ConstNode || ConstNode->getZExtValue() != 64)
17181       return SDValue();
17182 
17183     // Switch the element number to extract.
17184     EltToExtract = EltToExtract ? 0 : 1;
17185     // Update Op0 past the SRL.
17186     Op0 = Op0.getOperand(0);
17187   }
17188 
17189   // BITCAST feeding a TRUNCATE possibly via SRL.
17190   if (Op0.getOpcode() == ISD::BITCAST &&
17191       Op0.getValueType() == MVT::i128 &&
17192       Op0.getOperand(0).getValueType() == MVT::f128) {
17193     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17194     return DCI.DAG.getNode(
17195         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17196         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17197   }
17198   return SDValue();
17199 }
17200 
17201 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17202   SelectionDAG &DAG = DCI.DAG;
17203 
17204   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17205   if (!ConstOpOrElement)
17206     return SDValue();
17207 
17208   // An imul is usually smaller than the alternative sequence for legal type.
17209   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17210       isOperationLegal(ISD::MUL, N->getValueType(0)))
17211     return SDValue();
17212 
17213   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17214     switch (this->Subtarget.getCPUDirective()) {
17215     default:
17216       // TODO: enhance the condition for subtarget before pwr8
17217       return false;
17218     case PPC::DIR_PWR8:
17219       //  type        mul     add    shl
17220       // scalar        4       1      1
17221       // vector        7       2      2
17222       return true;
17223     case PPC::DIR_PWR9:
17224     case PPC::DIR_PWR10:
17225     case PPC::DIR_PWR_FUTURE:
17226       //  type        mul     add    shl
17227       // scalar        5       2      2
17228       // vector        7       2      2
17229 
17230       // The cycle RATIO of related operations are showed as a table above.
17231       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17232       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17233       // are 4, it is always profitable; but for 3 instrs patterns
17234       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17235       // So we should only do it for vector type.
17236       return IsAddOne && IsNeg ? VT.isVector() : true;
17237     }
17238   };
17239 
17240   EVT VT = N->getValueType(0);
17241   SDLoc DL(N);
17242 
17243   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17244   bool IsNeg = MulAmt.isNegative();
17245   APInt MulAmtAbs = MulAmt.abs();
17246 
17247   if ((MulAmtAbs - 1).isPowerOf2()) {
17248     // (mul x, 2^N + 1) => (add (shl x, N), x)
17249     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17250 
17251     if (!IsProfitable(IsNeg, true, VT))
17252       return SDValue();
17253 
17254     SDValue Op0 = N->getOperand(0);
17255     SDValue Op1 =
17256         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17257                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17258     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17259 
17260     if (!IsNeg)
17261       return Res;
17262 
17263     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17264   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17265     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17266     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17267 
17268     if (!IsProfitable(IsNeg, false, VT))
17269       return SDValue();
17270 
17271     SDValue Op0 = N->getOperand(0);
17272     SDValue Op1 =
17273         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17274                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17275 
17276     if (!IsNeg)
17277       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17278     else
17279       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17280 
17281   } else {
17282     return SDValue();
17283   }
17284 }
17285 
17286 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17287 // in combiner since we need to check SD flags and other subtarget features.
17288 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17289                                           DAGCombinerInfo &DCI) const {
17290   SDValue N0 = N->getOperand(0);
17291   SDValue N1 = N->getOperand(1);
17292   SDValue N2 = N->getOperand(2);
17293   SDNodeFlags Flags = N->getFlags();
17294   EVT VT = N->getValueType(0);
17295   SelectionDAG &DAG = DCI.DAG;
17296   const TargetOptions &Options = getTargetMachine().Options;
17297   unsigned Opc = N->getOpcode();
17298   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17299   bool LegalOps = !DCI.isBeforeLegalizeOps();
17300   SDLoc Loc(N);
17301 
17302   if (!isOperationLegal(ISD::FMA, VT))
17303     return SDValue();
17304 
17305   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17306   // since (fnmsub a b c)=-0 while c-ab=+0.
17307   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17308     return SDValue();
17309 
17310   // (fma (fneg a) b c) => (fnmsub a b c)
17311   // (fnmsub (fneg a) b c) => (fma a b c)
17312   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17313     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17314 
17315   // (fma a (fneg b) c) => (fnmsub a b c)
17316   // (fnmsub a (fneg b) c) => (fma a b c)
17317   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17318     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17319 
17320   return SDValue();
17321 }
17322 
17323 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17324   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17325   if (!Subtarget.is64BitELFABI())
17326     return false;
17327 
17328   // If not a tail call then no need to proceed.
17329   if (!CI->isTailCall())
17330     return false;
17331 
17332   // If sibling calls have been disabled and tail-calls aren't guaranteed
17333   // there is no reason to duplicate.
17334   auto &TM = getTargetMachine();
17335   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17336     return false;
17337 
17338   // Can't tail call a function called indirectly, or if it has variadic args.
17339   const Function *Callee = CI->getCalledFunction();
17340   if (!Callee || Callee->isVarArg())
17341     return false;
17342 
17343   // Make sure the callee and caller calling conventions are eligible for tco.
17344   const Function *Caller = CI->getParent()->getParent();
17345   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17346                                            CI->getCallingConv()))
17347       return false;
17348 
17349   // If the function is local then we have a good chance at tail-calling it
17350   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17351 }
17352 
17353 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17354   if (!Subtarget.hasVSX())
17355     return false;
17356   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17357     return true;
17358   return VT == MVT::f32 || VT == MVT::f64 ||
17359     VT == MVT::v4f32 || VT == MVT::v2f64;
17360 }
17361 
17362 bool PPCTargetLowering::
17363 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17364   const Value *Mask = AndI.getOperand(1);
17365   // If the mask is suitable for andi. or andis. we should sink the and.
17366   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17367     // Can't handle constants wider than 64-bits.
17368     if (CI->getBitWidth() > 64)
17369       return false;
17370     int64_t ConstVal = CI->getZExtValue();
17371     return isUInt<16>(ConstVal) ||
17372       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17373   }
17374 
17375   // For non-constant masks, we can always use the record-form and.
17376   return true;
17377 }
17378 
17379 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17380 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17381 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17382 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17383 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17384 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17385   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17386   assert(Subtarget.hasP9Altivec() &&
17387          "Only combine this when P9 altivec supported!");
17388   EVT VT = N->getValueType(0);
17389   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17390     return SDValue();
17391 
17392   SelectionDAG &DAG = DCI.DAG;
17393   SDLoc dl(N);
17394   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17395     // Even for signed integers, if it's known to be positive (as signed
17396     // integer) due to zero-extended inputs.
17397     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17398     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17399     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17400          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17401         (SubOpcd1 == ISD::ZERO_EXTEND ||
17402          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17403       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17404                          N->getOperand(0)->getOperand(0),
17405                          N->getOperand(0)->getOperand(1),
17406                          DAG.getTargetConstant(0, dl, MVT::i32));
17407     }
17408 
17409     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17410     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17411         N->getOperand(0).hasOneUse()) {
17412       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17413                          N->getOperand(0)->getOperand(0),
17414                          N->getOperand(0)->getOperand(1),
17415                          DAG.getTargetConstant(1, dl, MVT::i32));
17416     }
17417   }
17418 
17419   return SDValue();
17420 }
17421 
17422 // For type v4i32/v8ii16/v16i8, transform
17423 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17424 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17425 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17426 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17427 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17428                                           DAGCombinerInfo &DCI) const {
17429   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17430   assert(Subtarget.hasP9Altivec() &&
17431          "Only combine this when P9 altivec supported!");
17432 
17433   SelectionDAG &DAG = DCI.DAG;
17434   SDLoc dl(N);
17435   SDValue Cond = N->getOperand(0);
17436   SDValue TrueOpnd = N->getOperand(1);
17437   SDValue FalseOpnd = N->getOperand(2);
17438   EVT VT = N->getOperand(1).getValueType();
17439 
17440   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17441       FalseOpnd.getOpcode() != ISD::SUB)
17442     return SDValue();
17443 
17444   // ABSD only available for type v4i32/v8i16/v16i8
17445   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17446     return SDValue();
17447 
17448   // At least to save one more dependent computation
17449   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17450     return SDValue();
17451 
17452   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17453 
17454   // Can only handle unsigned comparison here
17455   switch (CC) {
17456   default:
17457     return SDValue();
17458   case ISD::SETUGT:
17459   case ISD::SETUGE:
17460     break;
17461   case ISD::SETULT:
17462   case ISD::SETULE:
17463     std::swap(TrueOpnd, FalseOpnd);
17464     break;
17465   }
17466 
17467   SDValue CmpOpnd1 = Cond.getOperand(0);
17468   SDValue CmpOpnd2 = Cond.getOperand(1);
17469 
17470   // SETCC CmpOpnd1 CmpOpnd2 cond
17471   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17472   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17473   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17474       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17475       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17476       FalseOpnd.getOperand(1) == CmpOpnd1) {
17477     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17478                        CmpOpnd1, CmpOpnd2,
17479                        DAG.getTargetConstant(0, dl, MVT::i32));
17480   }
17481 
17482   return SDValue();
17483 }
17484 
17485 /// getAddrModeForFlags - Based on the set of address flags, select the most
17486 /// optimal instruction format to match by.
17487 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17488   // This is not a node we should be handling here.
17489   if (Flags == PPC::MOF_None)
17490     return PPC::AM_None;
17491   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17492   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17493     if ((Flags & FlagSet) == FlagSet)
17494       return PPC::AM_DForm;
17495   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17496     if ((Flags & FlagSet) == FlagSet)
17497       return PPC::AM_DSForm;
17498   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17499     if ((Flags & FlagSet) == FlagSet)
17500       return PPC::AM_DQForm;
17501   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17502     if ((Flags & FlagSet) == FlagSet)
17503       return PPC::AM_PrefixDForm;
17504   // If no other forms are selected, return an X-Form as it is the most
17505   // general addressing mode.
17506   return PPC::AM_XForm;
17507 }
17508 
17509 /// Set alignment flags based on whether or not the Frame Index is aligned.
17510 /// Utilized when computing flags for address computation when selecting
17511 /// load and store instructions.
17512 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17513                                SelectionDAG &DAG) {
17514   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17515   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17516   if (!FI)
17517     return;
17518   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17519   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17520   // If this is (add $FI, $S16Imm), the alignment flags are already set
17521   // based on the immediate. We just need to clear the alignment flags
17522   // if the FI alignment is weaker.
17523   if ((FrameIndexAlign % 4) != 0)
17524     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17525   if ((FrameIndexAlign % 16) != 0)
17526     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17527   // If the address is a plain FrameIndex, set alignment flags based on
17528   // FI alignment.
17529   if (!IsAdd) {
17530     if ((FrameIndexAlign % 4) == 0)
17531       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17532     if ((FrameIndexAlign % 16) == 0)
17533       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17534   }
17535 }
17536 
17537 /// Given a node, compute flags that are used for address computation when
17538 /// selecting load and store instructions. The flags computed are stored in
17539 /// FlagSet. This function takes into account whether the node is a constant,
17540 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17541 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17542                                               SelectionDAG &DAG) {
17543   // Set the alignment flags for the node depending on if the node is
17544   // 4-byte or 16-byte aligned.
17545   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17546     if ((Imm & 0x3) == 0)
17547       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17548     if ((Imm & 0xf) == 0)
17549       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17550   };
17551 
17552   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17553     // All 32-bit constants can be computed as LIS + Disp.
17554     const APInt &ConstImm = CN->getAPIntValue();
17555     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17556       FlagSet |= PPC::MOF_AddrIsSImm32;
17557       SetAlignFlagsForImm(ConstImm.getZExtValue());
17558       setAlignFlagsForFI(N, FlagSet, DAG);
17559     }
17560     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17561       FlagSet |= PPC::MOF_RPlusSImm34;
17562     else // Let constant materialization handle large constants.
17563       FlagSet |= PPC::MOF_NotAddNorCst;
17564   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17565     // This address can be represented as an addition of:
17566     // - Register + Imm16 (possibly a multiple of 4/16)
17567     // - Register + Imm34
17568     // - Register + PPCISD::Lo
17569     // - Register + Register
17570     // In any case, we won't have to match this as Base + Zero.
17571     SDValue RHS = N.getOperand(1);
17572     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17573       const APInt &ConstImm = CN->getAPIntValue();
17574       if (ConstImm.isSignedIntN(16)) {
17575         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17576         SetAlignFlagsForImm(ConstImm.getZExtValue());
17577         setAlignFlagsForFI(N, FlagSet, DAG);
17578       }
17579       if (ConstImm.isSignedIntN(34))
17580         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17581       else
17582         FlagSet |= PPC::MOF_RPlusR; // Register.
17583     } else if (RHS.getOpcode() == PPCISD::Lo &&
17584                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17585       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17586     else
17587       FlagSet |= PPC::MOF_RPlusR;
17588   } else { // The address computation is not a constant or an addition.
17589     setAlignFlagsForFI(N, FlagSet, DAG);
17590     FlagSet |= PPC::MOF_NotAddNorCst;
17591   }
17592 }
17593 
17594 static bool isPCRelNode(SDValue N) {
17595   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17596       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17597       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17598       isValidPCRelNode<JumpTableSDNode>(N) ||
17599       isValidPCRelNode<BlockAddressSDNode>(N));
17600 }
17601 
17602 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17603 /// the address flags of the load/store instruction that is to be matched.
17604 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17605                                            SelectionDAG &DAG) const {
17606   unsigned FlagSet = PPC::MOF_None;
17607 
17608   // Compute subtarget flags.
17609   if (!Subtarget.hasP9Vector())
17610     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17611   else {
17612     FlagSet |= PPC::MOF_SubtargetP9;
17613     if (Subtarget.hasPrefixInstrs())
17614       FlagSet |= PPC::MOF_SubtargetP10;
17615   }
17616   if (Subtarget.hasSPE())
17617     FlagSet |= PPC::MOF_SubtargetSPE;
17618 
17619   // Check if we have a PCRel node and return early.
17620   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17621     return FlagSet;
17622 
17623   // If the node is the paired load/store intrinsics, compute flags for
17624   // address computation and return early.
17625   unsigned ParentOp = Parent->getOpcode();
17626   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17627                                (ParentOp == ISD::INTRINSIC_VOID))) {
17628     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17629     if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
17630       SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
17631                              ? Parent->getOperand(2)
17632                              : Parent->getOperand(3);
17633       computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17634       FlagSet |= PPC::MOF_Vector;
17635       return FlagSet;
17636     }
17637   }
17638 
17639   // Mark this as something we don't want to handle here if it is atomic
17640   // or pre-increment instruction.
17641   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17642     if (LSB->isIndexed())
17643       return PPC::MOF_None;
17644 
17645   // Compute in-memory type flags. This is based on if there are scalars,
17646   // floats or vectors.
17647   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17648   assert(MN && "Parent should be a MemSDNode!");
17649   EVT MemVT = MN->getMemoryVT();
17650   unsigned Size = MemVT.getSizeInBits();
17651   if (MemVT.isScalarInteger()) {
17652     assert(Size <= 128 &&
17653            "Not expecting scalar integers larger than 16 bytes!");
17654     if (Size < 32)
17655       FlagSet |= PPC::MOF_SubWordInt;
17656     else if (Size == 32)
17657       FlagSet |= PPC::MOF_WordInt;
17658     else
17659       FlagSet |= PPC::MOF_DoubleWordInt;
17660   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17661     if (Size == 128)
17662       FlagSet |= PPC::MOF_Vector;
17663     else if (Size == 256) {
17664       assert(Subtarget.pairedVectorMemops() &&
17665              "256-bit vectors are only available when paired vector memops is "
17666              "enabled!");
17667       FlagSet |= PPC::MOF_Vector;
17668     } else
17669       llvm_unreachable("Not expecting illegal vectors!");
17670   } else { // Floating point type: can be scalar, f128 or vector types.
17671     if (Size == 32 || Size == 64)
17672       FlagSet |= PPC::MOF_ScalarFloat;
17673     else if (MemVT == MVT::f128 || MemVT.isVector())
17674       FlagSet |= PPC::MOF_Vector;
17675     else
17676       llvm_unreachable("Not expecting illegal scalar floats!");
17677   }
17678 
17679   // Compute flags for address computation.
17680   computeFlagsForAddressComputation(N, FlagSet, DAG);
17681 
17682   // Compute type extension flags.
17683   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17684     switch (LN->getExtensionType()) {
17685     case ISD::SEXTLOAD:
17686       FlagSet |= PPC::MOF_SExt;
17687       break;
17688     case ISD::EXTLOAD:
17689     case ISD::ZEXTLOAD:
17690       FlagSet |= PPC::MOF_ZExt;
17691       break;
17692     case ISD::NON_EXTLOAD:
17693       FlagSet |= PPC::MOF_NoExt;
17694       break;
17695     }
17696   } else
17697     FlagSet |= PPC::MOF_NoExt;
17698 
17699   // For integers, no extension is the same as zero extension.
17700   // We set the extension mode to zero extension so we don't have
17701   // to add separate entries in AddrModesMap for loads and stores.
17702   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17703     FlagSet |= PPC::MOF_ZExt;
17704     FlagSet &= ~PPC::MOF_NoExt;
17705   }
17706 
17707   // If we don't have prefixed instructions, 34-bit constants should be
17708   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17709   bool IsNonP1034BitConst =
17710       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17711        FlagSet) == PPC::MOF_RPlusSImm34;
17712   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17713       IsNonP1034BitConst)
17714     FlagSet |= PPC::MOF_NotAddNorCst;
17715 
17716   return FlagSet;
17717 }
17718 
17719 /// SelectForceXFormMode - Given the specified address, force it to be
17720 /// represented as an indexed [r+r] operation (an XForm instruction).
17721 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17722                                                       SDValue &Base,
17723                                                       SelectionDAG &DAG) const {
17724 
17725   PPC::AddrMode Mode = PPC::AM_XForm;
17726   int16_t ForceXFormImm = 0;
17727   if (provablyDisjointOr(DAG, N) &&
17728       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17729     Disp = N.getOperand(0);
17730     Base = N.getOperand(1);
17731     return Mode;
17732   }
17733 
17734   // If the address is the result of an add, we will utilize the fact that the
17735   // address calculation includes an implicit add.  However, we can reduce
17736   // register pressure if we do not materialize a constant just for use as the
17737   // index register.  We only get rid of the add if it is not an add of a
17738   // value and a 16-bit signed constant and both have a single use.
17739   if (N.getOpcode() == ISD::ADD &&
17740       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17741        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17742     Disp = N.getOperand(0);
17743     Base = N.getOperand(1);
17744     return Mode;
17745   }
17746 
17747   // Otherwise, use R0 as the base register.
17748   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17749                          N.getValueType());
17750   Base = N;
17751 
17752   return Mode;
17753 }
17754 
17755 bool PPCTargetLowering::splitValueIntoRegisterParts(
17756     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
17757     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
17758   EVT ValVT = Val.getValueType();
17759   // If we are splitting a scalar integer into f64 parts (i.e. so they
17760   // can be placed into VFRC registers), we need to zero extend and
17761   // bitcast the values. This will ensure the value is placed into a
17762   // VSR using direct moves or stack operations as needed.
17763   if (PartVT == MVT::f64 &&
17764       (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
17765     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
17766     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
17767     Parts[0] = Val;
17768     return true;
17769   }
17770   return false;
17771 }
17772 
17773 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
17774                                           SelectionDAG &DAG) const {
17775   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17776   TargetLowering::CallLoweringInfo CLI(DAG);
17777   EVT RetVT = Op.getValueType();
17778   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
17779   SDValue Callee =
17780       DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
17781   bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
17782   TargetLowering::ArgListTy Args;
17783   TargetLowering::ArgListEntry Entry;
17784   for (const SDValue &N : Op->op_values()) {
17785     EVT ArgVT = N.getValueType();
17786     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17787     Entry.Node = N;
17788     Entry.Ty = ArgTy;
17789     Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
17790     Entry.IsZExt = !Entry.IsSExt;
17791     Args.push_back(Entry);
17792   }
17793 
17794   SDValue InChain = DAG.getEntryNode();
17795   SDValue TCChain = InChain;
17796   const Function &F = DAG.getMachineFunction().getFunction();
17797   bool isTailCall =
17798       TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
17799       (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
17800   if (isTailCall)
17801     InChain = TCChain;
17802   CLI.setDebugLoc(SDLoc(Op))
17803       .setChain(InChain)
17804       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
17805       .setTailCall(isTailCall)
17806       .setSExtResult(SignExtend)
17807       .setZExtResult(!SignExtend)
17808       .setIsPostTypeLegalization(true);
17809   return TLI.LowerCallTo(CLI).first;
17810 }
17811 
17812 SDValue PPCTargetLowering::lowerLibCallBasedOnType(
17813     const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
17814     SelectionDAG &DAG) const {
17815   if (Op.getValueType() == MVT::f32)
17816     return lowerToLibCall(LibCallFloatName, Op, DAG);
17817 
17818   if (Op.getValueType() == MVT::f64)
17819     return lowerToLibCall(LibCallDoubleName, Op, DAG);
17820 
17821   return SDValue();
17822 }
17823 
17824 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
17825   SDNodeFlags Flags = Op.getNode()->getFlags();
17826   return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
17827          Flags.hasNoNaNs() && Flags.hasNoInfs();
17828 }
17829 
17830 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
17831   return Op.getNode()->getFlags().hasApproximateFuncs();
17832 }
17833 
17834 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
17835                                             const char *LibCallFloatName,
17836                                             const char *LibCallDoubleNameFinite,
17837                                             const char *LibCallFloatNameFinite,
17838                                             SDValue Op,
17839                                             SelectionDAG &DAG) const {
17840   if (!isLowringToMASSSafe(Op))
17841     return SDValue();
17842 
17843   if (!isLowringToMASSFiniteSafe(Op))
17844     return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
17845                                    DAG);
17846 
17847   return lowerLibCallBasedOnType(LibCallFloatNameFinite,
17848                                  LibCallDoubleNameFinite, Op, DAG);
17849 }
17850 
17851 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
17852   return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
17853                           "__xl_powf_finite", Op, DAG);
17854 }
17855 
17856 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
17857   return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
17858                           "__xl_sinf_finite", Op, DAG);
17859 }
17860 
17861 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
17862   return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
17863                           "__xl_cosf_finite", Op, DAG);
17864 }
17865 
17866 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
17867   return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
17868                           "__xl_logf_finite", Op, DAG);
17869 }
17870 
17871 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
17872   return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
17873                           "__xl_log10f_finite", Op, DAG);
17874 }
17875 
17876 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
17877   return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
17878                           "__xl_expf_finite", Op, DAG);
17879 }
17880 
17881 // If we happen to match to an aligned D-Form, check if the Frame Index is
17882 // adequately aligned. If it is not, reset the mode to match to X-Form.
17883 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17884                                    PPC::AddrMode &Mode) {
17885   if (!isa<FrameIndexSDNode>(N))
17886     return;
17887   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17888       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17889     Mode = PPC::AM_XForm;
17890 }
17891 
17892 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17893 /// compute the address flags of the node, get the optimal address mode based
17894 /// on the flags, and set the Base and Disp based on the address mode.
17895 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17896                                                        SDValue N, SDValue &Disp,
17897                                                        SDValue &Base,
17898                                                        SelectionDAG &DAG,
17899                                                        MaybeAlign Align) const {
17900   SDLoc DL(Parent);
17901 
17902   // Compute the address flags.
17903   unsigned Flags = computeMOFlags(Parent, N, DAG);
17904 
17905   // Get the optimal address mode based on the Flags.
17906   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17907 
17908   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17909   // Select an X-Form load if it is not.
17910   setXFormForUnalignedFI(N, Flags, Mode);
17911 
17912   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17913   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17914     assert(Subtarget.isUsingPCRelativeCalls() &&
17915            "Must be using PC-Relative calls when a valid PC-Relative node is "
17916            "present!");
17917     Mode = PPC::AM_PCRel;
17918   }
17919 
17920   // Set Base and Disp accordingly depending on the address mode.
17921   switch (Mode) {
17922   case PPC::AM_DForm:
17923   case PPC::AM_DSForm:
17924   case PPC::AM_DQForm: {
17925     // This is a register plus a 16-bit immediate. The base will be the
17926     // register and the displacement will be the immediate unless it
17927     // isn't sufficiently aligned.
17928     if (Flags & PPC::MOF_RPlusSImm16) {
17929       SDValue Op0 = N.getOperand(0);
17930       SDValue Op1 = N.getOperand(1);
17931       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17932       if (!Align || isAligned(*Align, Imm)) {
17933         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17934         Base = Op0;
17935         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17936           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17937           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17938         }
17939         break;
17940       }
17941     }
17942     // This is a register plus the @lo relocation. The base is the register
17943     // and the displacement is the global address.
17944     else if (Flags & PPC::MOF_RPlusLo) {
17945       Disp = N.getOperand(1).getOperand(0); // The global address.
17946       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17947              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17948              Disp.getOpcode() == ISD::TargetConstantPool ||
17949              Disp.getOpcode() == ISD::TargetJumpTable);
17950       Base = N.getOperand(0);
17951       break;
17952     }
17953     // This is a constant address at most 32 bits. The base will be
17954     // zero or load-immediate-shifted and the displacement will be
17955     // the low 16 bits of the address.
17956     else if (Flags & PPC::MOF_AddrIsSImm32) {
17957       auto *CN = cast<ConstantSDNode>(N);
17958       EVT CNType = CN->getValueType(0);
17959       uint64_t CNImm = CN->getZExtValue();
17960       // If this address fits entirely in a 16-bit sext immediate field, codegen
17961       // this as "d, 0".
17962       int16_t Imm;
17963       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17964         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17965         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17966                                CNType);
17967         break;
17968       }
17969       // Handle 32-bit sext immediate with LIS + Addr mode.
17970       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17971           (!Align || isAligned(*Align, CNImm))) {
17972         int32_t Addr = (int32_t)CNImm;
17973         // Otherwise, break this down into LIS + Disp.
17974         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17975         Base =
17976             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17977         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17978         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17979         break;
17980       }
17981     }
17982     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17983     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17984     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17985       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17986       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17987     } else
17988       Base = N;
17989     break;
17990   }
17991   case PPC::AM_PrefixDForm: {
17992     int64_t Imm34 = 0;
17993     unsigned Opcode = N.getOpcode();
17994     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17995         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17996       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17997       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17998       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17999         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18000       else
18001         Base = N.getOperand(0);
18002     } else if (isIntS34Immediate(N, Imm34)) {
18003       // The address is a 34-bit signed immediate.
18004       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18005       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
18006     }
18007     break;
18008   }
18009   case PPC::AM_PCRel: {
18010     // When selecting PC-Relative instructions, "Base" is not utilized as
18011     // we select the address as [PC+imm].
18012     Disp = N;
18013     break;
18014   }
18015   case PPC::AM_None:
18016     break;
18017   default: { // By default, X-Form is always available to be selected.
18018     // When a frame index is not aligned, we also match by XForm.
18019     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
18020     Base = FI ? N : N.getOperand(1);
18021     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18022                                 N.getValueType())
18023               : N.getOperand(0);
18024     break;
18025   }
18026   }
18027   return Mode;
18028 }
18029 
18030 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
18031                                                  bool Return,
18032                                                  bool IsVarArg) const {
18033   switch (CC) {
18034   case CallingConv::Cold:
18035     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
18036   default:
18037     return CC_PPC64_ELF_FIS;
18038   }
18039 }
18040 
18041 TargetLowering::AtomicExpansionKind
18042 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18043   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18044   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18045     return AtomicExpansionKind::MaskedIntrinsic;
18046   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
18047 }
18048 
18049 TargetLowering::AtomicExpansionKind
18050 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18051   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
18052   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18053     return AtomicExpansionKind::MaskedIntrinsic;
18054   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
18055 }
18056 
18057 static Intrinsic::ID
18058 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
18059   switch (BinOp) {
18060   default:
18061     llvm_unreachable("Unexpected AtomicRMW BinOp");
18062   case AtomicRMWInst::Xchg:
18063     return Intrinsic::ppc_atomicrmw_xchg_i128;
18064   case AtomicRMWInst::Add:
18065     return Intrinsic::ppc_atomicrmw_add_i128;
18066   case AtomicRMWInst::Sub:
18067     return Intrinsic::ppc_atomicrmw_sub_i128;
18068   case AtomicRMWInst::And:
18069     return Intrinsic::ppc_atomicrmw_and_i128;
18070   case AtomicRMWInst::Or:
18071     return Intrinsic::ppc_atomicrmw_or_i128;
18072   case AtomicRMWInst::Xor:
18073     return Intrinsic::ppc_atomicrmw_xor_i128;
18074   case AtomicRMWInst::Nand:
18075     return Intrinsic::ppc_atomicrmw_nand_i128;
18076   }
18077 }
18078 
18079 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
18080     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
18081     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
18082   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18083          "Only support quadword now");
18084   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18085   Type *ValTy = Incr->getType();
18086   assert(ValTy->getPrimitiveSizeInBits() == 128);
18087   Function *RMW = Intrinsic::getDeclaration(
18088       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
18089   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18090   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
18091   Value *IncrHi =
18092       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
18093   Value *Addr =
18094       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18095   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
18096   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18097   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18098   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18099   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18100   return Builder.CreateOr(
18101       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18102 }
18103 
18104 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
18105     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
18106     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
18107   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18108          "Only support quadword now");
18109   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18110   Type *ValTy = CmpVal->getType();
18111   assert(ValTy->getPrimitiveSizeInBits() == 128);
18112   Function *IntCmpXchg =
18113       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
18114   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18115   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
18116   Value *CmpHi =
18117       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
18118   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
18119   Value *NewHi =
18120       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
18121   Value *Addr =
18122       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18123   emitLeadingFence(Builder, CI, Ord);
18124   Value *LoHi =
18125       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
18126   emitTrailingFence(Builder, CI, Ord);
18127   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18128   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18129   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18130   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18131   return Builder.CreateOr(
18132       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18133 }
18134