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, Custom);
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, Custom);
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 (shouldInlineQuadwordAtomics()) {
1325     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1326     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1327     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1328   }
1329 
1330   setBooleanContents(ZeroOrOneBooleanContent);
1331 
1332   if (Subtarget.hasAltivec()) {
1333     // Altivec instructions set fields to all zeros or all ones.
1334     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1335   }
1336 
1337   setLibcallName(RTLIB::MULO_I128, nullptr);
1338   if (!isPPC64) {
1339     // These libcalls are not available in 32-bit.
1340     setLibcallName(RTLIB::SHL_I128, nullptr);
1341     setLibcallName(RTLIB::SRL_I128, nullptr);
1342     setLibcallName(RTLIB::SRA_I128, nullptr);
1343     setLibcallName(RTLIB::MUL_I128, nullptr);
1344     setLibcallName(RTLIB::MULO_I64, nullptr);
1345   }
1346 
1347   if (!isPPC64)
1348     setMaxAtomicSizeInBitsSupported(32);
1349   else if (shouldInlineQuadwordAtomics())
1350     setMaxAtomicSizeInBitsSupported(128);
1351   else
1352     setMaxAtomicSizeInBitsSupported(64);
1353 
1354   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1355 
1356   // We have target-specific dag combine patterns for the following nodes:
1357   setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL,
1358                        ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR});
1359   if (Subtarget.hasFPCVT())
1360     setTargetDAGCombine(ISD::UINT_TO_FP);
1361   setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC});
1362   if (Subtarget.useCRBits())
1363     setTargetDAGCombine(ISD::BRCOND);
1364   setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN,
1365                        ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID});
1366 
1367   setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND});
1368 
1369   setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE});
1370 
1371   if (Subtarget.useCRBits()) {
1372     setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC});
1373   }
1374 
1375   if (Subtarget.hasP9Altivec()) {
1376     setTargetDAGCombine({ISD::ABS, ISD::VSELECT});
1377   }
1378 
1379   setLibcallName(RTLIB::LOG_F128, "logf128");
1380   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1381   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1382   setLibcallName(RTLIB::EXP_F128, "expf128");
1383   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1384   setLibcallName(RTLIB::SIN_F128, "sinf128");
1385   setLibcallName(RTLIB::COS_F128, "cosf128");
1386   setLibcallName(RTLIB::POW_F128, "powf128");
1387   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1388   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1389   setLibcallName(RTLIB::REM_F128, "fmodf128");
1390   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1391   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1392   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1393   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1394   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1395   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1396   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1397   setLibcallName(RTLIB::RINT_F128, "rintf128");
1398   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1399   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1400   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1401   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1402 
1403   // With 32 condition bits, we don't need to sink (and duplicate) compares
1404   // aggressively in CodeGenPrep.
1405   if (Subtarget.useCRBits()) {
1406     setHasMultipleConditionRegisters();
1407     setJumpIsExpensive();
1408   }
1409 
1410   setMinFunctionAlignment(Align(4));
1411 
1412   switch (Subtarget.getCPUDirective()) {
1413   default: break;
1414   case PPC::DIR_970:
1415   case PPC::DIR_A2:
1416   case PPC::DIR_E500:
1417   case PPC::DIR_E500mc:
1418   case PPC::DIR_E5500:
1419   case PPC::DIR_PWR4:
1420   case PPC::DIR_PWR5:
1421   case PPC::DIR_PWR5X:
1422   case PPC::DIR_PWR6:
1423   case PPC::DIR_PWR6X:
1424   case PPC::DIR_PWR7:
1425   case PPC::DIR_PWR8:
1426   case PPC::DIR_PWR9:
1427   case PPC::DIR_PWR10:
1428   case PPC::DIR_PWR_FUTURE:
1429     setPrefLoopAlignment(Align(16));
1430     setPrefFunctionAlignment(Align(16));
1431     break;
1432   }
1433 
1434   if (Subtarget.enableMachineScheduler())
1435     setSchedulingPreference(Sched::Source);
1436   else
1437     setSchedulingPreference(Sched::Hybrid);
1438 
1439   computeRegisterProperties(STI.getRegisterInfo());
1440 
1441   // The Freescale cores do better with aggressive inlining of memcpy and
1442   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1443   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1444       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1445     MaxStoresPerMemset = 32;
1446     MaxStoresPerMemsetOptSize = 16;
1447     MaxStoresPerMemcpy = 32;
1448     MaxStoresPerMemcpyOptSize = 8;
1449     MaxStoresPerMemmove = 32;
1450     MaxStoresPerMemmoveOptSize = 8;
1451   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1452     // The A2 also benefits from (very) aggressive inlining of memcpy and
1453     // friends. The overhead of a the function call, even when warm, can be
1454     // over one hundred cycles.
1455     MaxStoresPerMemset = 128;
1456     MaxStoresPerMemcpy = 128;
1457     MaxStoresPerMemmove = 128;
1458     MaxLoadsPerMemcmp = 128;
1459   } else {
1460     MaxLoadsPerMemcmp = 8;
1461     MaxLoadsPerMemcmpOptSize = 4;
1462   }
1463 
1464   IsStrictFPEnabled = true;
1465 
1466   // Let the subtarget (CPU) decide if a predictable select is more expensive
1467   // than the corresponding branch. This information is used in CGP to decide
1468   // when to convert selects into branches.
1469   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1470 }
1471 
1472 // *********************************** NOTE ************************************
1473 // For selecting load and store instructions, the addressing modes are defined
1474 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1475 // patterns to match the load the store instructions.
1476 //
1477 // The TD definitions for the addressing modes correspond to their respective
1478 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1479 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1480 // address mode flags of a particular node. Afterwards, the computed address
1481 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1482 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1483 // accordingly, based on the preferred addressing mode.
1484 //
1485 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1486 // MemOpFlags contains all the possible flags that can be used to compute the
1487 // optimal addressing mode for load and store instructions.
1488 // AddrMode contains all the possible load and store addressing modes available
1489 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1490 //
1491 // When adding new load and store instructions, it is possible that new address
1492 // flags may need to be added into MemOpFlags, and a new addressing mode will
1493 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1494 // of the minimal and main distinguishing address flags for the new load/store
1495 // instructions) will need to be added into initializeAddrModeMap() below.
1496 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1497 // need to be updated to account for selecting the optimal addressing mode.
1498 // *****************************************************************************
1499 /// Initialize the map that relates the different addressing modes of the load
1500 /// and store instructions to a set of flags. This ensures the load/store
1501 /// instruction is correctly matched during instruction selection.
1502 void PPCTargetLowering::initializeAddrModeMap() {
1503   AddrModesMap[PPC::AM_DForm] = {
1504       // LWZ, STW
1505       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1506       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1507       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1508       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1509       // LBZ, LHZ, STB, STH
1510       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1511       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1512       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1513       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1514       // LHA
1515       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1516       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1517       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1518       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1519       // LFS, LFD, STFS, STFD
1520       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1521       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1522       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1523       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1524   };
1525   AddrModesMap[PPC::AM_DSForm] = {
1526       // LWA
1527       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1528       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1529       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1530       // LD, STD
1531       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1532       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1533       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1534       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1535       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1536       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1537       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1538   };
1539   AddrModesMap[PPC::AM_DQForm] = {
1540       // LXV, STXV
1541       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1542       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1543       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1544   };
1545   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1546                                        PPC::MOF_SubtargetP10};
1547   // TODO: Add mapping for quadword load/store.
1548 }
1549 
1550 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1551 /// the desired ByVal argument alignment.
1552 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1553   if (MaxAlign == MaxMaxAlign)
1554     return;
1555   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1556     if (MaxMaxAlign >= 32 &&
1557         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1558       MaxAlign = Align(32);
1559     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1560              MaxAlign < 16)
1561       MaxAlign = Align(16);
1562   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1563     Align EltAlign;
1564     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1565     if (EltAlign > MaxAlign)
1566       MaxAlign = EltAlign;
1567   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1568     for (auto *EltTy : STy->elements()) {
1569       Align EltAlign;
1570       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1571       if (EltAlign > MaxAlign)
1572         MaxAlign = EltAlign;
1573       if (MaxAlign == MaxMaxAlign)
1574         break;
1575     }
1576   }
1577 }
1578 
1579 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1580 /// function arguments in the caller parameter area.
1581 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1582                                                   const DataLayout &DL) const {
1583   // 16byte and wider vectors are passed on 16byte boundary.
1584   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1585   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1586   if (Subtarget.hasAltivec())
1587     getMaxByValAlign(Ty, Alignment, Align(16));
1588   return Alignment.value();
1589 }
1590 
1591 bool PPCTargetLowering::useSoftFloat() const {
1592   return Subtarget.useSoftFloat();
1593 }
1594 
1595 bool PPCTargetLowering::hasSPE() const {
1596   return Subtarget.hasSPE();
1597 }
1598 
1599 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1600   return VT.isScalarInteger();
1601 }
1602 
1603 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1604   switch ((PPCISD::NodeType)Opcode) {
1605   case PPCISD::FIRST_NUMBER:    break;
1606   case PPCISD::FSEL:            return "PPCISD::FSEL";
1607   case PPCISD::XSMAXC:          return "PPCISD::XSMAXC";
1608   case PPCISD::XSMINC:          return "PPCISD::XSMINC";
1609   case PPCISD::FCFID:           return "PPCISD::FCFID";
1610   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1611   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1612   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1613   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1614   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1615   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1616   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1617   case PPCISD::FP_TO_UINT_IN_VSR:
1618                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1619   case PPCISD::FP_TO_SINT_IN_VSR:
1620                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1621   case PPCISD::FRE:             return "PPCISD::FRE";
1622   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1623   case PPCISD::FTSQRT:
1624     return "PPCISD::FTSQRT";
1625   case PPCISD::FSQRT:
1626     return "PPCISD::FSQRT";
1627   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1628   case PPCISD::VPERM:           return "PPCISD::VPERM";
1629   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1630   case PPCISD::XXSPLTI_SP_TO_DP:
1631     return "PPCISD::XXSPLTI_SP_TO_DP";
1632   case PPCISD::XXSPLTI32DX:
1633     return "PPCISD::XXSPLTI32DX";
1634   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1635   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1636   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1637   case PPCISD::CMPB:            return "PPCISD::CMPB";
1638   case PPCISD::Hi:              return "PPCISD::Hi";
1639   case PPCISD::Lo:              return "PPCISD::Lo";
1640   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1641   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1642   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1643   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1644   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1645   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1646   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1647   case PPCISD::SRL:             return "PPCISD::SRL";
1648   case PPCISD::SRA:             return "PPCISD::SRA";
1649   case PPCISD::SHL:             return "PPCISD::SHL";
1650   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1651   case PPCISD::CALL:            return "PPCISD::CALL";
1652   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1653   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1654   case PPCISD::CALL_RM:
1655     return "PPCISD::CALL_RM";
1656   case PPCISD::CALL_NOP_RM:
1657     return "PPCISD::CALL_NOP_RM";
1658   case PPCISD::CALL_NOTOC_RM:
1659     return "PPCISD::CALL_NOTOC_RM";
1660   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1661   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1662   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1663   case PPCISD::BCTRL_RM:
1664     return "PPCISD::BCTRL_RM";
1665   case PPCISD::BCTRL_LOAD_TOC_RM:
1666     return "PPCISD::BCTRL_LOAD_TOC_RM";
1667   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1668   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1669   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1670   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1671   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1672   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1673   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1674   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1675   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1676   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1677   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1678     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1679   case PPCISD::ANDI_rec_1_EQ_BIT:
1680     return "PPCISD::ANDI_rec_1_EQ_BIT";
1681   case PPCISD::ANDI_rec_1_GT_BIT:
1682     return "PPCISD::ANDI_rec_1_GT_BIT";
1683   case PPCISD::VCMP:            return "PPCISD::VCMP";
1684   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1685   case PPCISD::LBRX:            return "PPCISD::LBRX";
1686   case PPCISD::STBRX:           return "PPCISD::STBRX";
1687   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1688   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1689   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1690   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1691   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1692   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1693   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1694   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1695   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1696   case PPCISD::ST_VSR_SCAL_INT:
1697                                 return "PPCISD::ST_VSR_SCAL_INT";
1698   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1699   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1700   case PPCISD::BDZ:             return "PPCISD::BDZ";
1701   case PPCISD::MFFS:            return "PPCISD::MFFS";
1702   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1703   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1704   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1705   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1706   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1707   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1708   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1709   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1710   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1711   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1712   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1713   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1714   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1715   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1716   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1717   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1718   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1719   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1720   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1721   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1722   case PPCISD::PADDI_DTPREL:
1723     return "PPCISD::PADDI_DTPREL";
1724   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1725   case PPCISD::SC:              return "PPCISD::SC";
1726   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1727   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1728   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1729   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1730   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1731   case PPCISD::VABSD:           return "PPCISD::VABSD";
1732   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1733   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1734   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1735   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1736   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1737   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1738   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1739   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1740     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1741   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1742     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1743   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1744   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1745   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1746   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1747   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1748   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1749   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1750   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1751   case PPCISD::STRICT_FADDRTZ:
1752     return "PPCISD::STRICT_FADDRTZ";
1753   case PPCISD::STRICT_FCTIDZ:
1754     return "PPCISD::STRICT_FCTIDZ";
1755   case PPCISD::STRICT_FCTIWZ:
1756     return "PPCISD::STRICT_FCTIWZ";
1757   case PPCISD::STRICT_FCTIDUZ:
1758     return "PPCISD::STRICT_FCTIDUZ";
1759   case PPCISD::STRICT_FCTIWUZ:
1760     return "PPCISD::STRICT_FCTIWUZ";
1761   case PPCISD::STRICT_FCFID:
1762     return "PPCISD::STRICT_FCFID";
1763   case PPCISD::STRICT_FCFIDU:
1764     return "PPCISD::STRICT_FCFIDU";
1765   case PPCISD::STRICT_FCFIDS:
1766     return "PPCISD::STRICT_FCFIDS";
1767   case PPCISD::STRICT_FCFIDUS:
1768     return "PPCISD::STRICT_FCFIDUS";
1769   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1770   }
1771   return nullptr;
1772 }
1773 
1774 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1775                                           EVT VT) const {
1776   if (!VT.isVector())
1777     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1778 
1779   return VT.changeVectorElementTypeToInteger();
1780 }
1781 
1782 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1783   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1784   return true;
1785 }
1786 
1787 //===----------------------------------------------------------------------===//
1788 // Node matching predicates, for use by the tblgen matching code.
1789 //===----------------------------------------------------------------------===//
1790 
1791 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1792 static bool isFloatingPointZero(SDValue Op) {
1793   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1794     return CFP->getValueAPF().isZero();
1795   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1796     // Maybe this has already been legalized into the constant pool?
1797     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1798       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1799         return CFP->getValueAPF().isZero();
1800   }
1801   return false;
1802 }
1803 
1804 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1805 /// true if Op is undef or if it matches the specified value.
1806 static bool isConstantOrUndef(int Op, int Val) {
1807   return Op < 0 || Op == Val;
1808 }
1809 
1810 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1811 /// VPKUHUM instruction.
1812 /// The ShuffleKind distinguishes between big-endian operations with
1813 /// two different inputs (0), either-endian operations with two identical
1814 /// inputs (1), and little-endian operations with two different inputs (2).
1815 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1816 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1817                                SelectionDAG &DAG) {
1818   bool IsLE = DAG.getDataLayout().isLittleEndian();
1819   if (ShuffleKind == 0) {
1820     if (IsLE)
1821       return false;
1822     for (unsigned i = 0; i != 16; ++i)
1823       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1824         return false;
1825   } else if (ShuffleKind == 2) {
1826     if (!IsLE)
1827       return false;
1828     for (unsigned i = 0; i != 16; ++i)
1829       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1830         return false;
1831   } else if (ShuffleKind == 1) {
1832     unsigned j = IsLE ? 0 : 1;
1833     for (unsigned i = 0; i != 8; ++i)
1834       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1835           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1836         return false;
1837   }
1838   return true;
1839 }
1840 
1841 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1842 /// VPKUWUM instruction.
1843 /// The ShuffleKind distinguishes between big-endian operations with
1844 /// two different inputs (0), either-endian operations with two identical
1845 /// inputs (1), and little-endian operations with two different inputs (2).
1846 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1847 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1848                                SelectionDAG &DAG) {
1849   bool IsLE = DAG.getDataLayout().isLittleEndian();
1850   if (ShuffleKind == 0) {
1851     if (IsLE)
1852       return false;
1853     for (unsigned i = 0; i != 16; i += 2)
1854       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1855           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1856         return false;
1857   } else if (ShuffleKind == 2) {
1858     if (!IsLE)
1859       return false;
1860     for (unsigned i = 0; i != 16; i += 2)
1861       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1862           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1863         return false;
1864   } else if (ShuffleKind == 1) {
1865     unsigned j = IsLE ? 0 : 2;
1866     for (unsigned i = 0; i != 8; i += 2)
1867       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1868           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1869           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1870           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1871         return false;
1872   }
1873   return true;
1874 }
1875 
1876 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1877 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1878 /// current subtarget.
1879 ///
1880 /// The ShuffleKind distinguishes between big-endian operations with
1881 /// two different inputs (0), either-endian operations with two identical
1882 /// inputs (1), and little-endian operations with two different inputs (2).
1883 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1884 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1885                                SelectionDAG &DAG) {
1886   const PPCSubtarget& Subtarget =
1887       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1888   if (!Subtarget.hasP8Vector())
1889     return false;
1890 
1891   bool IsLE = DAG.getDataLayout().isLittleEndian();
1892   if (ShuffleKind == 0) {
1893     if (IsLE)
1894       return false;
1895     for (unsigned i = 0; i != 16; i += 4)
1896       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1897           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1898           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1899           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1900         return false;
1901   } else if (ShuffleKind == 2) {
1902     if (!IsLE)
1903       return false;
1904     for (unsigned i = 0; i != 16; i += 4)
1905       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1906           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1907           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1908           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1909         return false;
1910   } else if (ShuffleKind == 1) {
1911     unsigned j = IsLE ? 0 : 4;
1912     for (unsigned i = 0; i != 8; i += 4)
1913       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1914           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1915           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1916           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1917           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1918           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1919           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1920           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1921         return false;
1922   }
1923   return true;
1924 }
1925 
1926 /// isVMerge - Common function, used to match vmrg* shuffles.
1927 ///
1928 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1929                      unsigned LHSStart, unsigned RHSStart) {
1930   if (N->getValueType(0) != MVT::v16i8)
1931     return false;
1932   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1933          "Unsupported merge size!");
1934 
1935   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1936     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1937       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1938                              LHSStart+j+i*UnitSize) ||
1939           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1940                              RHSStart+j+i*UnitSize))
1941         return false;
1942     }
1943   return true;
1944 }
1945 
1946 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1947 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1948 /// The ShuffleKind distinguishes between big-endian merges with two
1949 /// different inputs (0), either-endian merges with two identical inputs (1),
1950 /// and little-endian merges with two different inputs (2).  For the latter,
1951 /// the input operands are swapped (see PPCInstrAltivec.td).
1952 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1953                              unsigned ShuffleKind, SelectionDAG &DAG) {
1954   if (DAG.getDataLayout().isLittleEndian()) {
1955     if (ShuffleKind == 1) // unary
1956       return isVMerge(N, UnitSize, 0, 0);
1957     else if (ShuffleKind == 2) // swapped
1958       return isVMerge(N, UnitSize, 0, 16);
1959     else
1960       return false;
1961   } else {
1962     if (ShuffleKind == 1) // unary
1963       return isVMerge(N, UnitSize, 8, 8);
1964     else if (ShuffleKind == 0) // normal
1965       return isVMerge(N, UnitSize, 8, 24);
1966     else
1967       return false;
1968   }
1969 }
1970 
1971 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1972 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1973 /// The ShuffleKind distinguishes between big-endian merges with two
1974 /// different inputs (0), either-endian merges with two identical inputs (1),
1975 /// and little-endian merges with two different inputs (2).  For the latter,
1976 /// the input operands are swapped (see PPCInstrAltivec.td).
1977 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1978                              unsigned ShuffleKind, SelectionDAG &DAG) {
1979   if (DAG.getDataLayout().isLittleEndian()) {
1980     if (ShuffleKind == 1) // unary
1981       return isVMerge(N, UnitSize, 8, 8);
1982     else if (ShuffleKind == 2) // swapped
1983       return isVMerge(N, UnitSize, 8, 24);
1984     else
1985       return false;
1986   } else {
1987     if (ShuffleKind == 1) // unary
1988       return isVMerge(N, UnitSize, 0, 0);
1989     else if (ShuffleKind == 0) // normal
1990       return isVMerge(N, UnitSize, 0, 16);
1991     else
1992       return false;
1993   }
1994 }
1995 
1996 /**
1997  * Common function used to match vmrgew and vmrgow shuffles
1998  *
1999  * The indexOffset determines whether to look for even or odd words in
2000  * the shuffle mask. This is based on the of the endianness of the target
2001  * machine.
2002  *   - Little Endian:
2003  *     - Use offset of 0 to check for odd elements
2004  *     - Use offset of 4 to check for even elements
2005  *   - Big Endian:
2006  *     - Use offset of 0 to check for even elements
2007  *     - Use offset of 4 to check for odd elements
2008  * A detailed description of the vector element ordering for little endian and
2009  * big endian can be found at
2010  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2011  * Targeting your applications - what little endian and big endian IBM XL C/C++
2012  * compiler differences mean to you
2013  *
2014  * The mask to the shuffle vector instruction specifies the indices of the
2015  * elements from the two input vectors to place in the result. The elements are
2016  * numbered in array-access order, starting with the first vector. These vectors
2017  * are always of type v16i8, thus each vector will contain 16 elements of size
2018  * 8. More info on the shuffle vector can be found in the
2019  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2020  * Language Reference.
2021  *
2022  * The RHSStartValue indicates whether the same input vectors are used (unary)
2023  * or two different input vectors are used, based on the following:
2024  *   - If the instruction uses the same vector for both inputs, the range of the
2025  *     indices will be 0 to 15. In this case, the RHSStart value passed should
2026  *     be 0.
2027  *   - If the instruction has two different vectors then the range of the
2028  *     indices will be 0 to 31. In this case, the RHSStart value passed should
2029  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
2030  *     to 31 specify elements in the second vector).
2031  *
2032  * \param[in] N The shuffle vector SD Node to analyze
2033  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2034  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2035  * vector to the shuffle_vector instruction
2036  * \return true iff this shuffle vector represents an even or odd word merge
2037  */
2038 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2039                      unsigned RHSStartValue) {
2040   if (N->getValueType(0) != MVT::v16i8)
2041     return false;
2042 
2043   for (unsigned i = 0; i < 2; ++i)
2044     for (unsigned j = 0; j < 4; ++j)
2045       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2046                              i*RHSStartValue+j+IndexOffset) ||
2047           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2048                              i*RHSStartValue+j+IndexOffset+8))
2049         return false;
2050   return true;
2051 }
2052 
2053 /**
2054  * Determine if the specified shuffle mask is suitable for the vmrgew or
2055  * vmrgow instructions.
2056  *
2057  * \param[in] N The shuffle vector SD Node to analyze
2058  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2059  * \param[in] ShuffleKind Identify the type of merge:
2060  *   - 0 = big-endian merge with two different inputs;
2061  *   - 1 = either-endian merge with two identical inputs;
2062  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2063  *     little-endian merges).
2064  * \param[in] DAG The current SelectionDAG
2065  * \return true iff this shuffle mask
2066  */
2067 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2068                               unsigned ShuffleKind, SelectionDAG &DAG) {
2069   if (DAG.getDataLayout().isLittleEndian()) {
2070     unsigned indexOffset = CheckEven ? 4 : 0;
2071     if (ShuffleKind == 1) // Unary
2072       return isVMerge(N, indexOffset, 0);
2073     else if (ShuffleKind == 2) // swapped
2074       return isVMerge(N, indexOffset, 16);
2075     else
2076       return false;
2077   }
2078   else {
2079     unsigned indexOffset = CheckEven ? 0 : 4;
2080     if (ShuffleKind == 1) // Unary
2081       return isVMerge(N, indexOffset, 0);
2082     else if (ShuffleKind == 0) // Normal
2083       return isVMerge(N, indexOffset, 16);
2084     else
2085       return false;
2086   }
2087   return false;
2088 }
2089 
2090 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2091 /// amount, otherwise return -1.
2092 /// The ShuffleKind distinguishes between big-endian operations with two
2093 /// different inputs (0), either-endian operations with two identical inputs
2094 /// (1), and little-endian operations with two different inputs (2).  For the
2095 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2096 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2097                              SelectionDAG &DAG) {
2098   if (N->getValueType(0) != MVT::v16i8)
2099     return -1;
2100 
2101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2102 
2103   // Find the first non-undef value in the shuffle mask.
2104   unsigned i;
2105   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2106     /*search*/;
2107 
2108   if (i == 16) return -1;  // all undef.
2109 
2110   // Otherwise, check to see if the rest of the elements are consecutively
2111   // numbered from this value.
2112   unsigned ShiftAmt = SVOp->getMaskElt(i);
2113   if (ShiftAmt < i) return -1;
2114 
2115   ShiftAmt -= i;
2116   bool isLE = DAG.getDataLayout().isLittleEndian();
2117 
2118   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2119     // Check the rest of the elements to see if they are consecutive.
2120     for (++i; i != 16; ++i)
2121       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2122         return -1;
2123   } else if (ShuffleKind == 1) {
2124     // Check the rest of the elements to see if they are consecutive.
2125     for (++i; i != 16; ++i)
2126       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2127         return -1;
2128   } else
2129     return -1;
2130 
2131   if (isLE)
2132     ShiftAmt = 16 - ShiftAmt;
2133 
2134   return ShiftAmt;
2135 }
2136 
2137 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2138 /// specifies a splat of a single element that is suitable for input to
2139 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2140 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2141   EVT VT = N->getValueType(0);
2142   if (VT == MVT::v2i64 || VT == MVT::v2f64)
2143     return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
2144 
2145   assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2146          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2147 
2148   // The consecutive indices need to specify an element, not part of two
2149   // different elements.  So abandon ship early if this isn't the case.
2150   if (N->getMaskElt(0) % EltSize != 0)
2151     return false;
2152 
2153   // This is a splat operation if each element of the permute is the same, and
2154   // if the value doesn't reference the second vector.
2155   unsigned ElementBase = N->getMaskElt(0);
2156 
2157   // FIXME: Handle UNDEF elements too!
2158   if (ElementBase >= 16)
2159     return false;
2160 
2161   // Check that the indices are consecutive, in the case of a multi-byte element
2162   // splatted with a v16i8 mask.
2163   for (unsigned i = 1; i != EltSize; ++i)
2164     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2165       return false;
2166 
2167   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2168     if (N->getMaskElt(i) < 0) continue;
2169     for (unsigned j = 0; j != EltSize; ++j)
2170       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2171         return false;
2172   }
2173   return true;
2174 }
2175 
2176 /// Check that the mask is shuffling N byte elements. Within each N byte
2177 /// element of the mask, the indices could be either in increasing or
2178 /// decreasing order as long as they are consecutive.
2179 /// \param[in] N the shuffle vector SD Node to analyze
2180 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2181 /// Word/DoubleWord/QuadWord).
2182 /// \param[in] StepLen the delta indices number among the N byte element, if
2183 /// the mask is in increasing/decreasing order then it is 1/-1.
2184 /// \return true iff the mask is shuffling N byte elements.
2185 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2186                                    int StepLen) {
2187   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2188          "Unexpected element width.");
2189   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2190 
2191   unsigned NumOfElem = 16 / Width;
2192   unsigned MaskVal[16]; //  Width is never greater than 16
2193   for (unsigned i = 0; i < NumOfElem; ++i) {
2194     MaskVal[0] = N->getMaskElt(i * Width);
2195     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2196       return false;
2197     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2198       return false;
2199     }
2200 
2201     for (unsigned int j = 1; j < Width; ++j) {
2202       MaskVal[j] = N->getMaskElt(i * Width + j);
2203       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2204         return false;
2205       }
2206     }
2207   }
2208 
2209   return true;
2210 }
2211 
2212 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2213                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2214   if (!isNByteElemShuffleMask(N, 4, 1))
2215     return false;
2216 
2217   // Now we look at mask elements 0,4,8,12
2218   unsigned M0 = N->getMaskElt(0) / 4;
2219   unsigned M1 = N->getMaskElt(4) / 4;
2220   unsigned M2 = N->getMaskElt(8) / 4;
2221   unsigned M3 = N->getMaskElt(12) / 4;
2222   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2223   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2224 
2225   // Below, let H and L be arbitrary elements of the shuffle mask
2226   // where H is in the range [4,7] and L is in the range [0,3].
2227   // H, 1, 2, 3 or L, 5, 6, 7
2228   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2229       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2230     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2231     InsertAtByte = IsLE ? 12 : 0;
2232     Swap = M0 < 4;
2233     return true;
2234   }
2235   // 0, H, 2, 3 or 4, L, 6, 7
2236   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2237       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2238     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2239     InsertAtByte = IsLE ? 8 : 4;
2240     Swap = M1 < 4;
2241     return true;
2242   }
2243   // 0, 1, H, 3 or 4, 5, L, 7
2244   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2245       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2246     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2247     InsertAtByte = IsLE ? 4 : 8;
2248     Swap = M2 < 4;
2249     return true;
2250   }
2251   // 0, 1, 2, H or 4, 5, 6, L
2252   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2253       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2254     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2255     InsertAtByte = IsLE ? 0 : 12;
2256     Swap = M3 < 4;
2257     return true;
2258   }
2259 
2260   // If both vector operands for the shuffle are the same vector, the mask will
2261   // contain only elements from the first one and the second one will be undef.
2262   if (N->getOperand(1).isUndef()) {
2263     ShiftElts = 0;
2264     Swap = true;
2265     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2266     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2267       InsertAtByte = IsLE ? 12 : 0;
2268       return true;
2269     }
2270     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2271       InsertAtByte = IsLE ? 8 : 4;
2272       return true;
2273     }
2274     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2275       InsertAtByte = IsLE ? 4 : 8;
2276       return true;
2277     }
2278     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2279       InsertAtByte = IsLE ? 0 : 12;
2280       return true;
2281     }
2282   }
2283 
2284   return false;
2285 }
2286 
2287 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2288                                bool &Swap, bool IsLE) {
2289   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2290   // Ensure each byte index of the word is consecutive.
2291   if (!isNByteElemShuffleMask(N, 4, 1))
2292     return false;
2293 
2294   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2295   unsigned M0 = N->getMaskElt(0) / 4;
2296   unsigned M1 = N->getMaskElt(4) / 4;
2297   unsigned M2 = N->getMaskElt(8) / 4;
2298   unsigned M3 = N->getMaskElt(12) / 4;
2299 
2300   // If both vector operands for the shuffle are the same vector, the mask will
2301   // contain only elements from the first one and the second one will be undef.
2302   if (N->getOperand(1).isUndef()) {
2303     assert(M0 < 4 && "Indexing into an undef vector?");
2304     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2305       return false;
2306 
2307     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2308     Swap = false;
2309     return true;
2310   }
2311 
2312   // Ensure each word index of the ShuffleVector Mask is consecutive.
2313   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2314     return false;
2315 
2316   if (IsLE) {
2317     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2318       // Input vectors don't need to be swapped if the leading element
2319       // of the result is one of the 3 left elements of the second vector
2320       // (or if there is no shift to be done at all).
2321       Swap = false;
2322       ShiftElts = (8 - M0) % 8;
2323     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2324       // Input vectors need to be swapped if the leading element
2325       // of the result is one of the 3 left elements of the first vector
2326       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2327       Swap = true;
2328       ShiftElts = (4 - M0) % 4;
2329     }
2330 
2331     return true;
2332   } else {                                          // BE
2333     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2334       // Input vectors don't need to be swapped if the leading element
2335       // of the result is one of the 4 elements of the first vector.
2336       Swap = false;
2337       ShiftElts = M0;
2338     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2339       // Input vectors need to be swapped if the leading element
2340       // of the result is one of the 4 elements of the right vector.
2341       Swap = true;
2342       ShiftElts = M0 - 4;
2343     }
2344 
2345     return true;
2346   }
2347 }
2348 
2349 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2350   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2351 
2352   if (!isNByteElemShuffleMask(N, Width, -1))
2353     return false;
2354 
2355   for (int i = 0; i < 16; i += Width)
2356     if (N->getMaskElt(i) != i + Width - 1)
2357       return false;
2358 
2359   return true;
2360 }
2361 
2362 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2363   return isXXBRShuffleMaskHelper(N, 2);
2364 }
2365 
2366 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2367   return isXXBRShuffleMaskHelper(N, 4);
2368 }
2369 
2370 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2371   return isXXBRShuffleMaskHelper(N, 8);
2372 }
2373 
2374 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2375   return isXXBRShuffleMaskHelper(N, 16);
2376 }
2377 
2378 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2379 /// if the inputs to the instruction should be swapped and set \p DM to the
2380 /// value for the immediate.
2381 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2382 /// AND element 0 of the result comes from the first input (LE) or second input
2383 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2384 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2385 /// mask.
2386 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2387                                bool &Swap, bool IsLE) {
2388   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2389 
2390   // Ensure each byte index of the double word is consecutive.
2391   if (!isNByteElemShuffleMask(N, 8, 1))
2392     return false;
2393 
2394   unsigned M0 = N->getMaskElt(0) / 8;
2395   unsigned M1 = N->getMaskElt(8) / 8;
2396   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2397 
2398   // If both vector operands for the shuffle are the same vector, the mask will
2399   // contain only elements from the first one and the second one will be undef.
2400   if (N->getOperand(1).isUndef()) {
2401     if ((M0 | M1) < 2) {
2402       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2403       Swap = false;
2404       return true;
2405     } else
2406       return false;
2407   }
2408 
2409   if (IsLE) {
2410     if (M0 > 1 && M1 < 2) {
2411       Swap = false;
2412     } else if (M0 < 2 && M1 > 1) {
2413       M0 = (M0 + 2) % 4;
2414       M1 = (M1 + 2) % 4;
2415       Swap = true;
2416     } else
2417       return false;
2418 
2419     // Note: if control flow comes here that means Swap is already set above
2420     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2421     return true;
2422   } else { // BE
2423     if (M0 < 2 && M1 > 1) {
2424       Swap = false;
2425     } else if (M0 > 1 && M1 < 2) {
2426       M0 = (M0 + 2) % 4;
2427       M1 = (M1 + 2) % 4;
2428       Swap = true;
2429     } else
2430       return false;
2431 
2432     // Note: if control flow comes here that means Swap is already set above
2433     DM = (M0 << 1) + (M1 & 1);
2434     return true;
2435   }
2436 }
2437 
2438 
2439 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2440 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2441 /// elements are counted from the left of the vector register).
2442 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2443                                          SelectionDAG &DAG) {
2444   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2445   assert(isSplatShuffleMask(SVOp, EltSize));
2446   EVT VT = SVOp->getValueType(0);
2447 
2448   if (VT == MVT::v2i64 || VT == MVT::v2f64)
2449     return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
2450                                                 : SVOp->getMaskElt(0);
2451 
2452   if (DAG.getDataLayout().isLittleEndian())
2453     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2454   else
2455     return SVOp->getMaskElt(0) / EltSize;
2456 }
2457 
2458 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2459 /// by using a vspltis[bhw] instruction of the specified element size, return
2460 /// the constant being splatted.  The ByteSize field indicates the number of
2461 /// bytes of each element [124] -> [bhw].
2462 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2463   SDValue OpVal;
2464 
2465   // If ByteSize of the splat is bigger than the element size of the
2466   // build_vector, then we have a case where we are checking for a splat where
2467   // multiple elements of the buildvector are folded together into a single
2468   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2469   unsigned EltSize = 16/N->getNumOperands();
2470   if (EltSize < ByteSize) {
2471     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2472     SDValue UniquedVals[4];
2473     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2474 
2475     // See if all of the elements in the buildvector agree across.
2476     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2477       if (N->getOperand(i).isUndef()) continue;
2478       // If the element isn't a constant, bail fully out.
2479       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2480 
2481       if (!UniquedVals[i&(Multiple-1)].getNode())
2482         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2483       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2484         return SDValue();  // no match.
2485     }
2486 
2487     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2488     // either constant or undef values that are identical for each chunk.  See
2489     // if these chunks can form into a larger vspltis*.
2490 
2491     // Check to see if all of the leading entries are either 0 or -1.  If
2492     // neither, then this won't fit into the immediate field.
2493     bool LeadingZero = true;
2494     bool LeadingOnes = true;
2495     for (unsigned i = 0; i != Multiple-1; ++i) {
2496       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2497 
2498       LeadingZero &= isNullConstant(UniquedVals[i]);
2499       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2500     }
2501     // Finally, check the least significant entry.
2502     if (LeadingZero) {
2503       if (!UniquedVals[Multiple-1].getNode())
2504         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2505       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2506       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2507         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2508     }
2509     if (LeadingOnes) {
2510       if (!UniquedVals[Multiple-1].getNode())
2511         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2512       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2513       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2514         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2515     }
2516 
2517     return SDValue();
2518   }
2519 
2520   // Check to see if this buildvec has a single non-undef value in its elements.
2521   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2522     if (N->getOperand(i).isUndef()) continue;
2523     if (!OpVal.getNode())
2524       OpVal = N->getOperand(i);
2525     else if (OpVal != N->getOperand(i))
2526       return SDValue();
2527   }
2528 
2529   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2530 
2531   unsigned ValSizeInBytes = EltSize;
2532   uint64_t Value = 0;
2533   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2534     Value = CN->getZExtValue();
2535   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2536     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2537     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2538   }
2539 
2540   // If the splat value is larger than the element value, then we can never do
2541   // this splat.  The only case that we could fit the replicated bits into our
2542   // immediate field for would be zero, and we prefer to use vxor for it.
2543   if (ValSizeInBytes < ByteSize) return SDValue();
2544 
2545   // If the element value is larger than the splat value, check if it consists
2546   // of a repeated bit pattern of size ByteSize.
2547   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2548     return SDValue();
2549 
2550   // Properly sign extend the value.
2551   int MaskVal = SignExtend32(Value, ByteSize * 8);
2552 
2553   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2554   if (MaskVal == 0) return SDValue();
2555 
2556   // Finally, if this value fits in a 5 bit sext field, return it
2557   if (SignExtend32<5>(MaskVal) == MaskVal)
2558     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2559   return SDValue();
2560 }
2561 
2562 //===----------------------------------------------------------------------===//
2563 //  Addressing Mode Selection
2564 //===----------------------------------------------------------------------===//
2565 
2566 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2567 /// or 64-bit immediate, and if the value can be accurately represented as a
2568 /// sign extension from a 16-bit value.  If so, this returns true and the
2569 /// immediate.
2570 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2571   if (!isa<ConstantSDNode>(N))
2572     return false;
2573 
2574   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2575   if (N->getValueType(0) == MVT::i32)
2576     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2577   else
2578     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2579 }
2580 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2581   return isIntS16Immediate(Op.getNode(), Imm);
2582 }
2583 
2584 /// Used when computing address flags for selecting loads and stores.
2585 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2586 /// An OR of two provably disjoint values is equivalent to an ADD.
2587 /// Most PPC load/store instructions compute the effective address as a sum,
2588 /// so doing this conversion is useful.
2589 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2590   if (N.getOpcode() != ISD::OR)
2591     return false;
2592   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2593   if (!LHSKnown.Zero.getBoolValue())
2594     return false;
2595   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2596   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2597 }
2598 
2599 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2600 /// be represented as an indexed [r+r] operation.
2601 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2602                                                SDValue &Index,
2603                                                SelectionDAG &DAG) const {
2604   for (SDNode *U : N->uses()) {
2605     if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2606       if (Memop->getMemoryVT() == MVT::f64) {
2607           Base = N.getOperand(0);
2608           Index = N.getOperand(1);
2609           return true;
2610       }
2611     }
2612   }
2613   return false;
2614 }
2615 
2616 /// isIntS34Immediate - This method tests if value of node given can be
2617 /// accurately represented as a sign extension from a 34-bit value.  If so,
2618 /// this returns true and the immediate.
2619 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2620   if (!isa<ConstantSDNode>(N))
2621     return false;
2622 
2623   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2624   return isInt<34>(Imm);
2625 }
2626 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2627   return isIntS34Immediate(Op.getNode(), Imm);
2628 }
2629 
2630 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2631 /// can be represented as an indexed [r+r] operation.  Returns false if it
2632 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2633 /// non-zero and N can be represented by a base register plus a signed 16-bit
2634 /// displacement, make a more precise judgement by checking (displacement % \p
2635 /// EncodingAlignment).
2636 bool PPCTargetLowering::SelectAddressRegReg(
2637     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2638     MaybeAlign EncodingAlignment) const {
2639   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2640   // a [pc+imm].
2641   if (SelectAddressPCRel(N, Base))
2642     return false;
2643 
2644   int16_t Imm = 0;
2645   if (N.getOpcode() == ISD::ADD) {
2646     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2647     // SPE load/store can only handle 8-bit offsets.
2648     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2649         return true;
2650     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2651         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2652       return false; // r+i
2653     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2654       return false;    // r+i
2655 
2656     Base = N.getOperand(0);
2657     Index = N.getOperand(1);
2658     return true;
2659   } else if (N.getOpcode() == ISD::OR) {
2660     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2661         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2662       return false; // r+i can fold it if we can.
2663 
2664     // If this is an or of disjoint bitfields, we can codegen this as an add
2665     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2666     // disjoint.
2667     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2668 
2669     if (LHSKnown.Zero.getBoolValue()) {
2670       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2671       // If all of the bits are known zero on the LHS or RHS, the add won't
2672       // carry.
2673       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2674         Base = N.getOperand(0);
2675         Index = N.getOperand(1);
2676         return true;
2677       }
2678     }
2679   }
2680 
2681   return false;
2682 }
2683 
2684 // If we happen to be doing an i64 load or store into a stack slot that has
2685 // less than a 4-byte alignment, then the frame-index elimination may need to
2686 // use an indexed load or store instruction (because the offset may not be a
2687 // multiple of 4). The extra register needed to hold the offset comes from the
2688 // register scavenger, and it is possible that the scavenger will need to use
2689 // an emergency spill slot. As a result, we need to make sure that a spill slot
2690 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2691 // stack slot.
2692 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2693   // FIXME: This does not handle the LWA case.
2694   if (VT != MVT::i64)
2695     return;
2696 
2697   // NOTE: We'll exclude negative FIs here, which come from argument
2698   // lowering, because there are no known test cases triggering this problem
2699   // using packed structures (or similar). We can remove this exclusion if
2700   // we find such a test case. The reason why this is so test-case driven is
2701   // because this entire 'fixup' is only to prevent crashes (from the
2702   // register scavenger) on not-really-valid inputs. For example, if we have:
2703   //   %a = alloca i1
2704   //   %b = bitcast i1* %a to i64*
2705   //   store i64* a, i64 b
2706   // then the store should really be marked as 'align 1', but is not. If it
2707   // were marked as 'align 1' then the indexed form would have been
2708   // instruction-selected initially, and the problem this 'fixup' is preventing
2709   // won't happen regardless.
2710   if (FrameIdx < 0)
2711     return;
2712 
2713   MachineFunction &MF = DAG.getMachineFunction();
2714   MachineFrameInfo &MFI = MF.getFrameInfo();
2715 
2716   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2717     return;
2718 
2719   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2720   FuncInfo->setHasNonRISpills();
2721 }
2722 
2723 /// Returns true if the address N can be represented by a base register plus
2724 /// a signed 16-bit displacement [r+imm], and if it is not better
2725 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2726 /// displacements that are multiples of that value.
2727 bool PPCTargetLowering::SelectAddressRegImm(
2728     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2729     MaybeAlign EncodingAlignment) const {
2730   // FIXME dl should come from parent load or store, not from address
2731   SDLoc dl(N);
2732 
2733   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2734   // a [pc+imm].
2735   if (SelectAddressPCRel(N, Base))
2736     return false;
2737 
2738   // If this can be more profitably realized as r+r, fail.
2739   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2740     return false;
2741 
2742   if (N.getOpcode() == ISD::ADD) {
2743     int16_t imm = 0;
2744     if (isIntS16Immediate(N.getOperand(1), imm) &&
2745         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2746       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2747       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2748         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2749         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2750       } else {
2751         Base = N.getOperand(0);
2752       }
2753       return true; // [r+i]
2754     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2755       // Match LOAD (ADD (X, Lo(G))).
2756       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2757              && "Cannot handle constant offsets yet!");
2758       Disp = N.getOperand(1).getOperand(0);  // The global address.
2759       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2760              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2761              Disp.getOpcode() == ISD::TargetConstantPool ||
2762              Disp.getOpcode() == ISD::TargetJumpTable);
2763       Base = N.getOperand(0);
2764       return true;  // [&g+r]
2765     }
2766   } else if (N.getOpcode() == ISD::OR) {
2767     int16_t imm = 0;
2768     if (isIntS16Immediate(N.getOperand(1), imm) &&
2769         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2770       // If this is an or of disjoint bitfields, we can codegen this as an add
2771       // (for better address arithmetic) if the LHS and RHS of the OR are
2772       // provably disjoint.
2773       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2774 
2775       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2776         // If all of the bits are known zero on the LHS or RHS, the add won't
2777         // carry.
2778         if (FrameIndexSDNode *FI =
2779               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2780           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2781           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2782         } else {
2783           Base = N.getOperand(0);
2784         }
2785         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2786         return true;
2787       }
2788     }
2789   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2790     // Loading from a constant address.
2791 
2792     // If this address fits entirely in a 16-bit sext immediate field, codegen
2793     // this as "d, 0"
2794     int16_t Imm;
2795     if (isIntS16Immediate(CN, Imm) &&
2796         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2797       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2798       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2799                              CN->getValueType(0));
2800       return true;
2801     }
2802 
2803     // Handle 32-bit sext immediates with LIS + addr mode.
2804     if ((CN->getValueType(0) == MVT::i32 ||
2805          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2806         (!EncodingAlignment ||
2807          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2808       int Addr = (int)CN->getZExtValue();
2809 
2810       // Otherwise, break this down into an LIS + disp.
2811       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2812 
2813       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2814                                    MVT::i32);
2815       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2816       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2817       return true;
2818     }
2819   }
2820 
2821   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2822   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2823     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2824     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2825   } else
2826     Base = N;
2827   return true;      // [r+0]
2828 }
2829 
2830 /// Similar to the 16-bit case but for instructions that take a 34-bit
2831 /// displacement field (prefixed loads/stores).
2832 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2833                                               SDValue &Base,
2834                                               SelectionDAG &DAG) const {
2835   // Only on 64-bit targets.
2836   if (N.getValueType() != MVT::i64)
2837     return false;
2838 
2839   SDLoc dl(N);
2840   int64_t Imm = 0;
2841 
2842   if (N.getOpcode() == ISD::ADD) {
2843     if (!isIntS34Immediate(N.getOperand(1), Imm))
2844       return false;
2845     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2846     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2847       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2848     else
2849       Base = N.getOperand(0);
2850     return true;
2851   }
2852 
2853   if (N.getOpcode() == ISD::OR) {
2854     if (!isIntS34Immediate(N.getOperand(1), Imm))
2855       return false;
2856     // If this is an or of disjoint bitfields, we can codegen this as an add
2857     // (for better address arithmetic) if the LHS and RHS of the OR are
2858     // provably disjoint.
2859     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2860     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2861       return false;
2862     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2863       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2864     else
2865       Base = N.getOperand(0);
2866     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2867     return true;
2868   }
2869 
2870   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2871     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2872     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2873     return true;
2874   }
2875 
2876   return false;
2877 }
2878 
2879 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2880 /// represented as an indexed [r+r] operation.
2881 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2882                                                 SDValue &Index,
2883                                                 SelectionDAG &DAG) const {
2884   // Check to see if we can easily represent this as an [r+r] address.  This
2885   // will fail if it thinks that the address is more profitably represented as
2886   // reg+imm, e.g. where imm = 0.
2887   if (SelectAddressRegReg(N, Base, Index, DAG))
2888     return true;
2889 
2890   // If the address is the result of an add, we will utilize the fact that the
2891   // address calculation includes an implicit add.  However, we can reduce
2892   // register pressure if we do not materialize a constant just for use as the
2893   // index register.  We only get rid of the add if it is not an add of a
2894   // value and a 16-bit signed constant and both have a single use.
2895   int16_t imm = 0;
2896   if (N.getOpcode() == ISD::ADD &&
2897       (!isIntS16Immediate(N.getOperand(1), imm) ||
2898        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2899     Base = N.getOperand(0);
2900     Index = N.getOperand(1);
2901     return true;
2902   }
2903 
2904   // Otherwise, do it the hard way, using R0 as the base register.
2905   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2906                          N.getValueType());
2907   Index = N;
2908   return true;
2909 }
2910 
2911 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2912   Ty *PCRelCand = dyn_cast<Ty>(N);
2913   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2914 }
2915 
2916 /// Returns true if this address is a PC Relative address.
2917 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2918 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2919 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2920   // This is a materialize PC Relative node. Always select this as PC Relative.
2921   Base = N;
2922   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2923     return true;
2924   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2925       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2926       isValidPCRelNode<JumpTableSDNode>(N) ||
2927       isValidPCRelNode<BlockAddressSDNode>(N))
2928     return true;
2929   return false;
2930 }
2931 
2932 /// Returns true if we should use a direct load into vector instruction
2933 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2934 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2935 
2936   // If there are any other uses other than scalar to vector, then we should
2937   // keep it as a scalar load -> direct move pattern to prevent multiple
2938   // loads.
2939   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2940   if (!LD)
2941     return false;
2942 
2943   EVT MemVT = LD->getMemoryVT();
2944   if (!MemVT.isSimple())
2945     return false;
2946   switch(MemVT.getSimpleVT().SimpleTy) {
2947   case MVT::i64:
2948     break;
2949   case MVT::i32:
2950     if (!ST.hasP8Vector())
2951       return false;
2952     break;
2953   case MVT::i16:
2954   case MVT::i8:
2955     if (!ST.hasP9Vector())
2956       return false;
2957     break;
2958   default:
2959     return false;
2960   }
2961 
2962   SDValue LoadedVal(N, 0);
2963   if (!LoadedVal.hasOneUse())
2964     return false;
2965 
2966   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2967        UI != UE; ++UI)
2968     if (UI.getUse().get().getResNo() == 0 &&
2969         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2970         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2971       return false;
2972 
2973   return true;
2974 }
2975 
2976 /// getPreIndexedAddressParts - returns true by value, base pointer and
2977 /// offset pointer and addressing mode by reference if the node's address
2978 /// can be legally represented as pre-indexed load / store address.
2979 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2980                                                   SDValue &Offset,
2981                                                   ISD::MemIndexedMode &AM,
2982                                                   SelectionDAG &DAG) const {
2983   if (DisablePPCPreinc) return false;
2984 
2985   bool isLoad = true;
2986   SDValue Ptr;
2987   EVT VT;
2988   unsigned Alignment;
2989   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2990     Ptr = LD->getBasePtr();
2991     VT = LD->getMemoryVT();
2992     Alignment = LD->getAlignment();
2993   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2994     Ptr = ST->getBasePtr();
2995     VT  = ST->getMemoryVT();
2996     Alignment = ST->getAlignment();
2997     isLoad = false;
2998   } else
2999     return false;
3000 
3001   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
3002   // instructions because we can fold these into a more efficient instruction
3003   // instead, (such as LXSD).
3004   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
3005     return false;
3006   }
3007 
3008   // PowerPC doesn't have preinc load/store instructions for vectors
3009   if (VT.isVector())
3010     return false;
3011 
3012   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3013     // Common code will reject creating a pre-inc form if the base pointer
3014     // is a frame index, or if N is a store and the base pointer is either
3015     // the same as or a predecessor of the value being stored.  Check for
3016     // those situations here, and try with swapped Base/Offset instead.
3017     bool Swap = false;
3018 
3019     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3020       Swap = true;
3021     else if (!isLoad) {
3022       SDValue Val = cast<StoreSDNode>(N)->getValue();
3023       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3024         Swap = true;
3025     }
3026 
3027     if (Swap)
3028       std::swap(Base, Offset);
3029 
3030     AM = ISD::PRE_INC;
3031     return true;
3032   }
3033 
3034   // LDU/STU can only handle immediates that are a multiple of 4.
3035   if (VT != MVT::i64) {
3036     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
3037       return false;
3038   } else {
3039     // LDU/STU need an address with at least 4-byte alignment.
3040     if (Alignment < 4)
3041       return false;
3042 
3043     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3044       return false;
3045   }
3046 
3047   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3048     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3049     // sext i32 to i64 when addr mode is r+i.
3050     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3051         LD->getExtensionType() == ISD::SEXTLOAD &&
3052         isa<ConstantSDNode>(Offset))
3053       return false;
3054   }
3055 
3056   AM = ISD::PRE_INC;
3057   return true;
3058 }
3059 
3060 //===----------------------------------------------------------------------===//
3061 //  LowerOperation implementation
3062 //===----------------------------------------------------------------------===//
3063 
3064 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3065 /// and LoOpFlags to the target MO flags.
3066 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3067                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3068                                const GlobalValue *GV = nullptr) {
3069   HiOpFlags = PPCII::MO_HA;
3070   LoOpFlags = PPCII::MO_LO;
3071 
3072   // Don't use the pic base if not in PIC relocation model.
3073   if (IsPIC) {
3074     HiOpFlags |= PPCII::MO_PIC_FLAG;
3075     LoOpFlags |= PPCII::MO_PIC_FLAG;
3076   }
3077 }
3078 
3079 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3080                              SelectionDAG &DAG) {
3081   SDLoc DL(HiPart);
3082   EVT PtrVT = HiPart.getValueType();
3083   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3084 
3085   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3086   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3087 
3088   // With PIC, the first instruction is actually "GR+hi(&G)".
3089   if (isPIC)
3090     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3091                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3092 
3093   // Generate non-pic code that has direct accesses to the constant pool.
3094   // The address of the global is just (hi(&g)+lo(&g)).
3095   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3096 }
3097 
3098 static void setUsesTOCBasePtr(MachineFunction &MF) {
3099   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3100   FuncInfo->setUsesTOCBasePtr();
3101 }
3102 
3103 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3104   setUsesTOCBasePtr(DAG.getMachineFunction());
3105 }
3106 
3107 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3108                                        SDValue GA) const {
3109   const bool Is64Bit = Subtarget.isPPC64();
3110   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3111   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3112                         : Subtarget.isAIXABI()
3113                               ? DAG.getRegister(PPC::R2, VT)
3114                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3115   SDValue Ops[] = { GA, Reg };
3116   return DAG.getMemIntrinsicNode(
3117       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3118       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3119       MachineMemOperand::MOLoad);
3120 }
3121 
3122 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3123                                              SelectionDAG &DAG) const {
3124   EVT PtrVT = Op.getValueType();
3125   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3126   const Constant *C = CP->getConstVal();
3127 
3128   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3129   // The actual address of the GlobalValue is stored in the TOC.
3130   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3131     if (Subtarget.isUsingPCRelativeCalls()) {
3132       SDLoc DL(CP);
3133       EVT Ty = getPointerTy(DAG.getDataLayout());
3134       SDValue ConstPool = DAG.getTargetConstantPool(
3135           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3136       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3137     }
3138     setUsesTOCBasePtr(DAG);
3139     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3140     return getTOCEntry(DAG, SDLoc(CP), GA);
3141   }
3142 
3143   unsigned MOHiFlag, MOLoFlag;
3144   bool IsPIC = isPositionIndependent();
3145   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3146 
3147   if (IsPIC && Subtarget.isSVR4ABI()) {
3148     SDValue GA =
3149         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3150     return getTOCEntry(DAG, SDLoc(CP), GA);
3151   }
3152 
3153   SDValue CPIHi =
3154       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3155   SDValue CPILo =
3156       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3157   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3158 }
3159 
3160 // For 64-bit PowerPC, prefer the more compact relative encodings.
3161 // This trades 32 bits per jump table entry for one or two instructions
3162 // on the jump site.
3163 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3164   if (isJumpTableRelative())
3165     return MachineJumpTableInfo::EK_LabelDifference32;
3166 
3167   return TargetLowering::getJumpTableEncoding();
3168 }
3169 
3170 bool PPCTargetLowering::isJumpTableRelative() const {
3171   if (UseAbsoluteJumpTables)
3172     return false;
3173   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3174     return true;
3175   return TargetLowering::isJumpTableRelative();
3176 }
3177 
3178 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3179                                                     SelectionDAG &DAG) const {
3180   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3181     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3182 
3183   switch (getTargetMachine().getCodeModel()) {
3184   case CodeModel::Small:
3185   case CodeModel::Medium:
3186     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3187   default:
3188     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3189                        getPointerTy(DAG.getDataLayout()));
3190   }
3191 }
3192 
3193 const MCExpr *
3194 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3195                                                 unsigned JTI,
3196                                                 MCContext &Ctx) const {
3197   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3198     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3199 
3200   switch (getTargetMachine().getCodeModel()) {
3201   case CodeModel::Small:
3202   case CodeModel::Medium:
3203     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3204   default:
3205     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3206   }
3207 }
3208 
3209 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3210   EVT PtrVT = Op.getValueType();
3211   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3212 
3213   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3214   if (Subtarget.isUsingPCRelativeCalls()) {
3215     SDLoc DL(JT);
3216     EVT Ty = getPointerTy(DAG.getDataLayout());
3217     SDValue GA =
3218         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3219     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3220     return MatAddr;
3221   }
3222 
3223   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3224   // The actual address of the GlobalValue is stored in the TOC.
3225   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3226     setUsesTOCBasePtr(DAG);
3227     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3228     return getTOCEntry(DAG, SDLoc(JT), GA);
3229   }
3230 
3231   unsigned MOHiFlag, MOLoFlag;
3232   bool IsPIC = isPositionIndependent();
3233   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3234 
3235   if (IsPIC && Subtarget.isSVR4ABI()) {
3236     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3237                                         PPCII::MO_PIC_FLAG);
3238     return getTOCEntry(DAG, SDLoc(GA), GA);
3239   }
3240 
3241   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3242   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3243   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3244 }
3245 
3246 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3247                                              SelectionDAG &DAG) const {
3248   EVT PtrVT = Op.getValueType();
3249   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3250   const BlockAddress *BA = BASDN->getBlockAddress();
3251 
3252   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3253   if (Subtarget.isUsingPCRelativeCalls()) {
3254     SDLoc DL(BASDN);
3255     EVT Ty = getPointerTy(DAG.getDataLayout());
3256     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3257                                            PPCII::MO_PCREL_FLAG);
3258     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3259     return MatAddr;
3260   }
3261 
3262   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3263   // The actual BlockAddress is stored in the TOC.
3264   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3265     setUsesTOCBasePtr(DAG);
3266     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3267     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3268   }
3269 
3270   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3271   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3272     return getTOCEntry(
3273         DAG, SDLoc(BASDN),
3274         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3275 
3276   unsigned MOHiFlag, MOLoFlag;
3277   bool IsPIC = isPositionIndependent();
3278   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3279   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3280   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3281   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3282 }
3283 
3284 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3285                                               SelectionDAG &DAG) const {
3286   if (Subtarget.isAIXABI())
3287     return LowerGlobalTLSAddressAIX(Op, DAG);
3288 
3289   return LowerGlobalTLSAddressLinux(Op, DAG);
3290 }
3291 
3292 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3293                                                     SelectionDAG &DAG) const {
3294   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3295 
3296   if (DAG.getTarget().useEmulatedTLS())
3297     report_fatal_error("Emulated TLS is not yet supported on AIX");
3298 
3299   SDLoc dl(GA);
3300   const GlobalValue *GV = GA->getGlobal();
3301   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3302 
3303   // The general-dynamic model is the only access model supported for now, so
3304   // all the GlobalTLSAddress nodes are lowered with this model.
3305   // We need to generate two TOC entries, one for the variable offset, one for
3306   // the region handle. The global address for the TOC entry of the region
3307   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3308   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3309   SDValue VariableOffsetTGA =
3310       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3311   SDValue RegionHandleTGA =
3312       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3313   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3314   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3315   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3316                      RegionHandle);
3317 }
3318 
3319 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3320                                                       SelectionDAG &DAG) const {
3321   // FIXME: TLS addresses currently use medium model code sequences,
3322   // which is the most useful form.  Eventually support for small and
3323   // large models could be added if users need it, at the cost of
3324   // additional complexity.
3325   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3326   if (DAG.getTarget().useEmulatedTLS())
3327     return LowerToTLSEmulatedModel(GA, DAG);
3328 
3329   SDLoc dl(GA);
3330   const GlobalValue *GV = GA->getGlobal();
3331   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3332   bool is64bit = Subtarget.isPPC64();
3333   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3334   PICLevel::Level picLevel = M->getPICLevel();
3335 
3336   const TargetMachine &TM = getTargetMachine();
3337   TLSModel::Model Model = TM.getTLSModel(GV);
3338 
3339   if (Model == TLSModel::LocalExec) {
3340     if (Subtarget.isUsingPCRelativeCalls()) {
3341       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3342       SDValue TGA = DAG.getTargetGlobalAddress(
3343           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3344       SDValue MatAddr =
3345           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3346       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3347     }
3348 
3349     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3350                                                PPCII::MO_TPREL_HA);
3351     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3352                                                PPCII::MO_TPREL_LO);
3353     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3354                              : DAG.getRegister(PPC::R2, MVT::i32);
3355 
3356     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3357     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3358   }
3359 
3360   if (Model == TLSModel::InitialExec) {
3361     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3362     SDValue TGA = DAG.getTargetGlobalAddress(
3363         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3364     SDValue TGATLS = DAG.getTargetGlobalAddress(
3365         GV, dl, PtrVT, 0,
3366         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3367     SDValue TPOffset;
3368     if (IsPCRel) {
3369       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3370       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3371                              MachinePointerInfo());
3372     } else {
3373       SDValue GOTPtr;
3374       if (is64bit) {
3375         setUsesTOCBasePtr(DAG);
3376         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3377         GOTPtr =
3378             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3379       } else {
3380         if (!TM.isPositionIndependent())
3381           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3382         else if (picLevel == PICLevel::SmallPIC)
3383           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3384         else
3385           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3386       }
3387       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3388     }
3389     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3390   }
3391 
3392   if (Model == TLSModel::GeneralDynamic) {
3393     if (Subtarget.isUsingPCRelativeCalls()) {
3394       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3395                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3396       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3397     }
3398 
3399     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3400     SDValue GOTPtr;
3401     if (is64bit) {
3402       setUsesTOCBasePtr(DAG);
3403       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3404       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3405                                    GOTReg, TGA);
3406     } else {
3407       if (picLevel == PICLevel::SmallPIC)
3408         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3409       else
3410         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3411     }
3412     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3413                        GOTPtr, TGA, TGA);
3414   }
3415 
3416   if (Model == TLSModel::LocalDynamic) {
3417     if (Subtarget.isUsingPCRelativeCalls()) {
3418       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3419                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3420       SDValue MatPCRel =
3421           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3422       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3423     }
3424 
3425     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3426     SDValue GOTPtr;
3427     if (is64bit) {
3428       setUsesTOCBasePtr(DAG);
3429       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3430       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3431                            GOTReg, TGA);
3432     } else {
3433       if (picLevel == PICLevel::SmallPIC)
3434         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3435       else
3436         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3437     }
3438     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3439                                   PtrVT, GOTPtr, TGA, TGA);
3440     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3441                                       PtrVT, TLSAddr, TGA);
3442     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3443   }
3444 
3445   llvm_unreachable("Unknown TLS model!");
3446 }
3447 
3448 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3449                                               SelectionDAG &DAG) const {
3450   EVT PtrVT = Op.getValueType();
3451   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3452   SDLoc DL(GSDN);
3453   const GlobalValue *GV = GSDN->getGlobal();
3454 
3455   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3456   // The actual address of the GlobalValue is stored in the TOC.
3457   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3458     if (Subtarget.isUsingPCRelativeCalls()) {
3459       EVT Ty = getPointerTy(DAG.getDataLayout());
3460       if (isAccessedAsGotIndirect(Op)) {
3461         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3462                                                 PPCII::MO_PCREL_FLAG |
3463                                                     PPCII::MO_GOT_FLAG);
3464         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3465         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3466                                    MachinePointerInfo());
3467         return Load;
3468       } else {
3469         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3470                                                 PPCII::MO_PCREL_FLAG);
3471         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3472       }
3473     }
3474     setUsesTOCBasePtr(DAG);
3475     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3476     return getTOCEntry(DAG, DL, GA);
3477   }
3478 
3479   unsigned MOHiFlag, MOLoFlag;
3480   bool IsPIC = isPositionIndependent();
3481   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3482 
3483   if (IsPIC && Subtarget.isSVR4ABI()) {
3484     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3485                                             GSDN->getOffset(),
3486                                             PPCII::MO_PIC_FLAG);
3487     return getTOCEntry(DAG, DL, GA);
3488   }
3489 
3490   SDValue GAHi =
3491     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3492   SDValue GALo =
3493     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3494 
3495   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3496 }
3497 
3498 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3499   bool IsStrict = Op->isStrictFPOpcode();
3500   ISD::CondCode CC =
3501       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3502   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3503   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3504   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3505   EVT LHSVT = LHS.getValueType();
3506   SDLoc dl(Op);
3507 
3508   // Soften the setcc with libcall if it is fp128.
3509   if (LHSVT == MVT::f128) {
3510     assert(!Subtarget.hasP9Vector() &&
3511            "SETCC for f128 is already legal under Power9!");
3512     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3513                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3514     if (RHS.getNode())
3515       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3516                         DAG.getCondCode(CC));
3517     if (IsStrict)
3518       return DAG.getMergeValues({LHS, Chain}, dl);
3519     return LHS;
3520   }
3521 
3522   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3523 
3524   if (Op.getValueType() == MVT::v2i64) {
3525     // When the operands themselves are v2i64 values, we need to do something
3526     // special because VSX has no underlying comparison operations for these.
3527     if (LHS.getValueType() == MVT::v2i64) {
3528       // Equality can be handled by casting to the legal type for Altivec
3529       // comparisons, everything else needs to be expanded.
3530       if (CC != ISD::SETEQ && CC != ISD::SETNE)
3531         return SDValue();
3532       SDValue SetCC32 = DAG.getSetCC(
3533           dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3534           DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3535       int ShuffV[] = {1, 0, 3, 2};
3536       SDValue Shuff =
3537           DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3538       return DAG.getBitcast(MVT::v2i64,
3539                             DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3540                                         dl, MVT::v4i32, Shuff, SetCC32));
3541     }
3542 
3543     // We handle most of these in the usual way.
3544     return Op;
3545   }
3546 
3547   // If we're comparing for equality to zero, expose the fact that this is
3548   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3549   // fold the new nodes.
3550   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3551     return V;
3552 
3553   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3554     // Leave comparisons against 0 and -1 alone for now, since they're usually
3555     // optimized.  FIXME: revisit this when we can custom lower all setcc
3556     // optimizations.
3557     if (C->isAllOnes() || C->isZero())
3558       return SDValue();
3559   }
3560 
3561   // If we have an integer seteq/setne, turn it into a compare against zero
3562   // by xor'ing the rhs with the lhs, which is faster than setting a
3563   // condition register, reading it back out, and masking the correct bit.  The
3564   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3565   // the result to other bit-twiddling opportunities.
3566   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3567     EVT VT = Op.getValueType();
3568     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3569     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3570   }
3571   return SDValue();
3572 }
3573 
3574 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3575   SDNode *Node = Op.getNode();
3576   EVT VT = Node->getValueType(0);
3577   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3578   SDValue InChain = Node->getOperand(0);
3579   SDValue VAListPtr = Node->getOperand(1);
3580   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3581   SDLoc dl(Node);
3582 
3583   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3584 
3585   // gpr_index
3586   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3587                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3588   InChain = GprIndex.getValue(1);
3589 
3590   if (VT == MVT::i64) {
3591     // Check if GprIndex is even
3592     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3593                                  DAG.getConstant(1, dl, MVT::i32));
3594     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3595                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3596     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3597                                           DAG.getConstant(1, dl, MVT::i32));
3598     // Align GprIndex to be even if it isn't
3599     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3600                            GprIndex);
3601   }
3602 
3603   // fpr index is 1 byte after gpr
3604   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3605                                DAG.getConstant(1, dl, MVT::i32));
3606 
3607   // fpr
3608   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3609                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3610   InChain = FprIndex.getValue(1);
3611 
3612   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3613                                        DAG.getConstant(8, dl, MVT::i32));
3614 
3615   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3616                                         DAG.getConstant(4, dl, MVT::i32));
3617 
3618   // areas
3619   SDValue OverflowArea =
3620       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3621   InChain = OverflowArea.getValue(1);
3622 
3623   SDValue RegSaveArea =
3624       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3625   InChain = RegSaveArea.getValue(1);
3626 
3627   // select overflow_area if index > 8
3628   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3629                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3630 
3631   // adjustment constant gpr_index * 4/8
3632   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3633                                     VT.isInteger() ? GprIndex : FprIndex,
3634                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3635                                                     MVT::i32));
3636 
3637   // OurReg = RegSaveArea + RegConstant
3638   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3639                                RegConstant);
3640 
3641   // Floating types are 32 bytes into RegSaveArea
3642   if (VT.isFloatingPoint())
3643     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3644                          DAG.getConstant(32, dl, MVT::i32));
3645 
3646   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3647   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3648                                    VT.isInteger() ? GprIndex : FprIndex,
3649                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3650                                                    MVT::i32));
3651 
3652   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3653                               VT.isInteger() ? VAListPtr : FprPtr,
3654                               MachinePointerInfo(SV), MVT::i8);
3655 
3656   // determine if we should load from reg_save_area or overflow_area
3657   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3658 
3659   // increase overflow_area by 4/8 if gpr/fpr > 8
3660   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3661                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3662                                           dl, MVT::i32));
3663 
3664   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3665                              OverflowAreaPlusN);
3666 
3667   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3668                               MachinePointerInfo(), MVT::i32);
3669 
3670   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3671 }
3672 
3673 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3674   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3675 
3676   // We have to copy the entire va_list struct:
3677   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3678   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3679                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3680                        false, true, false, MachinePointerInfo(),
3681                        MachinePointerInfo());
3682 }
3683 
3684 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3685                                                   SelectionDAG &DAG) const {
3686   if (Subtarget.isAIXABI())
3687     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3688 
3689   return Op.getOperand(0);
3690 }
3691 
3692 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3693   MachineFunction &MF = DAG.getMachineFunction();
3694   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3695 
3696   assert((Op.getOpcode() == ISD::INLINEASM ||
3697           Op.getOpcode() == ISD::INLINEASM_BR) &&
3698          "Expecting Inline ASM node.");
3699 
3700   // If an LR store is already known to be required then there is not point in
3701   // checking this ASM as well.
3702   if (MFI.isLRStoreRequired())
3703     return Op;
3704 
3705   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3706   // type MVT::Glue. We want to ignore this last operand if that is the case.
3707   unsigned NumOps = Op.getNumOperands();
3708   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3709     --NumOps;
3710 
3711   // Check all operands that may contain the LR.
3712   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3713     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3714     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3715     ++i; // Skip the ID value.
3716 
3717     switch (InlineAsm::getKind(Flags)) {
3718     default:
3719       llvm_unreachable("Bad flags!");
3720     case InlineAsm::Kind_RegUse:
3721     case InlineAsm::Kind_Imm:
3722     case InlineAsm::Kind_Mem:
3723       i += NumVals;
3724       break;
3725     case InlineAsm::Kind_Clobber:
3726     case InlineAsm::Kind_RegDef:
3727     case InlineAsm::Kind_RegDefEarlyClobber: {
3728       for (; NumVals; --NumVals, ++i) {
3729         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3730         if (Reg != PPC::LR && Reg != PPC::LR8)
3731           continue;
3732         MFI.setLRStoreRequired();
3733         return Op;
3734       }
3735       break;
3736     }
3737     }
3738   }
3739 
3740   return Op;
3741 }
3742 
3743 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3744                                                 SelectionDAG &DAG) const {
3745   if (Subtarget.isAIXABI())
3746     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3747 
3748   SDValue Chain = Op.getOperand(0);
3749   SDValue Trmp = Op.getOperand(1); // trampoline
3750   SDValue FPtr = Op.getOperand(2); // nested function
3751   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3752   SDLoc dl(Op);
3753 
3754   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3755   bool isPPC64 = (PtrVT == MVT::i64);
3756   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3757 
3758   TargetLowering::ArgListTy Args;
3759   TargetLowering::ArgListEntry Entry;
3760 
3761   Entry.Ty = IntPtrTy;
3762   Entry.Node = Trmp; Args.push_back(Entry);
3763 
3764   // TrampSize == (isPPC64 ? 48 : 40);
3765   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3766                                isPPC64 ? MVT::i64 : MVT::i32);
3767   Args.push_back(Entry);
3768 
3769   Entry.Node = FPtr; Args.push_back(Entry);
3770   Entry.Node = Nest; Args.push_back(Entry);
3771 
3772   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3773   TargetLowering::CallLoweringInfo CLI(DAG);
3774   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3775       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3776       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3777 
3778   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3779   return CallResult.second;
3780 }
3781 
3782 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3783   MachineFunction &MF = DAG.getMachineFunction();
3784   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3785   EVT PtrVT = getPointerTy(MF.getDataLayout());
3786 
3787   SDLoc dl(Op);
3788 
3789   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3790     // vastart just stores the address of the VarArgsFrameIndex slot into the
3791     // memory location argument.
3792     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3793     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3794     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3795                         MachinePointerInfo(SV));
3796   }
3797 
3798   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3799   // We suppose the given va_list is already allocated.
3800   //
3801   // typedef struct {
3802   //  char gpr;     /* index into the array of 8 GPRs
3803   //                 * stored in the register save area
3804   //                 * gpr=0 corresponds to r3,
3805   //                 * gpr=1 to r4, etc.
3806   //                 */
3807   //  char fpr;     /* index into the array of 8 FPRs
3808   //                 * stored in the register save area
3809   //                 * fpr=0 corresponds to f1,
3810   //                 * fpr=1 to f2, etc.
3811   //                 */
3812   //  char *overflow_arg_area;
3813   //                /* location on stack that holds
3814   //                 * the next overflow argument
3815   //                 */
3816   //  char *reg_save_area;
3817   //               /* where r3:r10 and f1:f8 (if saved)
3818   //                * are stored
3819   //                */
3820   // } va_list[1];
3821 
3822   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3823   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3824   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3825                                             PtrVT);
3826   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3827                                  PtrVT);
3828 
3829   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3830   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3831 
3832   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3833   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3834 
3835   uint64_t FPROffset = 1;
3836   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3837 
3838   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3839 
3840   // Store first byte : number of int regs
3841   SDValue firstStore =
3842       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3843                         MachinePointerInfo(SV), MVT::i8);
3844   uint64_t nextOffset = FPROffset;
3845   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3846                                   ConstFPROffset);
3847 
3848   // Store second byte : number of float regs
3849   SDValue secondStore =
3850       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3851                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3852   nextOffset += StackOffset;
3853   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3854 
3855   // Store second word : arguments given on stack
3856   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3857                                     MachinePointerInfo(SV, nextOffset));
3858   nextOffset += FrameOffset;
3859   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3860 
3861   // Store third word : arguments given in registers
3862   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3863                       MachinePointerInfo(SV, nextOffset));
3864 }
3865 
3866 /// FPR - The set of FP registers that should be allocated for arguments
3867 /// on Darwin and AIX.
3868 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3869                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3870                                 PPC::F11, PPC::F12, PPC::F13};
3871 
3872 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3873 /// the stack.
3874 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3875                                        unsigned PtrByteSize) {
3876   unsigned ArgSize = ArgVT.getStoreSize();
3877   if (Flags.isByVal())
3878     ArgSize = Flags.getByValSize();
3879 
3880   // Round up to multiples of the pointer size, except for array members,
3881   // which are always packed.
3882   if (!Flags.isInConsecutiveRegs())
3883     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3884 
3885   return ArgSize;
3886 }
3887 
3888 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3889 /// on the stack.
3890 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3891                                          ISD::ArgFlagsTy Flags,
3892                                          unsigned PtrByteSize) {
3893   Align Alignment(PtrByteSize);
3894 
3895   // Altivec parameters are padded to a 16 byte boundary.
3896   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3897       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3898       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3899       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3900     Alignment = Align(16);
3901 
3902   // ByVal parameters are aligned as requested.
3903   if (Flags.isByVal()) {
3904     auto BVAlign = Flags.getNonZeroByValAlign();
3905     if (BVAlign > PtrByteSize) {
3906       if (BVAlign.value() % PtrByteSize != 0)
3907         llvm_unreachable(
3908             "ByVal alignment is not a multiple of the pointer size");
3909 
3910       Alignment = BVAlign;
3911     }
3912   }
3913 
3914   // Array members are always packed to their original alignment.
3915   if (Flags.isInConsecutiveRegs()) {
3916     // If the array member was split into multiple registers, the first
3917     // needs to be aligned to the size of the full type.  (Except for
3918     // ppcf128, which is only aligned as its f64 components.)
3919     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3920       Alignment = Align(OrigVT.getStoreSize());
3921     else
3922       Alignment = Align(ArgVT.getStoreSize());
3923   }
3924 
3925   return Alignment;
3926 }
3927 
3928 /// CalculateStackSlotUsed - Return whether this argument will use its
3929 /// stack slot (instead of being passed in registers).  ArgOffset,
3930 /// AvailableFPRs, and AvailableVRs must hold the current argument
3931 /// position, and will be updated to account for this argument.
3932 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3933                                    unsigned PtrByteSize, unsigned LinkageSize,
3934                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3935                                    unsigned &AvailableFPRs,
3936                                    unsigned &AvailableVRs) {
3937   bool UseMemory = false;
3938 
3939   // Respect alignment of argument on the stack.
3940   Align Alignment =
3941       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3942   ArgOffset = alignTo(ArgOffset, Alignment);
3943   // If there's no space left in the argument save area, we must
3944   // use memory (this check also catches zero-sized arguments).
3945   if (ArgOffset >= LinkageSize + ParamAreaSize)
3946     UseMemory = true;
3947 
3948   // Allocate argument on the stack.
3949   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3950   if (Flags.isInConsecutiveRegsLast())
3951     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3952   // If we overran the argument save area, we must use memory
3953   // (this check catches arguments passed partially in memory)
3954   if (ArgOffset > LinkageSize + ParamAreaSize)
3955     UseMemory = true;
3956 
3957   // However, if the argument is actually passed in an FPR or a VR,
3958   // we don't use memory after all.
3959   if (!Flags.isByVal()) {
3960     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3961       if (AvailableFPRs > 0) {
3962         --AvailableFPRs;
3963         return false;
3964       }
3965     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3966         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3967         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3968         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3969       if (AvailableVRs > 0) {
3970         --AvailableVRs;
3971         return false;
3972       }
3973   }
3974 
3975   return UseMemory;
3976 }
3977 
3978 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3979 /// ensure minimum alignment required for target.
3980 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3981                                      unsigned NumBytes) {
3982   return alignTo(NumBytes, Lowering->getStackAlign());
3983 }
3984 
3985 SDValue PPCTargetLowering::LowerFormalArguments(
3986     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3987     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3988     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3989   if (Subtarget.isAIXABI())
3990     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3991                                     InVals);
3992   if (Subtarget.is64BitELFABI())
3993     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3994                                        InVals);
3995   assert(Subtarget.is32BitELFABI());
3996   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3997                                      InVals);
3998 }
3999 
4000 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
4001     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4002     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4003     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4004 
4005   // 32-bit SVR4 ABI Stack Frame Layout:
4006   //              +-----------------------------------+
4007   //        +-->  |            Back chain             |
4008   //        |     +-----------------------------------+
4009   //        |     | Floating-point register save area |
4010   //        |     +-----------------------------------+
4011   //        |     |    General register save area     |
4012   //        |     +-----------------------------------+
4013   //        |     |          CR save word             |
4014   //        |     +-----------------------------------+
4015   //        |     |         VRSAVE save word          |
4016   //        |     +-----------------------------------+
4017   //        |     |         Alignment padding         |
4018   //        |     +-----------------------------------+
4019   //        |     |     Vector register save area     |
4020   //        |     +-----------------------------------+
4021   //        |     |       Local variable space        |
4022   //        |     +-----------------------------------+
4023   //        |     |        Parameter list area        |
4024   //        |     +-----------------------------------+
4025   //        |     |           LR save word            |
4026   //        |     +-----------------------------------+
4027   // SP-->  +---  |            Back chain             |
4028   //              +-----------------------------------+
4029   //
4030   // Specifications:
4031   //   System V Application Binary Interface PowerPC Processor Supplement
4032   //   AltiVec Technology Programming Interface Manual
4033 
4034   MachineFunction &MF = DAG.getMachineFunction();
4035   MachineFrameInfo &MFI = MF.getFrameInfo();
4036   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4037 
4038   EVT PtrVT = getPointerTy(MF.getDataLayout());
4039   // Potential tail calls could cause overwriting of argument stack slots.
4040   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4041                        (CallConv == CallingConv::Fast));
4042   const Align PtrAlign(4);
4043 
4044   // Assign locations to all of the incoming arguments.
4045   SmallVector<CCValAssign, 16> ArgLocs;
4046   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4047                  *DAG.getContext());
4048 
4049   // Reserve space for the linkage area on the stack.
4050   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4051   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4052   if (useSoftFloat())
4053     CCInfo.PreAnalyzeFormalArguments(Ins);
4054 
4055   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4056   CCInfo.clearWasPPCF128();
4057 
4058   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4059     CCValAssign &VA = ArgLocs[i];
4060 
4061     // Arguments stored in registers.
4062     if (VA.isRegLoc()) {
4063       const TargetRegisterClass *RC;
4064       EVT ValVT = VA.getValVT();
4065 
4066       switch (ValVT.getSimpleVT().SimpleTy) {
4067         default:
4068           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4069         case MVT::i1:
4070         case MVT::i32:
4071           RC = &PPC::GPRCRegClass;
4072           break;
4073         case MVT::f32:
4074           if (Subtarget.hasP8Vector())
4075             RC = &PPC::VSSRCRegClass;
4076           else if (Subtarget.hasSPE())
4077             RC = &PPC::GPRCRegClass;
4078           else
4079             RC = &PPC::F4RCRegClass;
4080           break;
4081         case MVT::f64:
4082           if (Subtarget.hasVSX())
4083             RC = &PPC::VSFRCRegClass;
4084           else if (Subtarget.hasSPE())
4085             // SPE passes doubles in GPR pairs.
4086             RC = &PPC::GPRCRegClass;
4087           else
4088             RC = &PPC::F8RCRegClass;
4089           break;
4090         case MVT::v16i8:
4091         case MVT::v8i16:
4092         case MVT::v4i32:
4093           RC = &PPC::VRRCRegClass;
4094           break;
4095         case MVT::v4f32:
4096           RC = &PPC::VRRCRegClass;
4097           break;
4098         case MVT::v2f64:
4099         case MVT::v2i64:
4100           RC = &PPC::VRRCRegClass;
4101           break;
4102       }
4103 
4104       SDValue ArgValue;
4105       // Transform the arguments stored in physical registers into
4106       // virtual ones.
4107       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4108         assert(i + 1 < e && "No second half of double precision argument");
4109         Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4110         Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4111         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4112         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4113         if (!Subtarget.isLittleEndian())
4114           std::swap (ArgValueLo, ArgValueHi);
4115         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4116                                ArgValueHi);
4117       } else {
4118         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4119         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4120                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4121         if (ValVT == MVT::i1)
4122           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4123       }
4124 
4125       InVals.push_back(ArgValue);
4126     } else {
4127       // Argument stored in memory.
4128       assert(VA.isMemLoc());
4129 
4130       // Get the extended size of the argument type in stack
4131       unsigned ArgSize = VA.getLocVT().getStoreSize();
4132       // Get the actual size of the argument type
4133       unsigned ObjSize = VA.getValVT().getStoreSize();
4134       unsigned ArgOffset = VA.getLocMemOffset();
4135       // Stack objects in PPC32 are right justified.
4136       ArgOffset += ArgSize - ObjSize;
4137       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4138 
4139       // Create load nodes to retrieve arguments from the stack.
4140       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4141       InVals.push_back(
4142           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4143     }
4144   }
4145 
4146   // Assign locations to all of the incoming aggregate by value arguments.
4147   // Aggregates passed by value are stored in the local variable space of the
4148   // caller's stack frame, right above the parameter list area.
4149   SmallVector<CCValAssign, 16> ByValArgLocs;
4150   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4151                       ByValArgLocs, *DAG.getContext());
4152 
4153   // Reserve stack space for the allocations in CCInfo.
4154   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4155 
4156   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4157 
4158   // Area that is at least reserved in the caller of this function.
4159   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4160   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4161 
4162   // Set the size that is at least reserved in caller of this function.  Tail
4163   // call optimized function's reserved stack space needs to be aligned so that
4164   // taking the difference between two stack areas will result in an aligned
4165   // stack.
4166   MinReservedArea =
4167       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4168   FuncInfo->setMinReservedArea(MinReservedArea);
4169 
4170   SmallVector<SDValue, 8> MemOps;
4171 
4172   // If the function takes variable number of arguments, make a frame index for
4173   // the start of the first vararg value... for expansion of llvm.va_start.
4174   if (isVarArg) {
4175     static const MCPhysReg GPArgRegs[] = {
4176       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4177       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4178     };
4179     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4180 
4181     static const MCPhysReg FPArgRegs[] = {
4182       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4183       PPC::F8
4184     };
4185     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4186 
4187     if (useSoftFloat() || hasSPE())
4188        NumFPArgRegs = 0;
4189 
4190     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4191     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4192 
4193     // Make room for NumGPArgRegs and NumFPArgRegs.
4194     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4195                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4196 
4197     FuncInfo->setVarArgsStackOffset(
4198       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4199                             CCInfo.getNextStackOffset(), true));
4200 
4201     FuncInfo->setVarArgsFrameIndex(
4202         MFI.CreateStackObject(Depth, Align(8), false));
4203     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4204 
4205     // The fixed integer arguments of a variadic function are stored to the
4206     // VarArgsFrameIndex on the stack so that they may be loaded by
4207     // dereferencing the result of va_next.
4208     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4209       // Get an existing live-in vreg, or add a new one.
4210       Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4211       if (!VReg)
4212         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4213 
4214       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4215       SDValue Store =
4216           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4217       MemOps.push_back(Store);
4218       // Increment the address by four for the next argument to store
4219       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4220       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4221     }
4222 
4223     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4224     // is set.
4225     // The double arguments are stored to the VarArgsFrameIndex
4226     // on the stack.
4227     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4228       // Get an existing live-in vreg, or add a new one.
4229       Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4230       if (!VReg)
4231         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4232 
4233       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4234       SDValue Store =
4235           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4236       MemOps.push_back(Store);
4237       // Increment the address by eight for the next argument to store
4238       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4239                                          PtrVT);
4240       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4241     }
4242   }
4243 
4244   if (!MemOps.empty())
4245     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4246 
4247   return Chain;
4248 }
4249 
4250 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4251 // value to MVT::i64 and then truncate to the correct register size.
4252 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4253                                              EVT ObjectVT, SelectionDAG &DAG,
4254                                              SDValue ArgVal,
4255                                              const SDLoc &dl) const {
4256   if (Flags.isSExt())
4257     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4258                          DAG.getValueType(ObjectVT));
4259   else if (Flags.isZExt())
4260     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4261                          DAG.getValueType(ObjectVT));
4262 
4263   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4264 }
4265 
4266 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4267     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4268     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4269     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4270   // TODO: add description of PPC stack frame format, or at least some docs.
4271   //
4272   bool isELFv2ABI = Subtarget.isELFv2ABI();
4273   bool isLittleEndian = Subtarget.isLittleEndian();
4274   MachineFunction &MF = DAG.getMachineFunction();
4275   MachineFrameInfo &MFI = MF.getFrameInfo();
4276   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4277 
4278   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4279          "fastcc not supported on varargs functions");
4280 
4281   EVT PtrVT = getPointerTy(MF.getDataLayout());
4282   // Potential tail calls could cause overwriting of argument stack slots.
4283   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4284                        (CallConv == CallingConv::Fast));
4285   unsigned PtrByteSize = 8;
4286   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4287 
4288   static const MCPhysReg GPR[] = {
4289     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4290     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4291   };
4292   static const MCPhysReg VR[] = {
4293     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4294     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4295   };
4296 
4297   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4298   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4299   const unsigned Num_VR_Regs  = array_lengthof(VR);
4300 
4301   // Do a first pass over the arguments to determine whether the ABI
4302   // guarantees that our caller has allocated the parameter save area
4303   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4304   // in the ELFv2 ABI, it is true if this is a vararg function or if
4305   // any parameter is located in a stack slot.
4306 
4307   bool HasParameterArea = !isELFv2ABI || isVarArg;
4308   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4309   unsigned NumBytes = LinkageSize;
4310   unsigned AvailableFPRs = Num_FPR_Regs;
4311   unsigned AvailableVRs = Num_VR_Regs;
4312   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4313     if (Ins[i].Flags.isNest())
4314       continue;
4315 
4316     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4317                                PtrByteSize, LinkageSize, ParamAreaSize,
4318                                NumBytes, AvailableFPRs, AvailableVRs))
4319       HasParameterArea = true;
4320   }
4321 
4322   // Add DAG nodes to load the arguments or copy them out of registers.  On
4323   // entry to a function on PPC, the arguments start after the linkage area,
4324   // although the first ones are often in registers.
4325 
4326   unsigned ArgOffset = LinkageSize;
4327   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4328   SmallVector<SDValue, 8> MemOps;
4329   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4330   unsigned CurArgIdx = 0;
4331   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4332     SDValue ArgVal;
4333     bool needsLoad = false;
4334     EVT ObjectVT = Ins[ArgNo].VT;
4335     EVT OrigVT = Ins[ArgNo].ArgVT;
4336     unsigned ObjSize = ObjectVT.getStoreSize();
4337     unsigned ArgSize = ObjSize;
4338     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4339     if (Ins[ArgNo].isOrigArg()) {
4340       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4341       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4342     }
4343     // We re-align the argument offset for each argument, except when using the
4344     // fast calling convention, when we need to make sure we do that only when
4345     // we'll actually use a stack slot.
4346     unsigned CurArgOffset;
4347     Align Alignment;
4348     auto ComputeArgOffset = [&]() {
4349       /* Respect alignment of argument on the stack.  */
4350       Alignment =
4351           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4352       ArgOffset = alignTo(ArgOffset, Alignment);
4353       CurArgOffset = ArgOffset;
4354     };
4355 
4356     if (CallConv != CallingConv::Fast) {
4357       ComputeArgOffset();
4358 
4359       /* Compute GPR index associated with argument offset.  */
4360       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4361       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4362     }
4363 
4364     // FIXME the codegen can be much improved in some cases.
4365     // We do not have to keep everything in memory.
4366     if (Flags.isByVal()) {
4367       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4368 
4369       if (CallConv == CallingConv::Fast)
4370         ComputeArgOffset();
4371 
4372       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4373       ObjSize = Flags.getByValSize();
4374       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4375       // Empty aggregate parameters do not take up registers.  Examples:
4376       //   struct { } a;
4377       //   union  { } b;
4378       //   int c[0];
4379       // etc.  However, we have to provide a place-holder in InVals, so
4380       // pretend we have an 8-byte item at the current address for that
4381       // purpose.
4382       if (!ObjSize) {
4383         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4384         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4385         InVals.push_back(FIN);
4386         continue;
4387       }
4388 
4389       // Create a stack object covering all stack doublewords occupied
4390       // by the argument.  If the argument is (fully or partially) on
4391       // the stack, or if the argument is fully in registers but the
4392       // caller has allocated the parameter save anyway, we can refer
4393       // directly to the caller's stack frame.  Otherwise, create a
4394       // local copy in our own frame.
4395       int FI;
4396       if (HasParameterArea ||
4397           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4398         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4399       else
4400         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4401       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4402 
4403       // Handle aggregates smaller than 8 bytes.
4404       if (ObjSize < PtrByteSize) {
4405         // The value of the object is its address, which differs from the
4406         // address of the enclosing doubleword on big-endian systems.
4407         SDValue Arg = FIN;
4408         if (!isLittleEndian) {
4409           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4410           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4411         }
4412         InVals.push_back(Arg);
4413 
4414         if (GPR_idx != Num_GPR_Regs) {
4415           Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4416           FuncInfo->addLiveInAttr(VReg, Flags);
4417           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4418           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4419           SDValue Store =
4420               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4421                                 MachinePointerInfo(&*FuncArg), ObjType);
4422           MemOps.push_back(Store);
4423         }
4424         // Whether we copied from a register or not, advance the offset
4425         // into the parameter save area by a full doubleword.
4426         ArgOffset += PtrByteSize;
4427         continue;
4428       }
4429 
4430       // The value of the object is its address, which is the address of
4431       // its first stack doubleword.
4432       InVals.push_back(FIN);
4433 
4434       // Store whatever pieces of the object are in registers to memory.
4435       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4436         if (GPR_idx == Num_GPR_Regs)
4437           break;
4438 
4439         Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4440         FuncInfo->addLiveInAttr(VReg, Flags);
4441         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4442         SDValue Addr = FIN;
4443         if (j) {
4444           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4445           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4446         }
4447         unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4448         EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4449         SDValue Store =
4450             DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4451                               MachinePointerInfo(&*FuncArg, j), ObjType);
4452         MemOps.push_back(Store);
4453         ++GPR_idx;
4454       }
4455       ArgOffset += ArgSize;
4456       continue;
4457     }
4458 
4459     switch (ObjectVT.getSimpleVT().SimpleTy) {
4460     default: llvm_unreachable("Unhandled argument type!");
4461     case MVT::i1:
4462     case MVT::i32:
4463     case MVT::i64:
4464       if (Flags.isNest()) {
4465         // The 'nest' parameter, if any, is passed in R11.
4466         Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4467         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4468 
4469         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4470           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4471 
4472         break;
4473       }
4474 
4475       // These can be scalar arguments or elements of an integer array type
4476       // passed directly.  Clang may use those instead of "byval" aggregate
4477       // types to avoid forcing arguments to memory unnecessarily.
4478       if (GPR_idx != Num_GPR_Regs) {
4479         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4480         FuncInfo->addLiveInAttr(VReg, Flags);
4481         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4482 
4483         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4484           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4485           // value to MVT::i64 and then truncate to the correct register size.
4486           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4487       } else {
4488         if (CallConv == CallingConv::Fast)
4489           ComputeArgOffset();
4490 
4491         needsLoad = true;
4492         ArgSize = PtrByteSize;
4493       }
4494       if (CallConv != CallingConv::Fast || needsLoad)
4495         ArgOffset += 8;
4496       break;
4497 
4498     case MVT::f32:
4499     case MVT::f64:
4500       // These can be scalar arguments or elements of a float array type
4501       // passed directly.  The latter are used to implement ELFv2 homogenous
4502       // float aggregates.
4503       if (FPR_idx != Num_FPR_Regs) {
4504         unsigned VReg;
4505 
4506         if (ObjectVT == MVT::f32)
4507           VReg = MF.addLiveIn(FPR[FPR_idx],
4508                               Subtarget.hasP8Vector()
4509                                   ? &PPC::VSSRCRegClass
4510                                   : &PPC::F4RCRegClass);
4511         else
4512           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4513                                                 ? &PPC::VSFRCRegClass
4514                                                 : &PPC::F8RCRegClass);
4515 
4516         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4517         ++FPR_idx;
4518       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4519         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4520         // once we support fp <-> gpr moves.
4521 
4522         // This can only ever happen in the presence of f32 array types,
4523         // since otherwise we never run out of FPRs before running out
4524         // of GPRs.
4525         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4526         FuncInfo->addLiveInAttr(VReg, Flags);
4527         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4528 
4529         if (ObjectVT == MVT::f32) {
4530           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4531             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4532                                  DAG.getConstant(32, dl, MVT::i32));
4533           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4534         }
4535 
4536         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4537       } else {
4538         if (CallConv == CallingConv::Fast)
4539           ComputeArgOffset();
4540 
4541         needsLoad = true;
4542       }
4543 
4544       // When passing an array of floats, the array occupies consecutive
4545       // space in the argument area; only round up to the next doubleword
4546       // at the end of the array.  Otherwise, each float takes 8 bytes.
4547       if (CallConv != CallingConv::Fast || needsLoad) {
4548         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4549         ArgOffset += ArgSize;
4550         if (Flags.isInConsecutiveRegsLast())
4551           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4552       }
4553       break;
4554     case MVT::v4f32:
4555     case MVT::v4i32:
4556     case MVT::v8i16:
4557     case MVT::v16i8:
4558     case MVT::v2f64:
4559     case MVT::v2i64:
4560     case MVT::v1i128:
4561     case MVT::f128:
4562       // These can be scalar arguments or elements of a vector array type
4563       // passed directly.  The latter are used to implement ELFv2 homogenous
4564       // vector aggregates.
4565       if (VR_idx != Num_VR_Regs) {
4566         Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4567         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4568         ++VR_idx;
4569       } else {
4570         if (CallConv == CallingConv::Fast)
4571           ComputeArgOffset();
4572         needsLoad = true;
4573       }
4574       if (CallConv != CallingConv::Fast || needsLoad)
4575         ArgOffset += 16;
4576       break;
4577     }
4578 
4579     // We need to load the argument to a virtual register if we determined
4580     // above that we ran out of physical registers of the appropriate type.
4581     if (needsLoad) {
4582       if (ObjSize < ArgSize && !isLittleEndian)
4583         CurArgOffset += ArgSize - ObjSize;
4584       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4585       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4586       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4587     }
4588 
4589     InVals.push_back(ArgVal);
4590   }
4591 
4592   // Area that is at least reserved in the caller of this function.
4593   unsigned MinReservedArea;
4594   if (HasParameterArea)
4595     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4596   else
4597     MinReservedArea = LinkageSize;
4598 
4599   // Set the size that is at least reserved in caller of this function.  Tail
4600   // call optimized functions' reserved stack space needs to be aligned so that
4601   // taking the difference between two stack areas will result in an aligned
4602   // stack.
4603   MinReservedArea =
4604       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4605   FuncInfo->setMinReservedArea(MinReservedArea);
4606 
4607   // If the function takes variable number of arguments, make a frame index for
4608   // the start of the first vararg value... for expansion of llvm.va_start.
4609   // On ELFv2ABI spec, it writes:
4610   // C programs that are intended to be *portable* across different compilers
4611   // and architectures must use the header file <stdarg.h> to deal with variable
4612   // argument lists.
4613   if (isVarArg && MFI.hasVAStart()) {
4614     int Depth = ArgOffset;
4615 
4616     FuncInfo->setVarArgsFrameIndex(
4617       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4618     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4619 
4620     // If this function is vararg, store any remaining integer argument regs
4621     // to their spots on the stack so that they may be loaded by dereferencing
4622     // the result of va_next.
4623     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4624          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4625       Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4626       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4627       SDValue Store =
4628           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4629       MemOps.push_back(Store);
4630       // Increment the address by four for the next argument to store
4631       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4632       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4633     }
4634   }
4635 
4636   if (!MemOps.empty())
4637     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4638 
4639   return Chain;
4640 }
4641 
4642 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4643 /// adjusted to accommodate the arguments for the tailcall.
4644 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4645                                    unsigned ParamSize) {
4646 
4647   if (!isTailCall) return 0;
4648 
4649   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4650   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4651   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4652   // Remember only if the new adjustment is bigger.
4653   if (SPDiff < FI->getTailCallSPDelta())
4654     FI->setTailCallSPDelta(SPDiff);
4655 
4656   return SPDiff;
4657 }
4658 
4659 static bool isFunctionGlobalAddress(SDValue Callee);
4660 
4661 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4662                               const TargetMachine &TM) {
4663   // It does not make sense to call callsShareTOCBase() with a caller that
4664   // is PC Relative since PC Relative callers do not have a TOC.
4665 #ifndef NDEBUG
4666   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4667   assert(!STICaller->isUsingPCRelativeCalls() &&
4668          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4669 #endif
4670 
4671   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4672   // don't have enough information to determine if the caller and callee share
4673   // the same  TOC base, so we have to pessimistically assume they don't for
4674   // correctness.
4675   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4676   if (!G)
4677     return false;
4678 
4679   const GlobalValue *GV = G->getGlobal();
4680 
4681   // If the callee is preemptable, then the static linker will use a plt-stub
4682   // which saves the toc to the stack, and needs a nop after the call
4683   // instruction to convert to a toc-restore.
4684   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4685     return false;
4686 
4687   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4688   // We may need a TOC restore in the situation where the caller requires a
4689   // valid TOC but the callee is PC Relative and does not.
4690   const Function *F = dyn_cast<Function>(GV);
4691   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4692 
4693   // If we have an Alias we can try to get the function from there.
4694   if (Alias) {
4695     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4696     F = dyn_cast<Function>(GlobalObj);
4697   }
4698 
4699   // If we still have no valid function pointer we do not have enough
4700   // information to determine if the callee uses PC Relative calls so we must
4701   // assume that it does.
4702   if (!F)
4703     return false;
4704 
4705   // If the callee uses PC Relative we cannot guarantee that the callee won't
4706   // clobber the TOC of the caller and so we must assume that the two
4707   // functions do not share a TOC base.
4708   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4709   if (STICallee->isUsingPCRelativeCalls())
4710     return false;
4711 
4712   // If the GV is not a strong definition then we need to assume it can be
4713   // replaced by another function at link time. The function that replaces
4714   // it may not share the same TOC as the caller since the callee may be
4715   // replaced by a PC Relative version of the same function.
4716   if (!GV->isStrongDefinitionForLinker())
4717     return false;
4718 
4719   // The medium and large code models are expected to provide a sufficiently
4720   // large TOC to provide all data addressing needs of a module with a
4721   // single TOC.
4722   if (CodeModel::Medium == TM.getCodeModel() ||
4723       CodeModel::Large == TM.getCodeModel())
4724     return true;
4725 
4726   // Any explicitly-specified sections and section prefixes must also match.
4727   // Also, if we're using -ffunction-sections, then each function is always in
4728   // a different section (the same is true for COMDAT functions).
4729   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4730       GV->getSection() != Caller->getSection())
4731     return false;
4732   if (const auto *F = dyn_cast<Function>(GV)) {
4733     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4734       return false;
4735   }
4736 
4737   return true;
4738 }
4739 
4740 static bool
4741 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4742                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4743   assert(Subtarget.is64BitELFABI());
4744 
4745   const unsigned PtrByteSize = 8;
4746   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4747 
4748   static const MCPhysReg GPR[] = {
4749     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4750     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4751   };
4752   static const MCPhysReg VR[] = {
4753     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4754     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4755   };
4756 
4757   const unsigned NumGPRs = array_lengthof(GPR);
4758   const unsigned NumFPRs = 13;
4759   const unsigned NumVRs = array_lengthof(VR);
4760   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4761 
4762   unsigned NumBytes = LinkageSize;
4763   unsigned AvailableFPRs = NumFPRs;
4764   unsigned AvailableVRs = NumVRs;
4765 
4766   for (const ISD::OutputArg& Param : Outs) {
4767     if (Param.Flags.isNest()) continue;
4768 
4769     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4770                                LinkageSize, ParamAreaSize, NumBytes,
4771                                AvailableFPRs, AvailableVRs))
4772       return true;
4773   }
4774   return false;
4775 }
4776 
4777 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4778   if (CB.arg_size() != CallerFn->arg_size())
4779     return false;
4780 
4781   auto CalleeArgIter = CB.arg_begin();
4782   auto CalleeArgEnd = CB.arg_end();
4783   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4784 
4785   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4786     const Value* CalleeArg = *CalleeArgIter;
4787     const Value* CallerArg = &(*CallerArgIter);
4788     if (CalleeArg == CallerArg)
4789       continue;
4790 
4791     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4792     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4793     //      }
4794     // 1st argument of callee is undef and has the same type as caller.
4795     if (CalleeArg->getType() == CallerArg->getType() &&
4796         isa<UndefValue>(CalleeArg))
4797       continue;
4798 
4799     return false;
4800   }
4801 
4802   return true;
4803 }
4804 
4805 // Returns true if TCO is possible between the callers and callees
4806 // calling conventions.
4807 static bool
4808 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4809                                     CallingConv::ID CalleeCC) {
4810   // Tail calls are possible with fastcc and ccc.
4811   auto isTailCallableCC  = [] (CallingConv::ID CC){
4812       return  CC == CallingConv::C || CC == CallingConv::Fast;
4813   };
4814   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4815     return false;
4816 
4817   // We can safely tail call both fastcc and ccc callees from a c calling
4818   // convention caller. If the caller is fastcc, we may have less stack space
4819   // than a non-fastcc caller with the same signature so disable tail-calls in
4820   // that case.
4821   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4822 }
4823 
4824 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4825     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4826     const SmallVectorImpl<ISD::OutputArg> &Outs,
4827     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4828   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4829 
4830   if (DisableSCO && !TailCallOpt) return false;
4831 
4832   // Variadic argument functions are not supported.
4833   if (isVarArg) return false;
4834 
4835   auto &Caller = DAG.getMachineFunction().getFunction();
4836   // Check that the calling conventions are compatible for tco.
4837   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4838     return false;
4839 
4840   // Caller contains any byval parameter is not supported.
4841   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4842     return false;
4843 
4844   // Callee contains any byval parameter is not supported, too.
4845   // Note: This is a quick work around, because in some cases, e.g.
4846   // caller's stack size > callee's stack size, we are still able to apply
4847   // sibling call optimization. For example, gcc is able to do SCO for caller1
4848   // in the following example, but not for caller2.
4849   //   struct test {
4850   //     long int a;
4851   //     char ary[56];
4852   //   } gTest;
4853   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4854   //     b->a = v.a;
4855   //     return 0;
4856   //   }
4857   //   void caller1(struct test a, struct test c, struct test *b) {
4858   //     callee(gTest, b); }
4859   //   void caller2(struct test *b) { callee(gTest, b); }
4860   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4861     return false;
4862 
4863   // If callee and caller use different calling conventions, we cannot pass
4864   // parameters on stack since offsets for the parameter area may be different.
4865   if (Caller.getCallingConv() != CalleeCC &&
4866       needStackSlotPassParameters(Subtarget, Outs))
4867     return false;
4868 
4869   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4870   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4871   // callee potentially have different TOC bases then we cannot tail call since
4872   // we need to restore the TOC pointer after the call.
4873   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4874   // We cannot guarantee this for indirect calls or calls to external functions.
4875   // When PC-Relative addressing is used, the concept of the TOC is no longer
4876   // applicable so this check is not required.
4877   // Check first for indirect calls.
4878   if (!Subtarget.isUsingPCRelativeCalls() &&
4879       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4880     return false;
4881 
4882   // Check if we share the TOC base.
4883   if (!Subtarget.isUsingPCRelativeCalls() &&
4884       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4885     return false;
4886 
4887   // TCO allows altering callee ABI, so we don't have to check further.
4888   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4889     return true;
4890 
4891   if (DisableSCO) return false;
4892 
4893   // If callee use the same argument list that caller is using, then we can
4894   // apply SCO on this case. If it is not, then we need to check if callee needs
4895   // stack for passing arguments.
4896   // PC Relative tail calls may not have a CallBase.
4897   // If there is no CallBase we cannot verify if we have the same argument
4898   // list so assume that we don't have the same argument list.
4899   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4900       needStackSlotPassParameters(Subtarget, Outs))
4901     return false;
4902   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4903     return false;
4904 
4905   return true;
4906 }
4907 
4908 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4909 /// for tail call optimization. Targets which want to do tail call
4910 /// optimization should implement this function.
4911 bool
4912 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4913                                                      CallingConv::ID CalleeCC,
4914                                                      bool isVarArg,
4915                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4916                                                      SelectionDAG& DAG) const {
4917   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4918     return false;
4919 
4920   // Variable argument functions are not supported.
4921   if (isVarArg)
4922     return false;
4923 
4924   MachineFunction &MF = DAG.getMachineFunction();
4925   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4926   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4927     // Functions containing by val parameters are not supported.
4928     for (unsigned i = 0; i != Ins.size(); i++) {
4929        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4930        if (Flags.isByVal()) return false;
4931     }
4932 
4933     // Non-PIC/GOT tail calls are supported.
4934     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4935       return true;
4936 
4937     // At the moment we can only do local tail calls (in same module, hidden
4938     // or protected) if we are generating PIC.
4939     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4940       return G->getGlobal()->hasHiddenVisibility()
4941           || G->getGlobal()->hasProtectedVisibility();
4942   }
4943 
4944   return false;
4945 }
4946 
4947 /// isCallCompatibleAddress - Return the immediate to use if the specified
4948 /// 32-bit value is representable in the immediate field of a BxA instruction.
4949 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4950   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4951   if (!C) return nullptr;
4952 
4953   int Addr = C->getZExtValue();
4954   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4955       SignExtend32<26>(Addr) != Addr)
4956     return nullptr;  // Top 6 bits have to be sext of immediate.
4957 
4958   return DAG
4959       .getConstant(
4960           (int)C->getZExtValue() >> 2, SDLoc(Op),
4961           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4962       .getNode();
4963 }
4964 
4965 namespace {
4966 
4967 struct TailCallArgumentInfo {
4968   SDValue Arg;
4969   SDValue FrameIdxOp;
4970   int FrameIdx = 0;
4971 
4972   TailCallArgumentInfo() = default;
4973 };
4974 
4975 } // end anonymous namespace
4976 
4977 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4978 static void StoreTailCallArgumentsToStackSlot(
4979     SelectionDAG &DAG, SDValue Chain,
4980     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4981     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4982   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4983     SDValue Arg = TailCallArgs[i].Arg;
4984     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4985     int FI = TailCallArgs[i].FrameIdx;
4986     // Store relative to framepointer.
4987     MemOpChains.push_back(DAG.getStore(
4988         Chain, dl, Arg, FIN,
4989         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4990   }
4991 }
4992 
4993 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4994 /// the appropriate stack slot for the tail call optimized function call.
4995 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4996                                              SDValue OldRetAddr, SDValue OldFP,
4997                                              int SPDiff, const SDLoc &dl) {
4998   if (SPDiff) {
4999     // Calculate the new stack slot for the return address.
5000     MachineFunction &MF = DAG.getMachineFunction();
5001     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5002     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5003     bool isPPC64 = Subtarget.isPPC64();
5004     int SlotSize = isPPC64 ? 8 : 4;
5005     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5006     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5007                                                          NewRetAddrLoc, true);
5008     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5009     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5010     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5011                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5012   }
5013   return Chain;
5014 }
5015 
5016 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5017 /// the position of the argument.
5018 static void
5019 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5020                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5021                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5022   int Offset = ArgOffset + SPDiff;
5023   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5024   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5025   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5026   SDValue FIN = DAG.getFrameIndex(FI, VT);
5027   TailCallArgumentInfo Info;
5028   Info.Arg = Arg;
5029   Info.FrameIdxOp = FIN;
5030   Info.FrameIdx = FI;
5031   TailCallArguments.push_back(Info);
5032 }
5033 
5034 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5035 /// stack slot. Returns the chain as result and the loaded frame pointers in
5036 /// LROpOut/FPOpout. Used when tail calling.
5037 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5038     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5039     SDValue &FPOpOut, const SDLoc &dl) const {
5040   if (SPDiff) {
5041     // Load the LR and FP stack slot for later adjusting.
5042     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5043     LROpOut = getReturnAddrFrameIndex(DAG);
5044     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5045     Chain = SDValue(LROpOut.getNode(), 1);
5046   }
5047   return Chain;
5048 }
5049 
5050 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5051 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5052 /// specified by the specific parameter attribute. The copy will be passed as
5053 /// a byval function parameter.
5054 /// Sometimes what we are copying is the end of a larger object, the part that
5055 /// does not fit in registers.
5056 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5057                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5058                                          SelectionDAG &DAG, const SDLoc &dl) {
5059   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5060   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5061                        Flags.getNonZeroByValAlign(), false, false, false,
5062                        MachinePointerInfo(), MachinePointerInfo());
5063 }
5064 
5065 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5066 /// tail calls.
5067 static void LowerMemOpCallTo(
5068     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5069     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5070     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5071     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5072   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5073   if (!isTailCall) {
5074     if (isVector) {
5075       SDValue StackPtr;
5076       if (isPPC64)
5077         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5078       else
5079         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5080       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5081                            DAG.getConstant(ArgOffset, dl, PtrVT));
5082     }
5083     MemOpChains.push_back(
5084         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5085     // Calculate and remember argument location.
5086   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5087                                   TailCallArguments);
5088 }
5089 
5090 static void
5091 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5092                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5093                 SDValue FPOp,
5094                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5095   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5096   // might overwrite each other in case of tail call optimization.
5097   SmallVector<SDValue, 8> MemOpChains2;
5098   // Do not flag preceding copytoreg stuff together with the following stuff.
5099   InFlag = SDValue();
5100   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5101                                     MemOpChains2, dl);
5102   if (!MemOpChains2.empty())
5103     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5104 
5105   // Store the return address to the appropriate stack slot.
5106   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5107 
5108   // Emit callseq_end just before tailcall node.
5109   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5110                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5111   InFlag = Chain.getValue(1);
5112 }
5113 
5114 // Is this global address that of a function that can be called by name? (as
5115 // opposed to something that must hold a descriptor for an indirect call).
5116 static bool isFunctionGlobalAddress(SDValue Callee) {
5117   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5118     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5119         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5120       return false;
5121 
5122     return G->getGlobal()->getValueType()->isFunctionTy();
5123   }
5124 
5125   return false;
5126 }
5127 
5128 SDValue PPCTargetLowering::LowerCallResult(
5129     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5130     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5131     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5132   SmallVector<CCValAssign, 16> RVLocs;
5133   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5134                     *DAG.getContext());
5135 
5136   CCRetInfo.AnalyzeCallResult(
5137       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5138                ? RetCC_PPC_Cold
5139                : RetCC_PPC);
5140 
5141   // Copy all of the result registers out of their specified physreg.
5142   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5143     CCValAssign &VA = RVLocs[i];
5144     assert(VA.isRegLoc() && "Can only return in registers!");
5145 
5146     SDValue Val;
5147 
5148     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5149       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5150                                       InFlag);
5151       Chain = Lo.getValue(1);
5152       InFlag = Lo.getValue(2);
5153       VA = RVLocs[++i]; // skip ahead to next loc
5154       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5155                                       InFlag);
5156       Chain = Hi.getValue(1);
5157       InFlag = Hi.getValue(2);
5158       if (!Subtarget.isLittleEndian())
5159         std::swap (Lo, Hi);
5160       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5161     } else {
5162       Val = DAG.getCopyFromReg(Chain, dl,
5163                                VA.getLocReg(), VA.getLocVT(), InFlag);
5164       Chain = Val.getValue(1);
5165       InFlag = Val.getValue(2);
5166     }
5167 
5168     switch (VA.getLocInfo()) {
5169     default: llvm_unreachable("Unknown loc info!");
5170     case CCValAssign::Full: break;
5171     case CCValAssign::AExt:
5172       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5173       break;
5174     case CCValAssign::ZExt:
5175       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5176                         DAG.getValueType(VA.getValVT()));
5177       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5178       break;
5179     case CCValAssign::SExt:
5180       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5181                         DAG.getValueType(VA.getValVT()));
5182       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5183       break;
5184     }
5185 
5186     InVals.push_back(Val);
5187   }
5188 
5189   return Chain;
5190 }
5191 
5192 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5193                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5194   // PatchPoint calls are not indirect.
5195   if (isPatchPoint)
5196     return false;
5197 
5198   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5199     return false;
5200 
5201   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5202   // becuase the immediate function pointer points to a descriptor instead of
5203   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5204   // pointer immediate points to the global entry point, while the BLA would
5205   // need to jump to the local entry point (see rL211174).
5206   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5207       isBLACompatibleAddress(Callee, DAG))
5208     return false;
5209 
5210   return true;
5211 }
5212 
5213 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5214 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5215   return Subtarget.isAIXABI() ||
5216          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5217 }
5218 
5219 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5220                               const Function &Caller, const SDValue &Callee,
5221                               const PPCSubtarget &Subtarget,
5222                               const TargetMachine &TM,
5223                               bool IsStrictFPCall = false) {
5224   if (CFlags.IsTailCall)
5225     return PPCISD::TC_RETURN;
5226 
5227   unsigned RetOpc = 0;
5228   // This is a call through a function pointer.
5229   if (CFlags.IsIndirect) {
5230     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5231     // indirect calls. The save of the caller's TOC pointer to the stack will be
5232     // inserted into the DAG as part of call lowering. The restore of the TOC
5233     // pointer is modeled by using a pseudo instruction for the call opcode that
5234     // represents the 2 instruction sequence of an indirect branch and link,
5235     // immediately followed by a load of the TOC pointer from the the stack save
5236     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5237     // as it is not saved or used.
5238     RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5239                                                  : PPCISD::BCTRL;
5240   } else if (Subtarget.isUsingPCRelativeCalls()) {
5241     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5242     RetOpc = PPCISD::CALL_NOTOC;
5243   } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5244     // The ABIs that maintain a TOC pointer accross calls need to have a nop
5245     // immediately following the call instruction if the caller and callee may
5246     // have different TOC bases. At link time if the linker determines the calls
5247     // may not share a TOC base, the call is redirected to a trampoline inserted
5248     // by the linker. The trampoline will (among other things) save the callers
5249     // TOC pointer at an ABI designated offset in the linkage area and the
5250     // linker will rewrite the nop to be a load of the TOC pointer from the
5251     // linkage area into gpr2.
5252     RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5253                                                     : PPCISD::CALL_NOP;
5254   else
5255     RetOpc = PPCISD::CALL;
5256   if (IsStrictFPCall) {
5257     switch (RetOpc) {
5258     default:
5259       llvm_unreachable("Unknown call opcode");
5260     case PPCISD::BCTRL_LOAD_TOC:
5261       RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5262       break;
5263     case PPCISD::BCTRL:
5264       RetOpc = PPCISD::BCTRL_RM;
5265       break;
5266     case PPCISD::CALL_NOTOC:
5267       RetOpc = PPCISD::CALL_NOTOC_RM;
5268       break;
5269     case PPCISD::CALL:
5270       RetOpc = PPCISD::CALL_RM;
5271       break;
5272     case PPCISD::CALL_NOP:
5273       RetOpc = PPCISD::CALL_NOP_RM;
5274       break;
5275     }
5276   }
5277   return RetOpc;
5278 }
5279 
5280 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5281                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5282   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5283     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5284       return SDValue(Dest, 0);
5285 
5286   // Returns true if the callee is local, and false otherwise.
5287   auto isLocalCallee = [&]() {
5288     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5289     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5290     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5291 
5292     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5293            !isa_and_nonnull<GlobalIFunc>(GV);
5294   };
5295 
5296   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5297   // a static relocation model causes some versions of GNU LD (2.17.50, at
5298   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5299   // built with secure-PLT.
5300   bool UsePlt =
5301       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5302       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5303 
5304   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5305     const TargetMachine &TM = Subtarget.getTargetMachine();
5306     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5307     MCSymbolXCOFF *S =
5308         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5309 
5310     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5311     return DAG.getMCSymbol(S, PtrVT);
5312   };
5313 
5314   if (isFunctionGlobalAddress(Callee)) {
5315     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5316 
5317     if (Subtarget.isAIXABI()) {
5318       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5319       return getAIXFuncEntryPointSymbolSDNode(GV);
5320     }
5321     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5322                                       UsePlt ? PPCII::MO_PLT : 0);
5323   }
5324 
5325   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5326     const char *SymName = S->getSymbol();
5327     if (Subtarget.isAIXABI()) {
5328       // If there exists a user-declared function whose name is the same as the
5329       // ExternalSymbol's, then we pick up the user-declared version.
5330       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5331       if (const Function *F =
5332               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5333         return getAIXFuncEntryPointSymbolSDNode(F);
5334 
5335       // On AIX, direct function calls reference the symbol for the function's
5336       // entry point, which is named by prepending a "." before the function's
5337       // C-linkage name. A Qualname is returned here because an external
5338       // function entry point is a csect with XTY_ER property.
5339       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5340         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5341         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5342             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5343             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5344         return Sec->getQualNameSymbol();
5345       };
5346 
5347       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5348     }
5349     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5350                                        UsePlt ? PPCII::MO_PLT : 0);
5351   }
5352 
5353   // No transformation needed.
5354   assert(Callee.getNode() && "What no callee?");
5355   return Callee;
5356 }
5357 
5358 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5359   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5360          "Expected a CALLSEQ_STARTSDNode.");
5361 
5362   // The last operand is the chain, except when the node has glue. If the node
5363   // has glue, then the last operand is the glue, and the chain is the second
5364   // last operand.
5365   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5366   if (LastValue.getValueType() != MVT::Glue)
5367     return LastValue;
5368 
5369   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5370 }
5371 
5372 // Creates the node that moves a functions address into the count register
5373 // to prepare for an indirect call instruction.
5374 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5375                                 SDValue &Glue, SDValue &Chain,
5376                                 const SDLoc &dl) {
5377   SDValue MTCTROps[] = {Chain, Callee, Glue};
5378   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5379   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5380                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5381   // The glue is the second value produced.
5382   Glue = Chain.getValue(1);
5383 }
5384 
5385 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5386                                           SDValue &Glue, SDValue &Chain,
5387                                           SDValue CallSeqStart,
5388                                           const CallBase *CB, const SDLoc &dl,
5389                                           bool hasNest,
5390                                           const PPCSubtarget &Subtarget) {
5391   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5392   // entry point, but to the function descriptor (the function entry point
5393   // address is part of the function descriptor though).
5394   // The function descriptor is a three doubleword structure with the
5395   // following fields: function entry point, TOC base address and
5396   // environment pointer.
5397   // Thus for a call through a function pointer, the following actions need
5398   // to be performed:
5399   //   1. Save the TOC of the caller in the TOC save area of its stack
5400   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5401   //   2. Load the address of the function entry point from the function
5402   //      descriptor.
5403   //   3. Load the TOC of the callee from the function descriptor into r2.
5404   //   4. Load the environment pointer from the function descriptor into
5405   //      r11.
5406   //   5. Branch to the function entry point address.
5407   //   6. On return of the callee, the TOC of the caller needs to be
5408   //      restored (this is done in FinishCall()).
5409   //
5410   // The loads are scheduled at the beginning of the call sequence, and the
5411   // register copies are flagged together to ensure that no other
5412   // operations can be scheduled in between. E.g. without flagging the
5413   // copies together, a TOC access in the caller could be scheduled between
5414   // the assignment of the callee TOC and the branch to the callee, which leads
5415   // to incorrect code.
5416 
5417   // Start by loading the function address from the descriptor.
5418   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5419   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5420                       ? (MachineMemOperand::MODereferenceable |
5421                          MachineMemOperand::MOInvariant)
5422                       : MachineMemOperand::MONone;
5423 
5424   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5425 
5426   // Registers used in building the DAG.
5427   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5428   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5429 
5430   // Offsets of descriptor members.
5431   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5432   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5433 
5434   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5435   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5436 
5437   // One load for the functions entry point address.
5438   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5439                                     Alignment, MMOFlags);
5440 
5441   // One for loading the TOC anchor for the module that contains the called
5442   // function.
5443   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5444   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5445   SDValue TOCPtr =
5446       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5447                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5448 
5449   // One for loading the environment pointer.
5450   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5451   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5452   SDValue LoadEnvPtr =
5453       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5454                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5455 
5456 
5457   // Then copy the newly loaded TOC anchor to the TOC pointer.
5458   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5459   Chain = TOCVal.getValue(0);
5460   Glue = TOCVal.getValue(1);
5461 
5462   // If the function call has an explicit 'nest' parameter, it takes the
5463   // place of the environment pointer.
5464   assert((!hasNest || !Subtarget.isAIXABI()) &&
5465          "Nest parameter is not supported on AIX.");
5466   if (!hasNest) {
5467     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5468     Chain = EnvVal.getValue(0);
5469     Glue = EnvVal.getValue(1);
5470   }
5471 
5472   // The rest of the indirect call sequence is the same as the non-descriptor
5473   // DAG.
5474   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5475 }
5476 
5477 static void
5478 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5479                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5480                   SelectionDAG &DAG,
5481                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5482                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5483                   const PPCSubtarget &Subtarget) {
5484   const bool IsPPC64 = Subtarget.isPPC64();
5485   // MVT for a general purpose register.
5486   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5487 
5488   // First operand is always the chain.
5489   Ops.push_back(Chain);
5490 
5491   // If it's a direct call pass the callee as the second operand.
5492   if (!CFlags.IsIndirect)
5493     Ops.push_back(Callee);
5494   else {
5495     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5496 
5497     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5498     // on the stack (this would have been done in `LowerCall_64SVR4` or
5499     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5500     // represents both the indirect branch and a load that restores the TOC
5501     // pointer from the linkage area. The operand for the TOC restore is an add
5502     // of the TOC save offset to the stack pointer. This must be the second
5503     // operand: after the chain input but before any other variadic arguments.
5504     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5505     // saved or used.
5506     if (isTOCSaveRestoreRequired(Subtarget)) {
5507       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5508 
5509       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5510       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5511       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5512       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5513       Ops.push_back(AddTOC);
5514     }
5515 
5516     // Add the register used for the environment pointer.
5517     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5518       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5519                                     RegVT));
5520 
5521 
5522     // Add CTR register as callee so a bctr can be emitted later.
5523     if (CFlags.IsTailCall)
5524       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5525   }
5526 
5527   // If this is a tail call add stack pointer delta.
5528   if (CFlags.IsTailCall)
5529     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5530 
5531   // Add argument registers to the end of the list so that they are known live
5532   // into the call.
5533   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5534     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5535                                   RegsToPass[i].second.getValueType()));
5536 
5537   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5538   // no way to mark dependencies as implicit here.
5539   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5540   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5541        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5542     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5543 
5544   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5545   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5546     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5547 
5548   // Add a register mask operand representing the call-preserved registers.
5549   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5550   const uint32_t *Mask =
5551       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5552   assert(Mask && "Missing call preserved mask for calling convention");
5553   Ops.push_back(DAG.getRegisterMask(Mask));
5554 
5555   // If the glue is valid, it is the last operand.
5556   if (Glue.getNode())
5557     Ops.push_back(Glue);
5558 }
5559 
5560 SDValue PPCTargetLowering::FinishCall(
5561     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5562     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5563     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5564     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5565     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5566 
5567   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5568       Subtarget.isAIXABI())
5569     setUsesTOCBasePtr(DAG);
5570 
5571   unsigned CallOpc =
5572       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5573                     Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5574 
5575   if (!CFlags.IsIndirect)
5576     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5577   else if (Subtarget.usesFunctionDescriptors())
5578     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5579                                   dl, CFlags.HasNest, Subtarget);
5580   else
5581     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5582 
5583   // Build the operand list for the call instruction.
5584   SmallVector<SDValue, 8> Ops;
5585   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5586                     SPDiff, Subtarget);
5587 
5588   // Emit tail call.
5589   if (CFlags.IsTailCall) {
5590     // Indirect tail call when using PC Relative calls do not have the same
5591     // constraints.
5592     assert(((Callee.getOpcode() == ISD::Register &&
5593              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5594             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5595             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5596             isa<ConstantSDNode>(Callee) ||
5597             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5598            "Expecting a global address, external symbol, absolute value, "
5599            "register or an indirect tail call when PC Relative calls are "
5600            "used.");
5601     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5602     assert(CallOpc == PPCISD::TC_RETURN &&
5603            "Unexpected call opcode for a tail call.");
5604     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5605     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5606   }
5607 
5608   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5609   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5610   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5611   Glue = Chain.getValue(1);
5612 
5613   // When performing tail call optimization the callee pops its arguments off
5614   // the stack. Account for this here so these bytes can be pushed back on in
5615   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5616   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5617                          getTargetMachine().Options.GuaranteedTailCallOpt)
5618                             ? NumBytes
5619                             : 0;
5620 
5621   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5622                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5623                              Glue, dl);
5624   Glue = Chain.getValue(1);
5625 
5626   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5627                          DAG, InVals);
5628 }
5629 
5630 SDValue
5631 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5632                              SmallVectorImpl<SDValue> &InVals) const {
5633   SelectionDAG &DAG                     = CLI.DAG;
5634   SDLoc &dl                             = CLI.DL;
5635   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5636   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5637   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5638   SDValue Chain                         = CLI.Chain;
5639   SDValue Callee                        = CLI.Callee;
5640   bool &isTailCall                      = CLI.IsTailCall;
5641   CallingConv::ID CallConv              = CLI.CallConv;
5642   bool isVarArg                         = CLI.IsVarArg;
5643   bool isPatchPoint                     = CLI.IsPatchPoint;
5644   const CallBase *CB                    = CLI.CB;
5645 
5646   if (isTailCall) {
5647     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5648       isTailCall = false;
5649     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5650       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5651           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5652     else
5653       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5654                                                      Ins, DAG);
5655     if (isTailCall) {
5656       ++NumTailCalls;
5657       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5658         ++NumSiblingCalls;
5659 
5660       // PC Relative calls no longer guarantee that the callee is a Global
5661       // Address Node. The callee could be an indirect tail call in which
5662       // case the SDValue for the callee could be a load (to load the address
5663       // of a function pointer) or it may be a register copy (to move the
5664       // address of the callee from a function parameter into a virtual
5665       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5666       assert((Subtarget.isUsingPCRelativeCalls() ||
5667               isa<GlobalAddressSDNode>(Callee)) &&
5668              "Callee should be an llvm::Function object.");
5669 
5670       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5671                         << "\nTCO callee: ");
5672       LLVM_DEBUG(Callee.dump());
5673     }
5674   }
5675 
5676   if (!isTailCall && CB && CB->isMustTailCall())
5677     report_fatal_error("failed to perform tail call elimination on a call "
5678                        "site marked musttail");
5679 
5680   // When long calls (i.e. indirect calls) are always used, calls are always
5681   // made via function pointer. If we have a function name, first translate it
5682   // into a pointer.
5683   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5684       !isTailCall)
5685     Callee = LowerGlobalAddress(Callee, DAG);
5686 
5687   CallFlags CFlags(
5688       CallConv, isTailCall, isVarArg, isPatchPoint,
5689       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5690       // hasNest
5691       Subtarget.is64BitELFABI() &&
5692           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5693       CLI.NoMerge);
5694 
5695   if (Subtarget.isAIXABI())
5696     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5697                          InVals, CB);
5698 
5699   assert(Subtarget.isSVR4ABI());
5700   if (Subtarget.isPPC64())
5701     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5702                             InVals, CB);
5703   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5704                           InVals, CB);
5705 }
5706 
5707 SDValue PPCTargetLowering::LowerCall_32SVR4(
5708     SDValue Chain, SDValue Callee, CallFlags CFlags,
5709     const SmallVectorImpl<ISD::OutputArg> &Outs,
5710     const SmallVectorImpl<SDValue> &OutVals,
5711     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5712     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5713     const CallBase *CB) const {
5714   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5715   // of the 32-bit SVR4 ABI stack frame layout.
5716 
5717   const CallingConv::ID CallConv = CFlags.CallConv;
5718   const bool IsVarArg = CFlags.IsVarArg;
5719   const bool IsTailCall = CFlags.IsTailCall;
5720 
5721   assert((CallConv == CallingConv::C ||
5722           CallConv == CallingConv::Cold ||
5723           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5724 
5725   const Align PtrAlign(4);
5726 
5727   MachineFunction &MF = DAG.getMachineFunction();
5728 
5729   // Mark this function as potentially containing a function that contains a
5730   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5731   // and restoring the callers stack pointer in this functions epilog. This is
5732   // done because by tail calling the called function might overwrite the value
5733   // in this function's (MF) stack pointer stack slot 0(SP).
5734   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5735       CallConv == CallingConv::Fast)
5736     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5737 
5738   // Count how many bytes are to be pushed on the stack, including the linkage
5739   // area, parameter list area and the part of the local variable space which
5740   // contains copies of aggregates which are passed by value.
5741 
5742   // Assign locations to all of the outgoing arguments.
5743   SmallVector<CCValAssign, 16> ArgLocs;
5744   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5745 
5746   // Reserve space for the linkage area on the stack.
5747   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5748                        PtrAlign);
5749   if (useSoftFloat())
5750     CCInfo.PreAnalyzeCallOperands(Outs);
5751 
5752   if (IsVarArg) {
5753     // Handle fixed and variable vector arguments differently.
5754     // Fixed vector arguments go into registers as long as registers are
5755     // available. Variable vector arguments always go into memory.
5756     unsigned NumArgs = Outs.size();
5757 
5758     for (unsigned i = 0; i != NumArgs; ++i) {
5759       MVT ArgVT = Outs[i].VT;
5760       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5761       bool Result;
5762 
5763       if (Outs[i].IsFixed) {
5764         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5765                                CCInfo);
5766       } else {
5767         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5768                                       ArgFlags, CCInfo);
5769       }
5770 
5771       if (Result) {
5772 #ifndef NDEBUG
5773         errs() << "Call operand #" << i << " has unhandled type "
5774              << EVT(ArgVT).getEVTString() << "\n";
5775 #endif
5776         llvm_unreachable(nullptr);
5777       }
5778     }
5779   } else {
5780     // All arguments are treated the same.
5781     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5782   }
5783   CCInfo.clearWasPPCF128();
5784 
5785   // Assign locations to all of the outgoing aggregate by value arguments.
5786   SmallVector<CCValAssign, 16> ByValArgLocs;
5787   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5788 
5789   // Reserve stack space for the allocations in CCInfo.
5790   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5791 
5792   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5793 
5794   // Size of the linkage area, parameter list area and the part of the local
5795   // space variable where copies of aggregates which are passed by value are
5796   // stored.
5797   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5798 
5799   // Calculate by how many bytes the stack has to be adjusted in case of tail
5800   // call optimization.
5801   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5802 
5803   // Adjust the stack pointer for the new arguments...
5804   // These operations are automatically eliminated by the prolog/epilog pass
5805   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5806   SDValue CallSeqStart = Chain;
5807 
5808   // Load the return address and frame pointer so it can be moved somewhere else
5809   // later.
5810   SDValue LROp, FPOp;
5811   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5812 
5813   // Set up a copy of the stack pointer for use loading and storing any
5814   // arguments that may not fit in the registers available for argument
5815   // passing.
5816   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5817 
5818   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5819   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5820   SmallVector<SDValue, 8> MemOpChains;
5821 
5822   bool seenFloatArg = false;
5823   // Walk the register/memloc assignments, inserting copies/loads.
5824   // i - Tracks the index into the list of registers allocated for the call
5825   // RealArgIdx - Tracks the index into the list of actual function arguments
5826   // j - Tracks the index into the list of byval arguments
5827   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5828        i != e;
5829        ++i, ++RealArgIdx) {
5830     CCValAssign &VA = ArgLocs[i];
5831     SDValue Arg = OutVals[RealArgIdx];
5832     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5833 
5834     if (Flags.isByVal()) {
5835       // Argument is an aggregate which is passed by value, thus we need to
5836       // create a copy of it in the local variable space of the current stack
5837       // frame (which is the stack frame of the caller) and pass the address of
5838       // this copy to the callee.
5839       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5840       CCValAssign &ByValVA = ByValArgLocs[j++];
5841       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5842 
5843       // Memory reserved in the local variable space of the callers stack frame.
5844       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5845 
5846       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5847       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5848                            StackPtr, PtrOff);
5849 
5850       // Create a copy of the argument in the local area of the current
5851       // stack frame.
5852       SDValue MemcpyCall =
5853         CreateCopyOfByValArgument(Arg, PtrOff,
5854                                   CallSeqStart.getNode()->getOperand(0),
5855                                   Flags, DAG, dl);
5856 
5857       // This must go outside the CALLSEQ_START..END.
5858       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5859                                                      SDLoc(MemcpyCall));
5860       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5861                              NewCallSeqStart.getNode());
5862       Chain = CallSeqStart = NewCallSeqStart;
5863 
5864       // Pass the address of the aggregate copy on the stack either in a
5865       // physical register or in the parameter list area of the current stack
5866       // frame to the callee.
5867       Arg = PtrOff;
5868     }
5869 
5870     // When useCRBits() is true, there can be i1 arguments.
5871     // It is because getRegisterType(MVT::i1) => MVT::i1,
5872     // and for other integer types getRegisterType() => MVT::i32.
5873     // Extend i1 and ensure callee will get i32.
5874     if (Arg.getValueType() == MVT::i1)
5875       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5876                         dl, MVT::i32, Arg);
5877 
5878     if (VA.isRegLoc()) {
5879       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5880       // Put argument in a physical register.
5881       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5882         bool IsLE = Subtarget.isLittleEndian();
5883         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5884                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5885         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5886         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5887                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5888         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5889                              SVal.getValue(0)));
5890       } else
5891         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5892     } else {
5893       // Put argument in the parameter list area of the current stack frame.
5894       assert(VA.isMemLoc());
5895       unsigned LocMemOffset = VA.getLocMemOffset();
5896 
5897       if (!IsTailCall) {
5898         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5899         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5900                              StackPtr, PtrOff);
5901 
5902         MemOpChains.push_back(
5903             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5904       } else {
5905         // Calculate and remember argument location.
5906         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5907                                  TailCallArguments);
5908       }
5909     }
5910   }
5911 
5912   if (!MemOpChains.empty())
5913     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5914 
5915   // Build a sequence of copy-to-reg nodes chained together with token chain
5916   // and flag operands which copy the outgoing args into the appropriate regs.
5917   SDValue InFlag;
5918   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5919     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5920                              RegsToPass[i].second, InFlag);
5921     InFlag = Chain.getValue(1);
5922   }
5923 
5924   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5925   // registers.
5926   if (IsVarArg) {
5927     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5928     SDValue Ops[] = { Chain, InFlag };
5929 
5930     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5931                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5932 
5933     InFlag = Chain.getValue(1);
5934   }
5935 
5936   if (IsTailCall)
5937     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5938                     TailCallArguments);
5939 
5940   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5941                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5942 }
5943 
5944 // Copy an argument into memory, being careful to do this outside the
5945 // call sequence for the call to which the argument belongs.
5946 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5947     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5948     SelectionDAG &DAG, const SDLoc &dl) const {
5949   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5950                         CallSeqStart.getNode()->getOperand(0),
5951                         Flags, DAG, dl);
5952   // The MEMCPY must go outside the CALLSEQ_START..END.
5953   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5954   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5955                                                  SDLoc(MemcpyCall));
5956   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5957                          NewCallSeqStart.getNode());
5958   return NewCallSeqStart;
5959 }
5960 
5961 SDValue PPCTargetLowering::LowerCall_64SVR4(
5962     SDValue Chain, SDValue Callee, CallFlags CFlags,
5963     const SmallVectorImpl<ISD::OutputArg> &Outs,
5964     const SmallVectorImpl<SDValue> &OutVals,
5965     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5966     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5967     const CallBase *CB) const {
5968   bool isELFv2ABI = Subtarget.isELFv2ABI();
5969   bool isLittleEndian = Subtarget.isLittleEndian();
5970   unsigned NumOps = Outs.size();
5971   bool IsSibCall = false;
5972   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5973 
5974   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5975   unsigned PtrByteSize = 8;
5976 
5977   MachineFunction &MF = DAG.getMachineFunction();
5978 
5979   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5980     IsSibCall = true;
5981 
5982   // Mark this function as potentially containing a function that contains a
5983   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5984   // and restoring the callers stack pointer in this functions epilog. This is
5985   // done because by tail calling the called function might overwrite the value
5986   // in this function's (MF) stack pointer stack slot 0(SP).
5987   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5988     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5989 
5990   assert(!(IsFastCall && CFlags.IsVarArg) &&
5991          "fastcc not supported on varargs functions");
5992 
5993   // Count how many bytes are to be pushed on the stack, including the linkage
5994   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5995   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5996   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5997   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5998   unsigned NumBytes = LinkageSize;
5999   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6000 
6001   static const MCPhysReg GPR[] = {
6002     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6003     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6004   };
6005   static const MCPhysReg VR[] = {
6006     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6007     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6008   };
6009 
6010   const unsigned NumGPRs = array_lengthof(GPR);
6011   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6012   const unsigned NumVRs  = array_lengthof(VR);
6013 
6014   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6015   // can be passed to the callee in registers.
6016   // For the fast calling convention, there is another check below.
6017   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6018   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6019   if (!HasParameterArea) {
6020     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6021     unsigned AvailableFPRs = NumFPRs;
6022     unsigned AvailableVRs = NumVRs;
6023     unsigned NumBytesTmp = NumBytes;
6024     for (unsigned i = 0; i != NumOps; ++i) {
6025       if (Outs[i].Flags.isNest()) continue;
6026       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6027                                  PtrByteSize, LinkageSize, ParamAreaSize,
6028                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6029         HasParameterArea = true;
6030     }
6031   }
6032 
6033   // When using the fast calling convention, we don't provide backing for
6034   // arguments that will be in registers.
6035   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6036 
6037   // Avoid allocating parameter area for fastcc functions if all the arguments
6038   // can be passed in the registers.
6039   if (IsFastCall)
6040     HasParameterArea = false;
6041 
6042   // Add up all the space actually used.
6043   for (unsigned i = 0; i != NumOps; ++i) {
6044     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6045     EVT ArgVT = Outs[i].VT;
6046     EVT OrigVT = Outs[i].ArgVT;
6047 
6048     if (Flags.isNest())
6049       continue;
6050 
6051     if (IsFastCall) {
6052       if (Flags.isByVal()) {
6053         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6054         if (NumGPRsUsed > NumGPRs)
6055           HasParameterArea = true;
6056       } else {
6057         switch (ArgVT.getSimpleVT().SimpleTy) {
6058         default: llvm_unreachable("Unexpected ValueType for argument!");
6059         case MVT::i1:
6060         case MVT::i32:
6061         case MVT::i64:
6062           if (++NumGPRsUsed <= NumGPRs)
6063             continue;
6064           break;
6065         case MVT::v4i32:
6066         case MVT::v8i16:
6067         case MVT::v16i8:
6068         case MVT::v2f64:
6069         case MVT::v2i64:
6070         case MVT::v1i128:
6071         case MVT::f128:
6072           if (++NumVRsUsed <= NumVRs)
6073             continue;
6074           break;
6075         case MVT::v4f32:
6076           if (++NumVRsUsed <= NumVRs)
6077             continue;
6078           break;
6079         case MVT::f32:
6080         case MVT::f64:
6081           if (++NumFPRsUsed <= NumFPRs)
6082             continue;
6083           break;
6084         }
6085         HasParameterArea = true;
6086       }
6087     }
6088 
6089     /* Respect alignment of argument on the stack.  */
6090     auto Alignement =
6091         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6092     NumBytes = alignTo(NumBytes, Alignement);
6093 
6094     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6095     if (Flags.isInConsecutiveRegsLast())
6096       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6097   }
6098 
6099   unsigned NumBytesActuallyUsed = NumBytes;
6100 
6101   // In the old ELFv1 ABI,
6102   // the prolog code of the callee may store up to 8 GPR argument registers to
6103   // the stack, allowing va_start to index over them in memory if its varargs.
6104   // Because we cannot tell if this is needed on the caller side, we have to
6105   // conservatively assume that it is needed.  As such, make sure we have at
6106   // least enough stack space for the caller to store the 8 GPRs.
6107   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6108   // really requires memory operands, e.g. a vararg function.
6109   if (HasParameterArea)
6110     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6111   else
6112     NumBytes = LinkageSize;
6113 
6114   // Tail call needs the stack to be aligned.
6115   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6116     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6117 
6118   int SPDiff = 0;
6119 
6120   // Calculate by how many bytes the stack has to be adjusted in case of tail
6121   // call optimization.
6122   if (!IsSibCall)
6123     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6124 
6125   // To protect arguments on the stack from being clobbered in a tail call,
6126   // force all the loads to happen before doing any other lowering.
6127   if (CFlags.IsTailCall)
6128     Chain = DAG.getStackArgumentTokenFactor(Chain);
6129 
6130   // Adjust the stack pointer for the new arguments...
6131   // These operations are automatically eliminated by the prolog/epilog pass
6132   if (!IsSibCall)
6133     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6134   SDValue CallSeqStart = Chain;
6135 
6136   // Load the return address and frame pointer so it can be move somewhere else
6137   // later.
6138   SDValue LROp, FPOp;
6139   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6140 
6141   // Set up a copy of the stack pointer for use loading and storing any
6142   // arguments that may not fit in the registers available for argument
6143   // passing.
6144   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6145 
6146   // Figure out which arguments are going to go in registers, and which in
6147   // memory.  Also, if this is a vararg function, floating point operations
6148   // must be stored to our stack, and loaded into integer regs as well, if
6149   // any integer regs are available for argument passing.
6150   unsigned ArgOffset = LinkageSize;
6151 
6152   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6153   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6154 
6155   SmallVector<SDValue, 8> MemOpChains;
6156   for (unsigned i = 0; i != NumOps; ++i) {
6157     SDValue Arg = OutVals[i];
6158     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6159     EVT ArgVT = Outs[i].VT;
6160     EVT OrigVT = Outs[i].ArgVT;
6161 
6162     // PtrOff will be used to store the current argument to the stack if a
6163     // register cannot be found for it.
6164     SDValue PtrOff;
6165 
6166     // We re-align the argument offset for each argument, except when using the
6167     // fast calling convention, when we need to make sure we do that only when
6168     // we'll actually use a stack slot.
6169     auto ComputePtrOff = [&]() {
6170       /* Respect alignment of argument on the stack.  */
6171       auto Alignment =
6172           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6173       ArgOffset = alignTo(ArgOffset, Alignment);
6174 
6175       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6176 
6177       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6178     };
6179 
6180     if (!IsFastCall) {
6181       ComputePtrOff();
6182 
6183       /* Compute GPR index associated with argument offset.  */
6184       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6185       GPR_idx = std::min(GPR_idx, NumGPRs);
6186     }
6187 
6188     // Promote integers to 64-bit values.
6189     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6190       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6191       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6192       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6193     }
6194 
6195     // FIXME memcpy is used way more than necessary.  Correctness first.
6196     // Note: "by value" is code for passing a structure by value, not
6197     // basic types.
6198     if (Flags.isByVal()) {
6199       // Note: Size includes alignment padding, so
6200       //   struct x { short a; char b; }
6201       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6202       // These are the proper values we need for right-justifying the
6203       // aggregate in a parameter register.
6204       unsigned Size = Flags.getByValSize();
6205 
6206       // An empty aggregate parameter takes up no storage and no
6207       // registers.
6208       if (Size == 0)
6209         continue;
6210 
6211       if (IsFastCall)
6212         ComputePtrOff();
6213 
6214       // All aggregates smaller than 8 bytes must be passed right-justified.
6215       if (Size==1 || Size==2 || Size==4) {
6216         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6217         if (GPR_idx != NumGPRs) {
6218           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6219                                         MachinePointerInfo(), VT);
6220           MemOpChains.push_back(Load.getValue(1));
6221           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6222 
6223           ArgOffset += PtrByteSize;
6224           continue;
6225         }
6226       }
6227 
6228       if (GPR_idx == NumGPRs && Size < 8) {
6229         SDValue AddPtr = PtrOff;
6230         if (!isLittleEndian) {
6231           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6232                                           PtrOff.getValueType());
6233           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6234         }
6235         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6236                                                           CallSeqStart,
6237                                                           Flags, DAG, dl);
6238         ArgOffset += PtrByteSize;
6239         continue;
6240       }
6241       // Copy the object to parameter save area if it can not be entirely passed
6242       // by registers.
6243       // FIXME: we only need to copy the parts which need to be passed in
6244       // parameter save area. For the parts passed by registers, we don't need
6245       // to copy them to the stack although we need to allocate space for them
6246       // in parameter save area.
6247       if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6248         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6249                                                           CallSeqStart,
6250                                                           Flags, DAG, dl);
6251 
6252       // When a register is available, pass a small aggregate right-justified.
6253       if (Size < 8 && GPR_idx != NumGPRs) {
6254         // The easiest way to get this right-justified in a register
6255         // is to copy the structure into the rightmost portion of a
6256         // local variable slot, then load the whole slot into the
6257         // register.
6258         // FIXME: The memcpy seems to produce pretty awful code for
6259         // small aggregates, particularly for packed ones.
6260         // FIXME: It would be preferable to use the slot in the
6261         // parameter save area instead of a new local variable.
6262         SDValue AddPtr = PtrOff;
6263         if (!isLittleEndian) {
6264           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6265           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6266         }
6267         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6268                                                           CallSeqStart,
6269                                                           Flags, DAG, dl);
6270 
6271         // Load the slot into the register.
6272         SDValue Load =
6273             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6274         MemOpChains.push_back(Load.getValue(1));
6275         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6276 
6277         // Done with this argument.
6278         ArgOffset += PtrByteSize;
6279         continue;
6280       }
6281 
6282       // For aggregates larger than PtrByteSize, copy the pieces of the
6283       // object that fit into registers from the parameter save area.
6284       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6285         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6286         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6287         if (GPR_idx != NumGPRs) {
6288           unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6289           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6290           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6291                                         MachinePointerInfo(), ObjType);
6292 
6293           MemOpChains.push_back(Load.getValue(1));
6294           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6295           ArgOffset += PtrByteSize;
6296         } else {
6297           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6298           break;
6299         }
6300       }
6301       continue;
6302     }
6303 
6304     switch (Arg.getSimpleValueType().SimpleTy) {
6305     default: llvm_unreachable("Unexpected ValueType for argument!");
6306     case MVT::i1:
6307     case MVT::i32:
6308     case MVT::i64:
6309       if (Flags.isNest()) {
6310         // The 'nest' parameter, if any, is passed in R11.
6311         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6312         break;
6313       }
6314 
6315       // These can be scalar arguments or elements of an integer array type
6316       // passed directly.  Clang may use those instead of "byval" aggregate
6317       // types to avoid forcing arguments to memory unnecessarily.
6318       if (GPR_idx != NumGPRs) {
6319         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6320       } else {
6321         if (IsFastCall)
6322           ComputePtrOff();
6323 
6324         assert(HasParameterArea &&
6325                "Parameter area must exist to pass an argument in memory.");
6326         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6327                          true, CFlags.IsTailCall, false, MemOpChains,
6328                          TailCallArguments, dl);
6329         if (IsFastCall)
6330           ArgOffset += PtrByteSize;
6331       }
6332       if (!IsFastCall)
6333         ArgOffset += PtrByteSize;
6334       break;
6335     case MVT::f32:
6336     case MVT::f64: {
6337       // These can be scalar arguments or elements of a float array type
6338       // passed directly.  The latter are used to implement ELFv2 homogenous
6339       // float aggregates.
6340 
6341       // Named arguments go into FPRs first, and once they overflow, the
6342       // remaining arguments go into GPRs and then the parameter save area.
6343       // Unnamed arguments for vararg functions always go to GPRs and
6344       // then the parameter save area.  For now, put all arguments to vararg
6345       // routines always in both locations (FPR *and* GPR or stack slot).
6346       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6347       bool NeededLoad = false;
6348 
6349       // First load the argument into the next available FPR.
6350       if (FPR_idx != NumFPRs)
6351         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6352 
6353       // Next, load the argument into GPR or stack slot if needed.
6354       if (!NeedGPROrStack)
6355         ;
6356       else if (GPR_idx != NumGPRs && !IsFastCall) {
6357         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6358         // once we support fp <-> gpr moves.
6359 
6360         // In the non-vararg case, this can only ever happen in the
6361         // presence of f32 array types, since otherwise we never run
6362         // out of FPRs before running out of GPRs.
6363         SDValue ArgVal;
6364 
6365         // Double values are always passed in a single GPR.
6366         if (Arg.getValueType() != MVT::f32) {
6367           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6368 
6369         // Non-array float values are extended and passed in a GPR.
6370         } else if (!Flags.isInConsecutiveRegs()) {
6371           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6372           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6373 
6374         // If we have an array of floats, we collect every odd element
6375         // together with its predecessor into one GPR.
6376         } else if (ArgOffset % PtrByteSize != 0) {
6377           SDValue Lo, Hi;
6378           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6379           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6380           if (!isLittleEndian)
6381             std::swap(Lo, Hi);
6382           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6383 
6384         // The final element, if even, goes into the first half of a GPR.
6385         } else if (Flags.isInConsecutiveRegsLast()) {
6386           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6387           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6388           if (!isLittleEndian)
6389             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6390                                  DAG.getConstant(32, dl, MVT::i32));
6391 
6392         // Non-final even elements are skipped; they will be handled
6393         // together the with subsequent argument on the next go-around.
6394         } else
6395           ArgVal = SDValue();
6396 
6397         if (ArgVal.getNode())
6398           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6399       } else {
6400         if (IsFastCall)
6401           ComputePtrOff();
6402 
6403         // Single-precision floating-point values are mapped to the
6404         // second (rightmost) word of the stack doubleword.
6405         if (Arg.getValueType() == MVT::f32 &&
6406             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6407           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6408           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6409         }
6410 
6411         assert(HasParameterArea &&
6412                "Parameter area must exist to pass an argument in memory.");
6413         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6414                          true, CFlags.IsTailCall, false, MemOpChains,
6415                          TailCallArguments, dl);
6416 
6417         NeededLoad = true;
6418       }
6419       // When passing an array of floats, the array occupies consecutive
6420       // space in the argument area; only round up to the next doubleword
6421       // at the end of the array.  Otherwise, each float takes 8 bytes.
6422       if (!IsFastCall || NeededLoad) {
6423         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6424                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6425         if (Flags.isInConsecutiveRegsLast())
6426           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6427       }
6428       break;
6429     }
6430     case MVT::v4f32:
6431     case MVT::v4i32:
6432     case MVT::v8i16:
6433     case MVT::v16i8:
6434     case MVT::v2f64:
6435     case MVT::v2i64:
6436     case MVT::v1i128:
6437     case MVT::f128:
6438       // These can be scalar arguments or elements of a vector array type
6439       // passed directly.  The latter are used to implement ELFv2 homogenous
6440       // vector aggregates.
6441 
6442       // For a varargs call, named arguments go into VRs or on the stack as
6443       // usual; unnamed arguments always go to the stack or the corresponding
6444       // GPRs when within range.  For now, we always put the value in both
6445       // locations (or even all three).
6446       if (CFlags.IsVarArg) {
6447         assert(HasParameterArea &&
6448                "Parameter area must exist if we have a varargs call.");
6449         // We could elide this store in the case where the object fits
6450         // entirely in R registers.  Maybe later.
6451         SDValue Store =
6452             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6453         MemOpChains.push_back(Store);
6454         if (VR_idx != NumVRs) {
6455           SDValue Load =
6456               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6457           MemOpChains.push_back(Load.getValue(1));
6458           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6459         }
6460         ArgOffset += 16;
6461         for (unsigned i=0; i<16; i+=PtrByteSize) {
6462           if (GPR_idx == NumGPRs)
6463             break;
6464           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6465                                    DAG.getConstant(i, dl, PtrVT));
6466           SDValue Load =
6467               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6468           MemOpChains.push_back(Load.getValue(1));
6469           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6470         }
6471         break;
6472       }
6473 
6474       // Non-varargs Altivec params go into VRs or on the stack.
6475       if (VR_idx != NumVRs) {
6476         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6477       } else {
6478         if (IsFastCall)
6479           ComputePtrOff();
6480 
6481         assert(HasParameterArea &&
6482                "Parameter area must exist to pass an argument in memory.");
6483         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6484                          true, CFlags.IsTailCall, true, MemOpChains,
6485                          TailCallArguments, dl);
6486         if (IsFastCall)
6487           ArgOffset += 16;
6488       }
6489 
6490       if (!IsFastCall)
6491         ArgOffset += 16;
6492       break;
6493     }
6494   }
6495 
6496   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6497          "mismatch in size of parameter area");
6498   (void)NumBytesActuallyUsed;
6499 
6500   if (!MemOpChains.empty())
6501     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6502 
6503   // Check if this is an indirect call (MTCTR/BCTRL).
6504   // See prepareDescriptorIndirectCall and buildCallOperands for more
6505   // information about calls through function pointers in the 64-bit SVR4 ABI.
6506   if (CFlags.IsIndirect) {
6507     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6508     // caller in the TOC save area.
6509     if (isTOCSaveRestoreRequired(Subtarget)) {
6510       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6511       // Load r2 into a virtual register and store it to the TOC save area.
6512       setUsesTOCBasePtr(DAG);
6513       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6514       // TOC save area offset.
6515       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6516       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6517       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6518       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6519                            MachinePointerInfo::getStack(
6520                                DAG.getMachineFunction(), TOCSaveOffset));
6521     }
6522     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6523     // This does not mean the MTCTR instruction must use R12; it's easier
6524     // to model this as an extra parameter, so do that.
6525     if (isELFv2ABI && !CFlags.IsPatchPoint)
6526       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6527   }
6528 
6529   // Build a sequence of copy-to-reg nodes chained together with token chain
6530   // and flag operands which copy the outgoing args into the appropriate regs.
6531   SDValue InFlag;
6532   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6533     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6534                              RegsToPass[i].second, InFlag);
6535     InFlag = Chain.getValue(1);
6536   }
6537 
6538   if (CFlags.IsTailCall && !IsSibCall)
6539     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6540                     TailCallArguments);
6541 
6542   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6543                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6544 }
6545 
6546 // Returns true when the shadow of a general purpose argument register
6547 // in the parameter save area is aligned to at least 'RequiredAlign'.
6548 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6549   assert(RequiredAlign.value() <= 16 &&
6550          "Required alignment greater than stack alignment.");
6551   switch (Reg) {
6552   default:
6553     report_fatal_error("called on invalid register.");
6554   case PPC::R5:
6555   case PPC::R9:
6556   case PPC::X3:
6557   case PPC::X5:
6558   case PPC::X7:
6559   case PPC::X9:
6560     // These registers are 16 byte aligned which is the most strict aligment
6561     // we can support.
6562     return true;
6563   case PPC::R3:
6564   case PPC::R7:
6565   case PPC::X4:
6566   case PPC::X6:
6567   case PPC::X8:
6568   case PPC::X10:
6569     // The shadow of these registers in the PSA is 8 byte aligned.
6570     return RequiredAlign <= 8;
6571   case PPC::R4:
6572   case PPC::R6:
6573   case PPC::R8:
6574   case PPC::R10:
6575     return RequiredAlign <= 4;
6576   }
6577 }
6578 
6579 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6580                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6581                    CCState &S) {
6582   AIXCCState &State = static_cast<AIXCCState &>(S);
6583   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6584       State.getMachineFunction().getSubtarget());
6585   const bool IsPPC64 = Subtarget.isPPC64();
6586   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6587   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6588 
6589   if (ValVT == MVT::f128)
6590     report_fatal_error("f128 is unimplemented on AIX.");
6591 
6592   if (ArgFlags.isNest())
6593     report_fatal_error("Nest arguments are unimplemented.");
6594 
6595   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6596                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6597                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6598   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6599                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6600                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6601 
6602   static const MCPhysReg VR[] = {// Vector registers.
6603                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6604                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6605                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6606 
6607   if (ArgFlags.isByVal()) {
6608     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6609       report_fatal_error("Pass-by-value arguments with alignment greater than "
6610                          "register width are not supported.");
6611 
6612     const unsigned ByValSize = ArgFlags.getByValSize();
6613 
6614     // An empty aggregate parameter takes up no storage and no registers,
6615     // but needs a MemLoc for a stack slot for the formal arguments side.
6616     if (ByValSize == 0) {
6617       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6618                                        State.getNextStackOffset(), RegVT,
6619                                        LocInfo));
6620       return false;
6621     }
6622 
6623     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6624     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6625     for (const unsigned E = Offset + StackSize; Offset < E;
6626          Offset += PtrAlign.value()) {
6627       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6628         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6629       else {
6630         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6631                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6632                                          LocInfo));
6633         break;
6634       }
6635     }
6636     return false;
6637   }
6638 
6639   // Arguments always reserve parameter save area.
6640   switch (ValVT.SimpleTy) {
6641   default:
6642     report_fatal_error("Unhandled value type for argument.");
6643   case MVT::i64:
6644     // i64 arguments should have been split to i32 for PPC32.
6645     assert(IsPPC64 && "PPC32 should have split i64 values.");
6646     LLVM_FALLTHROUGH;
6647   case MVT::i1:
6648   case MVT::i32: {
6649     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6650     // AIX integer arguments are always passed in register width.
6651     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6652       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6653                                   : CCValAssign::LocInfo::ZExt;
6654     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6655       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6656     else
6657       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6658 
6659     return false;
6660   }
6661   case MVT::f32:
6662   case MVT::f64: {
6663     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6664     const unsigned StoreSize = LocVT.getStoreSize();
6665     // Floats are always 4-byte aligned in the PSA on AIX.
6666     // This includes f64 in 64-bit mode for ABI compatibility.
6667     const unsigned Offset =
6668         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6669     unsigned FReg = State.AllocateReg(FPR);
6670     if (FReg)
6671       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6672 
6673     // Reserve and initialize GPRs or initialize the PSA as required.
6674     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6675       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6676         assert(FReg && "An FPR should be available when a GPR is reserved.");
6677         if (State.isVarArg()) {
6678           // Successfully reserved GPRs are only initialized for vararg calls.
6679           // Custom handling is required for:
6680           //   f64 in PPC32 needs to be split into 2 GPRs.
6681           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6682           State.addLoc(
6683               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6684         }
6685       } else {
6686         // If there are insufficient GPRs, the PSA needs to be initialized.
6687         // Initialization occurs even if an FPR was initialized for
6688         // compatibility with the AIX XL compiler. The full memory for the
6689         // argument will be initialized even if a prior word is saved in GPR.
6690         // A custom memLoc is used when the argument also passes in FPR so
6691         // that the callee handling can skip over it easily.
6692         State.addLoc(
6693             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6694                                              LocInfo)
6695                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6696         break;
6697       }
6698     }
6699 
6700     return false;
6701   }
6702   case MVT::v4f32:
6703   case MVT::v4i32:
6704   case MVT::v8i16:
6705   case MVT::v16i8:
6706   case MVT::v2i64:
6707   case MVT::v2f64:
6708   case MVT::v1i128: {
6709     const unsigned VecSize = 16;
6710     const Align VecAlign(VecSize);
6711 
6712     if (!State.isVarArg()) {
6713       // If there are vector registers remaining we don't consume any stack
6714       // space.
6715       if (unsigned VReg = State.AllocateReg(VR)) {
6716         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6717         return false;
6718       }
6719       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6720       // might be allocated in the portion of the PSA that is shadowed by the
6721       // GPRs.
6722       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6723       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6724       return false;
6725     }
6726 
6727     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6728     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6729 
6730     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6731     // Burn any underaligned registers and their shadowed stack space until
6732     // we reach the required alignment.
6733     while (NextRegIndex != GPRs.size() &&
6734            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6735       // Shadow allocate register and its stack shadow.
6736       unsigned Reg = State.AllocateReg(GPRs);
6737       State.AllocateStack(PtrSize, PtrAlign);
6738       assert(Reg && "Allocating register unexpectedly failed.");
6739       (void)Reg;
6740       NextRegIndex = State.getFirstUnallocated(GPRs);
6741     }
6742 
6743     // Vectors that are passed as fixed arguments are handled differently.
6744     // They are passed in VRs if any are available (unlike arguments passed
6745     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6746     // functions)
6747     if (State.isFixed(ValNo)) {
6748       if (unsigned VReg = State.AllocateReg(VR)) {
6749         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6750         // Shadow allocate GPRs and stack space even though we pass in a VR.
6751         for (unsigned I = 0; I != VecSize; I += PtrSize)
6752           State.AllocateReg(GPRs);
6753         State.AllocateStack(VecSize, VecAlign);
6754         return false;
6755       }
6756       // No vector registers remain so pass on the stack.
6757       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6758       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6759       return false;
6760     }
6761 
6762     // If all GPRS are consumed then we pass the argument fully on the stack.
6763     if (NextRegIndex == GPRs.size()) {
6764       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6765       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6766       return false;
6767     }
6768 
6769     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6770     // half of the argument, and then need to pass the remaining half on the
6771     // stack.
6772     if (GPRs[NextRegIndex] == PPC::R9) {
6773       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6774       State.addLoc(
6775           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6776 
6777       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6778       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6779       assert(FirstReg && SecondReg &&
6780              "Allocating R9 or R10 unexpectedly failed.");
6781       State.addLoc(
6782           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6783       State.addLoc(
6784           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6785       return false;
6786     }
6787 
6788     // We have enough GPRs to fully pass the vector argument, and we have
6789     // already consumed any underaligned registers. Start with the custom
6790     // MemLoc and then the custom RegLocs.
6791     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6792     State.addLoc(
6793         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6794     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6795       const unsigned Reg = State.AllocateReg(GPRs);
6796       assert(Reg && "Failed to allocated register for vararg vector argument");
6797       State.addLoc(
6798           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6799     }
6800     return false;
6801   }
6802   }
6803   return true;
6804 }
6805 
6806 // So far, this function is only used by LowerFormalArguments_AIX()
6807 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6808                                                     bool IsPPC64,
6809                                                     bool HasP8Vector,
6810                                                     bool HasVSX) {
6811   assert((IsPPC64 || SVT != MVT::i64) &&
6812          "i64 should have been split for 32-bit codegen.");
6813 
6814   switch (SVT) {
6815   default:
6816     report_fatal_error("Unexpected value type for formal argument");
6817   case MVT::i1:
6818   case MVT::i32:
6819   case MVT::i64:
6820     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6821   case MVT::f32:
6822     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6823   case MVT::f64:
6824     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6825   case MVT::v4f32:
6826   case MVT::v4i32:
6827   case MVT::v8i16:
6828   case MVT::v16i8:
6829   case MVT::v2i64:
6830   case MVT::v2f64:
6831   case MVT::v1i128:
6832     return &PPC::VRRCRegClass;
6833   }
6834 }
6835 
6836 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6837                                         SelectionDAG &DAG, SDValue ArgValue,
6838                                         MVT LocVT, const SDLoc &dl) {
6839   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6840   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6841 
6842   if (Flags.isSExt())
6843     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6844                            DAG.getValueType(ValVT));
6845   else if (Flags.isZExt())
6846     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6847                            DAG.getValueType(ValVT));
6848 
6849   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6850 }
6851 
6852 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6853   const unsigned LASize = FL->getLinkageSize();
6854 
6855   if (PPC::GPRCRegClass.contains(Reg)) {
6856     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6857            "Reg must be a valid argument register!");
6858     return LASize + 4 * (Reg - PPC::R3);
6859   }
6860 
6861   if (PPC::G8RCRegClass.contains(Reg)) {
6862     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6863            "Reg must be a valid argument register!");
6864     return LASize + 8 * (Reg - PPC::X3);
6865   }
6866 
6867   llvm_unreachable("Only general purpose registers expected.");
6868 }
6869 
6870 //   AIX ABI Stack Frame Layout:
6871 //
6872 //   Low Memory +--------------------------------------------+
6873 //   SP   +---> | Back chain                                 | ---+
6874 //        |     +--------------------------------------------+    |
6875 //        |     | Saved Condition Register                   |    |
6876 //        |     +--------------------------------------------+    |
6877 //        |     | Saved Linkage Register                     |    |
6878 //        |     +--------------------------------------------+    | Linkage Area
6879 //        |     | Reserved for compilers                     |    |
6880 //        |     +--------------------------------------------+    |
6881 //        |     | Reserved for binders                       |    |
6882 //        |     +--------------------------------------------+    |
6883 //        |     | Saved TOC pointer                          | ---+
6884 //        |     +--------------------------------------------+
6885 //        |     | Parameter save area                        |
6886 //        |     +--------------------------------------------+
6887 //        |     | Alloca space                               |
6888 //        |     +--------------------------------------------+
6889 //        |     | Local variable space                       |
6890 //        |     +--------------------------------------------+
6891 //        |     | Float/int conversion temporary             |
6892 //        |     +--------------------------------------------+
6893 //        |     | Save area for AltiVec registers            |
6894 //        |     +--------------------------------------------+
6895 //        |     | AltiVec alignment padding                  |
6896 //        |     +--------------------------------------------+
6897 //        |     | Save area for VRSAVE register              |
6898 //        |     +--------------------------------------------+
6899 //        |     | Save area for General Purpose registers    |
6900 //        |     +--------------------------------------------+
6901 //        |     | Save area for Floating Point registers     |
6902 //        |     +--------------------------------------------+
6903 //        +---- | Back chain                                 |
6904 // High Memory  +--------------------------------------------+
6905 //
6906 //  Specifications:
6907 //  AIX 7.2 Assembler Language Reference
6908 //  Subroutine linkage convention
6909 
6910 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6911     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6912     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6913     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6914 
6915   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6916           CallConv == CallingConv::Fast) &&
6917          "Unexpected calling convention!");
6918 
6919   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6920     report_fatal_error("Tail call support is unimplemented on AIX.");
6921 
6922   if (useSoftFloat())
6923     report_fatal_error("Soft float support is unimplemented on AIX.");
6924 
6925   const PPCSubtarget &Subtarget =
6926       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6927 
6928   const bool IsPPC64 = Subtarget.isPPC64();
6929   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6930 
6931   // Assign locations to all of the incoming arguments.
6932   SmallVector<CCValAssign, 16> ArgLocs;
6933   MachineFunction &MF = DAG.getMachineFunction();
6934   MachineFrameInfo &MFI = MF.getFrameInfo();
6935   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6936   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6937 
6938   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6939   // Reserve space for the linkage area on the stack.
6940   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6941   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6942   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6943 
6944   SmallVector<SDValue, 8> MemOps;
6945 
6946   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6947     CCValAssign &VA = ArgLocs[I++];
6948     MVT LocVT = VA.getLocVT();
6949     MVT ValVT = VA.getValVT();
6950     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6951     // For compatibility with the AIX XL compiler, the float args in the
6952     // parameter save area are initialized even if the argument is available
6953     // in register.  The caller is required to initialize both the register
6954     // and memory, however, the callee can choose to expect it in either.
6955     // The memloc is dismissed here because the argument is retrieved from
6956     // the register.
6957     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6958       continue;
6959 
6960     auto HandleMemLoc = [&]() {
6961       const unsigned LocSize = LocVT.getStoreSize();
6962       const unsigned ValSize = ValVT.getStoreSize();
6963       assert((ValSize <= LocSize) &&
6964              "Object size is larger than size of MemLoc");
6965       int CurArgOffset = VA.getLocMemOffset();
6966       // Objects are right-justified because AIX is big-endian.
6967       if (LocSize > ValSize)
6968         CurArgOffset += LocSize - ValSize;
6969       // Potential tail calls could cause overwriting of argument stack slots.
6970       const bool IsImmutable =
6971           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6972             (CallConv == CallingConv::Fast));
6973       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6974       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6975       SDValue ArgValue =
6976           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6977       InVals.push_back(ArgValue);
6978     };
6979 
6980     // Vector arguments to VaArg functions are passed both on the stack, and
6981     // in any available GPRs. Load the value from the stack and add the GPRs
6982     // as live ins.
6983     if (VA.isMemLoc() && VA.needsCustom()) {
6984       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6985       assert(isVarArg && "Only use custom memloc for vararg.");
6986       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6987       // matching custom RegLocs.
6988       const unsigned OriginalValNo = VA.getValNo();
6989       (void)OriginalValNo;
6990 
6991       auto HandleCustomVecRegLoc = [&]() {
6992         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6993                "Missing custom RegLoc.");
6994         VA = ArgLocs[I++];
6995         assert(VA.getValVT().isVector() &&
6996                "Unexpected Val type for custom RegLoc.");
6997         assert(VA.getValNo() == OriginalValNo &&
6998                "ValNo mismatch between custom MemLoc and RegLoc.");
6999         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
7000         MF.addLiveIn(VA.getLocReg(),
7001                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7002                                        Subtarget.hasVSX()));
7003       };
7004 
7005       HandleMemLoc();
7006       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7007       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7008       // R10.
7009       HandleCustomVecRegLoc();
7010       HandleCustomVecRegLoc();
7011 
7012       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7013       // we passed the vector in R5, R6, R7 and R8.
7014       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7015         assert(!IsPPC64 &&
7016                "Only 2 custom RegLocs expected for 64-bit codegen.");
7017         HandleCustomVecRegLoc();
7018         HandleCustomVecRegLoc();
7019       }
7020 
7021       continue;
7022     }
7023 
7024     if (VA.isRegLoc()) {
7025       if (VA.getValVT().isScalarInteger())
7026         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7027       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7028         switch (VA.getValVT().SimpleTy) {
7029         default:
7030           report_fatal_error("Unhandled value type for argument.");
7031         case MVT::f32:
7032           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7033           break;
7034         case MVT::f64:
7035           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7036           break;
7037         }
7038       } else if (VA.getValVT().isVector()) {
7039         switch (VA.getValVT().SimpleTy) {
7040         default:
7041           report_fatal_error("Unhandled value type for argument.");
7042         case MVT::v16i8:
7043           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7044           break;
7045         case MVT::v8i16:
7046           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7047           break;
7048         case MVT::v4i32:
7049         case MVT::v2i64:
7050         case MVT::v1i128:
7051           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7052           break;
7053         case MVT::v4f32:
7054         case MVT::v2f64:
7055           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7056           break;
7057         }
7058       }
7059     }
7060 
7061     if (Flags.isByVal() && VA.isMemLoc()) {
7062       const unsigned Size =
7063           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7064                   PtrByteSize);
7065       const int FI = MF.getFrameInfo().CreateFixedObject(
7066           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7067           /* IsAliased */ true);
7068       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7069       InVals.push_back(FIN);
7070 
7071       continue;
7072     }
7073 
7074     if (Flags.isByVal()) {
7075       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7076 
7077       const MCPhysReg ArgReg = VA.getLocReg();
7078       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7079 
7080       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7081         report_fatal_error("Over aligned byvals not supported yet.");
7082 
7083       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7084       const int FI = MF.getFrameInfo().CreateFixedObject(
7085           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7086           /* IsAliased */ true);
7087       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7088       InVals.push_back(FIN);
7089 
7090       // Add live ins for all the RegLocs for the same ByVal.
7091       const TargetRegisterClass *RegClass =
7092           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7093 
7094       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7095                                                unsigned Offset) {
7096         const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7097         // Since the callers side has left justified the aggregate in the
7098         // register, we can simply store the entire register into the stack
7099         // slot.
7100         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7101         // The store to the fixedstack object is needed becuase accessing a
7102         // field of the ByVal will use a gep and load. Ideally we will optimize
7103         // to extracting the value from the register directly, and elide the
7104         // stores when the arguments address is not taken, but that will need to
7105         // be future work.
7106         SDValue Store = DAG.getStore(
7107             CopyFrom.getValue(1), dl, CopyFrom,
7108             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7109             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7110 
7111         MemOps.push_back(Store);
7112       };
7113 
7114       unsigned Offset = 0;
7115       HandleRegLoc(VA.getLocReg(), Offset);
7116       Offset += PtrByteSize;
7117       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7118            Offset += PtrByteSize) {
7119         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7120                "RegLocs should be for ByVal argument.");
7121 
7122         const CCValAssign RL = ArgLocs[I++];
7123         HandleRegLoc(RL.getLocReg(), Offset);
7124         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7125       }
7126 
7127       if (Offset != StackSize) {
7128         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7129                "Expected MemLoc for remaining bytes.");
7130         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7131         // Consume the MemLoc.The InVal has already been emitted, so nothing
7132         // more needs to be done.
7133         ++I;
7134       }
7135 
7136       continue;
7137     }
7138 
7139     if (VA.isRegLoc() && !VA.needsCustom()) {
7140       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7141       Register VReg =
7142           MF.addLiveIn(VA.getLocReg(),
7143                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7144                                          Subtarget.hasVSX()));
7145       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7146       if (ValVT.isScalarInteger() &&
7147           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7148         ArgValue =
7149             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7150       }
7151       InVals.push_back(ArgValue);
7152       continue;
7153     }
7154     if (VA.isMemLoc()) {
7155       HandleMemLoc();
7156       continue;
7157     }
7158   }
7159 
7160   // On AIX a minimum of 8 words is saved to the parameter save area.
7161   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7162   // Area that is at least reserved in the caller of this function.
7163   unsigned CallerReservedArea =
7164       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7165 
7166   // Set the size that is at least reserved in caller of this function. Tail
7167   // call optimized function's reserved stack space needs to be aligned so
7168   // that taking the difference between two stack areas will result in an
7169   // aligned stack.
7170   CallerReservedArea =
7171       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7172   FuncInfo->setMinReservedArea(CallerReservedArea);
7173 
7174   if (isVarArg) {
7175     FuncInfo->setVarArgsFrameIndex(
7176         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7177     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7178 
7179     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7180                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7181 
7182     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7183                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7184     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7185 
7186     // The fixed integer arguments of a variadic function are stored to the
7187     // VarArgsFrameIndex on the stack so that they may be loaded by
7188     // dereferencing the result of va_next.
7189     for (unsigned GPRIndex =
7190              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7191          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7192 
7193       const Register VReg =
7194           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7195                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7196 
7197       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7198       SDValue Store =
7199           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7200       MemOps.push_back(Store);
7201       // Increment the address for the next argument to store.
7202       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7203       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7204     }
7205   }
7206 
7207   if (!MemOps.empty())
7208     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7209 
7210   return Chain;
7211 }
7212 
7213 SDValue PPCTargetLowering::LowerCall_AIX(
7214     SDValue Chain, SDValue Callee, CallFlags CFlags,
7215     const SmallVectorImpl<ISD::OutputArg> &Outs,
7216     const SmallVectorImpl<SDValue> &OutVals,
7217     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7218     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7219     const CallBase *CB) const {
7220   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7221   // AIX ABI stack frame layout.
7222 
7223   assert((CFlags.CallConv == CallingConv::C ||
7224           CFlags.CallConv == CallingConv::Cold ||
7225           CFlags.CallConv == CallingConv::Fast) &&
7226          "Unexpected calling convention!");
7227 
7228   if (CFlags.IsPatchPoint)
7229     report_fatal_error("This call type is unimplemented on AIX.");
7230 
7231   const PPCSubtarget& Subtarget =
7232       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7233 
7234   MachineFunction &MF = DAG.getMachineFunction();
7235   SmallVector<CCValAssign, 16> ArgLocs;
7236   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7237                     *DAG.getContext());
7238 
7239   // Reserve space for the linkage save area (LSA) on the stack.
7240   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7241   //   [SP][CR][LR][2 x reserved][TOC].
7242   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7243   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7244   const bool IsPPC64 = Subtarget.isPPC64();
7245   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7246   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7247   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7248   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7249 
7250   // The prolog code of the callee may store up to 8 GPR argument registers to
7251   // the stack, allowing va_start to index over them in memory if the callee
7252   // is variadic.
7253   // Because we cannot tell if this is needed on the caller side, we have to
7254   // conservatively assume that it is needed.  As such, make sure we have at
7255   // least enough stack space for the caller to store the 8 GPRs.
7256   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7257   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7258                                      CCInfo.getNextStackOffset());
7259 
7260   // Adjust the stack pointer for the new arguments...
7261   // These operations are automatically eliminated by the prolog/epilog pass.
7262   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7263   SDValue CallSeqStart = Chain;
7264 
7265   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7266   SmallVector<SDValue, 8> MemOpChains;
7267 
7268   // Set up a copy of the stack pointer for loading and storing any
7269   // arguments that may not fit in the registers available for argument
7270   // passing.
7271   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7272                                    : DAG.getRegister(PPC::R1, MVT::i32);
7273 
7274   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7275     const unsigned ValNo = ArgLocs[I].getValNo();
7276     SDValue Arg = OutVals[ValNo];
7277     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7278 
7279     if (Flags.isByVal()) {
7280       const unsigned ByValSize = Flags.getByValSize();
7281 
7282       // Nothing to do for zero-sized ByVals on the caller side.
7283       if (!ByValSize) {
7284         ++I;
7285         continue;
7286       }
7287 
7288       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7289         return DAG.getExtLoad(
7290             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7291             (LoadOffset != 0)
7292                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7293                 : Arg,
7294             MachinePointerInfo(), VT);
7295       };
7296 
7297       unsigned LoadOffset = 0;
7298 
7299       // Initialize registers, which are fully occupied by the by-val argument.
7300       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7301         SDValue Load = GetLoad(PtrVT, LoadOffset);
7302         MemOpChains.push_back(Load.getValue(1));
7303         LoadOffset += PtrByteSize;
7304         const CCValAssign &ByValVA = ArgLocs[I++];
7305         assert(ByValVA.getValNo() == ValNo &&
7306                "Unexpected location for pass-by-value argument.");
7307         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7308       }
7309 
7310       if (LoadOffset == ByValSize)
7311         continue;
7312 
7313       // There must be one more loc to handle the remainder.
7314       assert(ArgLocs[I].getValNo() == ValNo &&
7315              "Expected additional location for by-value argument.");
7316 
7317       if (ArgLocs[I].isMemLoc()) {
7318         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7319         const CCValAssign &ByValVA = ArgLocs[I++];
7320         ISD::ArgFlagsTy MemcpyFlags = Flags;
7321         // Only memcpy the bytes that don't pass in register.
7322         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7323         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7324             (LoadOffset != 0)
7325                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7326                 : Arg,
7327             DAG.getObjectPtrOffset(dl, StackPtr,
7328                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7329             CallSeqStart, MemcpyFlags, DAG, dl);
7330         continue;
7331       }
7332 
7333       // Initialize the final register residue.
7334       // Any residue that occupies the final by-val arg register must be
7335       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7336       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7337       // 2 and 1 byte loads.
7338       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7339       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7340              "Unexpected register residue for by-value argument.");
7341       SDValue ResidueVal;
7342       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7343         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7344         const MVT VT =
7345             N == 1 ? MVT::i8
7346                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7347         SDValue Load = GetLoad(VT, LoadOffset);
7348         MemOpChains.push_back(Load.getValue(1));
7349         LoadOffset += N;
7350         Bytes += N;
7351 
7352         // By-val arguments are passed left-justfied in register.
7353         // Every load here needs to be shifted, otherwise a full register load
7354         // should have been used.
7355         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7356                "Unexpected load emitted during handling of pass-by-value "
7357                "argument.");
7358         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7359         EVT ShiftAmountTy =
7360             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7361         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7362         SDValue ShiftedLoad =
7363             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7364         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7365                                               ShiftedLoad)
7366                                 : ShiftedLoad;
7367       }
7368 
7369       const CCValAssign &ByValVA = ArgLocs[I++];
7370       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7371       continue;
7372     }
7373 
7374     CCValAssign &VA = ArgLocs[I++];
7375     const MVT LocVT = VA.getLocVT();
7376     const MVT ValVT = VA.getValVT();
7377 
7378     switch (VA.getLocInfo()) {
7379     default:
7380       report_fatal_error("Unexpected argument extension type.");
7381     case CCValAssign::Full:
7382       break;
7383     case CCValAssign::ZExt:
7384       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7385       break;
7386     case CCValAssign::SExt:
7387       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7388       break;
7389     }
7390 
7391     if (VA.isRegLoc() && !VA.needsCustom()) {
7392       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7393       continue;
7394     }
7395 
7396     // Vector arguments passed to VarArg functions need custom handling when
7397     // they are passed (at least partially) in GPRs.
7398     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7399       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7400       // Store value to its stack slot.
7401       SDValue PtrOff =
7402           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7403       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7404       SDValue Store =
7405           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7406       MemOpChains.push_back(Store);
7407       const unsigned OriginalValNo = VA.getValNo();
7408       // Then load the GPRs from the stack
7409       unsigned LoadOffset = 0;
7410       auto HandleCustomVecRegLoc = [&]() {
7411         assert(I != E && "Unexpected end of CCvalAssigns.");
7412         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7413                "Expected custom RegLoc.");
7414         CCValAssign RegVA = ArgLocs[I++];
7415         assert(RegVA.getValNo() == OriginalValNo &&
7416                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7417         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7418                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7419         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7420         MemOpChains.push_back(Load.getValue(1));
7421         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7422         LoadOffset += PtrByteSize;
7423       };
7424 
7425       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7426       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7427       // R10.
7428       HandleCustomVecRegLoc();
7429       HandleCustomVecRegLoc();
7430 
7431       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7432           ArgLocs[I].getValNo() == OriginalValNo) {
7433         assert(!IsPPC64 &&
7434                "Only 2 custom RegLocs expected for 64-bit codegen.");
7435         HandleCustomVecRegLoc();
7436         HandleCustomVecRegLoc();
7437       }
7438 
7439       continue;
7440     }
7441 
7442     if (VA.isMemLoc()) {
7443       SDValue PtrOff =
7444           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7445       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7446       MemOpChains.push_back(
7447           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7448 
7449       continue;
7450     }
7451 
7452     if (!ValVT.isFloatingPoint())
7453       report_fatal_error(
7454           "Unexpected register handling for calling convention.");
7455 
7456     // Custom handling is used for GPR initializations for vararg float
7457     // arguments.
7458     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7459            LocVT.isInteger() &&
7460            "Custom register handling only expected for VarArg.");
7461 
7462     SDValue ArgAsInt =
7463         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7464 
7465     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7466       // f32 in 32-bit GPR
7467       // f64 in 64-bit GPR
7468       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7469     else if (Arg.getValueType().getFixedSizeInBits() <
7470              LocVT.getFixedSizeInBits())
7471       // f32 in 64-bit GPR.
7472       RegsToPass.push_back(std::make_pair(
7473           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7474     else {
7475       // f64 in two 32-bit GPRs
7476       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7477       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7478              "Unexpected custom register for argument!");
7479       CCValAssign &GPR1 = VA;
7480       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7481                                      DAG.getConstant(32, dl, MVT::i8));
7482       RegsToPass.push_back(std::make_pair(
7483           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7484 
7485       if (I != E) {
7486         // If only 1 GPR was available, there will only be one custom GPR and
7487         // the argument will also pass in memory.
7488         CCValAssign &PeekArg = ArgLocs[I];
7489         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7490           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7491           CCValAssign &GPR2 = ArgLocs[I++];
7492           RegsToPass.push_back(std::make_pair(
7493               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7494         }
7495       }
7496     }
7497   }
7498 
7499   if (!MemOpChains.empty())
7500     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7501 
7502   // For indirect calls, we need to save the TOC base to the stack for
7503   // restoration after the call.
7504   if (CFlags.IsIndirect) {
7505     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7506     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7507     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7508     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7509     const unsigned TOCSaveOffset =
7510         Subtarget.getFrameLowering()->getTOCSaveOffset();
7511 
7512     setUsesTOCBasePtr(DAG);
7513     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7514     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7515     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7516     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7517     Chain = DAG.getStore(
7518         Val.getValue(1), dl, Val, AddPtr,
7519         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7520   }
7521 
7522   // Build a sequence of copy-to-reg nodes chained together with token chain
7523   // and flag operands which copy the outgoing args into the appropriate regs.
7524   SDValue InFlag;
7525   for (auto Reg : RegsToPass) {
7526     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7527     InFlag = Chain.getValue(1);
7528   }
7529 
7530   const int SPDiff = 0;
7531   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7532                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7533 }
7534 
7535 bool
7536 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7537                                   MachineFunction &MF, bool isVarArg,
7538                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7539                                   LLVMContext &Context) const {
7540   SmallVector<CCValAssign, 16> RVLocs;
7541   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7542   return CCInfo.CheckReturn(
7543       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7544                 ? RetCC_PPC_Cold
7545                 : RetCC_PPC);
7546 }
7547 
7548 SDValue
7549 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7550                                bool isVarArg,
7551                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7552                                const SmallVectorImpl<SDValue> &OutVals,
7553                                const SDLoc &dl, SelectionDAG &DAG) const {
7554   SmallVector<CCValAssign, 16> RVLocs;
7555   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7556                  *DAG.getContext());
7557   CCInfo.AnalyzeReturn(Outs,
7558                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7559                            ? RetCC_PPC_Cold
7560                            : RetCC_PPC);
7561 
7562   SDValue Flag;
7563   SmallVector<SDValue, 4> RetOps(1, Chain);
7564 
7565   // Copy the result values into the output registers.
7566   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7567     CCValAssign &VA = RVLocs[i];
7568     assert(VA.isRegLoc() && "Can only return in registers!");
7569 
7570     SDValue Arg = OutVals[RealResIdx];
7571 
7572     switch (VA.getLocInfo()) {
7573     default: llvm_unreachable("Unknown loc info!");
7574     case CCValAssign::Full: break;
7575     case CCValAssign::AExt:
7576       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7577       break;
7578     case CCValAssign::ZExt:
7579       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7580       break;
7581     case CCValAssign::SExt:
7582       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7583       break;
7584     }
7585     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7586       bool isLittleEndian = Subtarget.isLittleEndian();
7587       // Legalize ret f64 -> ret 2 x i32.
7588       SDValue SVal =
7589           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7590                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7591       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7592       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7593       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7594                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7595       Flag = Chain.getValue(1);
7596       VA = RVLocs[++i]; // skip ahead to next loc
7597       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7598     } else
7599       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7600     Flag = Chain.getValue(1);
7601     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7602   }
7603 
7604   RetOps[0] = Chain;  // Update chain.
7605 
7606   // Add the flag if we have it.
7607   if (Flag.getNode())
7608     RetOps.push_back(Flag);
7609 
7610   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7611 }
7612 
7613 SDValue
7614 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7615                                                 SelectionDAG &DAG) const {
7616   SDLoc dl(Op);
7617 
7618   // Get the correct type for integers.
7619   EVT IntVT = Op.getValueType();
7620 
7621   // Get the inputs.
7622   SDValue Chain = Op.getOperand(0);
7623   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7624   // Build a DYNAREAOFFSET node.
7625   SDValue Ops[2] = {Chain, FPSIdx};
7626   SDVTList VTs = DAG.getVTList(IntVT);
7627   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7628 }
7629 
7630 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7631                                              SelectionDAG &DAG) const {
7632   // When we pop the dynamic allocation we need to restore the SP link.
7633   SDLoc dl(Op);
7634 
7635   // Get the correct type for pointers.
7636   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7637 
7638   // Construct the stack pointer operand.
7639   bool isPPC64 = Subtarget.isPPC64();
7640   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7641   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7642 
7643   // Get the operands for the STACKRESTORE.
7644   SDValue Chain = Op.getOperand(0);
7645   SDValue SaveSP = Op.getOperand(1);
7646 
7647   // Load the old link SP.
7648   SDValue LoadLinkSP =
7649       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7650 
7651   // Restore the stack pointer.
7652   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7653 
7654   // Store the old link SP.
7655   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7656 }
7657 
7658 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7659   MachineFunction &MF = DAG.getMachineFunction();
7660   bool isPPC64 = Subtarget.isPPC64();
7661   EVT PtrVT = getPointerTy(MF.getDataLayout());
7662 
7663   // Get current frame pointer save index.  The users of this index will be
7664   // primarily DYNALLOC instructions.
7665   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7666   int RASI = FI->getReturnAddrSaveIndex();
7667 
7668   // If the frame pointer save index hasn't been defined yet.
7669   if (!RASI) {
7670     // Find out what the fix offset of the frame pointer save area.
7671     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7672     // Allocate the frame index for frame pointer save area.
7673     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7674     // Save the result.
7675     FI->setReturnAddrSaveIndex(RASI);
7676   }
7677   return DAG.getFrameIndex(RASI, PtrVT);
7678 }
7679 
7680 SDValue
7681 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7682   MachineFunction &MF = DAG.getMachineFunction();
7683   bool isPPC64 = Subtarget.isPPC64();
7684   EVT PtrVT = getPointerTy(MF.getDataLayout());
7685 
7686   // Get current frame pointer save index.  The users of this index will be
7687   // primarily DYNALLOC instructions.
7688   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7689   int FPSI = FI->getFramePointerSaveIndex();
7690 
7691   // If the frame pointer save index hasn't been defined yet.
7692   if (!FPSI) {
7693     // Find out what the fix offset of the frame pointer save area.
7694     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7695     // Allocate the frame index for frame pointer save area.
7696     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7697     // Save the result.
7698     FI->setFramePointerSaveIndex(FPSI);
7699   }
7700   return DAG.getFrameIndex(FPSI, PtrVT);
7701 }
7702 
7703 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7704                                                    SelectionDAG &DAG) const {
7705   MachineFunction &MF = DAG.getMachineFunction();
7706   // Get the inputs.
7707   SDValue Chain = Op.getOperand(0);
7708   SDValue Size  = Op.getOperand(1);
7709   SDLoc dl(Op);
7710 
7711   // Get the correct type for pointers.
7712   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7713   // Negate the size.
7714   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7715                                 DAG.getConstant(0, dl, PtrVT), Size);
7716   // Construct a node for the frame pointer save index.
7717   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7718   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7719   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7720   if (hasInlineStackProbe(MF))
7721     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7722   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7723 }
7724 
7725 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7726                                                      SelectionDAG &DAG) const {
7727   MachineFunction &MF = DAG.getMachineFunction();
7728 
7729   bool isPPC64 = Subtarget.isPPC64();
7730   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7731 
7732   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7733   return DAG.getFrameIndex(FI, PtrVT);
7734 }
7735 
7736 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7737                                                SelectionDAG &DAG) const {
7738   SDLoc DL(Op);
7739   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7740                      DAG.getVTList(MVT::i32, MVT::Other),
7741                      Op.getOperand(0), Op.getOperand(1));
7742 }
7743 
7744 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7745                                                 SelectionDAG &DAG) const {
7746   SDLoc DL(Op);
7747   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7748                      Op.getOperand(0), Op.getOperand(1));
7749 }
7750 
7751 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7752   if (Op.getValueType().isVector())
7753     return LowerVectorLoad(Op, DAG);
7754 
7755   assert(Op.getValueType() == MVT::i1 &&
7756          "Custom lowering only for i1 loads");
7757 
7758   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7759 
7760   SDLoc dl(Op);
7761   LoadSDNode *LD = cast<LoadSDNode>(Op);
7762 
7763   SDValue Chain = LD->getChain();
7764   SDValue BasePtr = LD->getBasePtr();
7765   MachineMemOperand *MMO = LD->getMemOperand();
7766 
7767   SDValue NewLD =
7768       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7769                      BasePtr, MVT::i8, MMO);
7770   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7771 
7772   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7773   return DAG.getMergeValues(Ops, dl);
7774 }
7775 
7776 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7777   if (Op.getOperand(1).getValueType().isVector())
7778     return LowerVectorStore(Op, DAG);
7779 
7780   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7781          "Custom lowering only for i1 stores");
7782 
7783   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7784 
7785   SDLoc dl(Op);
7786   StoreSDNode *ST = cast<StoreSDNode>(Op);
7787 
7788   SDValue Chain = ST->getChain();
7789   SDValue BasePtr = ST->getBasePtr();
7790   SDValue Value = ST->getValue();
7791   MachineMemOperand *MMO = ST->getMemOperand();
7792 
7793   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7794                       Value);
7795   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7796 }
7797 
7798 // FIXME: Remove this once the ANDI glue bug is fixed:
7799 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7800   assert(Op.getValueType() == MVT::i1 &&
7801          "Custom lowering only for i1 results");
7802 
7803   SDLoc DL(Op);
7804   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7805 }
7806 
7807 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7808                                                SelectionDAG &DAG) const {
7809 
7810   // Implements a vector truncate that fits in a vector register as a shuffle.
7811   // We want to legalize vector truncates down to where the source fits in
7812   // a vector register (and target is therefore smaller than vector register
7813   // size).  At that point legalization will try to custom lower the sub-legal
7814   // result and get here - where we can contain the truncate as a single target
7815   // operation.
7816 
7817   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7818   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7819   //
7820   // We will implement it for big-endian ordering as this (where x denotes
7821   // undefined):
7822   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7823   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7824   //
7825   // The same operation in little-endian ordering will be:
7826   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7827   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7828 
7829   EVT TrgVT = Op.getValueType();
7830   assert(TrgVT.isVector() && "Vector type expected.");
7831   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7832   EVT EltVT = TrgVT.getVectorElementType();
7833   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7834       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7835       !isPowerOf2_32(EltVT.getSizeInBits()))
7836     return SDValue();
7837 
7838   SDValue N1 = Op.getOperand(0);
7839   EVT SrcVT = N1.getValueType();
7840   unsigned SrcSize = SrcVT.getSizeInBits();
7841   if (SrcSize > 256 ||
7842       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7843       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7844     return SDValue();
7845   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7846     return SDValue();
7847 
7848   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7849   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7850 
7851   SDLoc DL(Op);
7852   SDValue Op1, Op2;
7853   if (SrcSize == 256) {
7854     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7855     EVT SplitVT =
7856         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7857     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7858     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7859                       DAG.getConstant(0, DL, VecIdxTy));
7860     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7861                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7862   }
7863   else {
7864     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7865     Op2 = DAG.getUNDEF(WideVT);
7866   }
7867 
7868   // First list the elements we want to keep.
7869   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7870   SmallVector<int, 16> ShuffV;
7871   if (Subtarget.isLittleEndian())
7872     for (unsigned i = 0; i < TrgNumElts; ++i)
7873       ShuffV.push_back(i * SizeMult);
7874   else
7875     for (unsigned i = 1; i <= TrgNumElts; ++i)
7876       ShuffV.push_back(i * SizeMult - 1);
7877 
7878   // Populate the remaining elements with undefs.
7879   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7880     // ShuffV.push_back(i + WideNumElts);
7881     ShuffV.push_back(WideNumElts + 1);
7882 
7883   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7884   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7885   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7886 }
7887 
7888 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7889 /// possible.
7890 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7891   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7892   EVT ResVT = Op.getValueType();
7893   EVT CmpVT = Op.getOperand(0).getValueType();
7894   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7895   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7896   SDLoc dl(Op);
7897 
7898   // Without power9-vector, we don't have native instruction for f128 comparison.
7899   // Following transformation to libcall is needed for setcc:
7900   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7901   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7902     SDValue Z = DAG.getSetCC(
7903         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7904         LHS, RHS, CC);
7905     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7906     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7907   }
7908 
7909   // Not FP, or using SPE? Not a fsel.
7910   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7911       Subtarget.hasSPE())
7912     return Op;
7913 
7914   SDNodeFlags Flags = Op.getNode()->getFlags();
7915 
7916   // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
7917   // presence of infinities.
7918   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7919     switch (CC) {
7920     default:
7921       break;
7922     case ISD::SETOGT:
7923     case ISD::SETGT:
7924       return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
7925     case ISD::SETOLT:
7926     case ISD::SETLT:
7927       return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
7928     }
7929   }
7930 
7931   // We might be able to do better than this under some circumstances, but in
7932   // general, fsel-based lowering of select is a finite-math-only optimization.
7933   // For more information, see section F.3 of the 2.06 ISA specification.
7934   // With ISA 3.0
7935   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7936       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7937     return Op;
7938 
7939   // If the RHS of the comparison is a 0.0, we don't need to do the
7940   // subtraction at all.
7941   SDValue Sel1;
7942   if (isFloatingPointZero(RHS))
7943     switch (CC) {
7944     default: break;       // SETUO etc aren't handled by fsel.
7945     case ISD::SETNE:
7946       std::swap(TV, FV);
7947       LLVM_FALLTHROUGH;
7948     case ISD::SETEQ:
7949       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7950         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7951       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7952       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7953         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7954       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7955                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7956     case ISD::SETULT:
7957     case ISD::SETLT:
7958       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7959       LLVM_FALLTHROUGH;
7960     case ISD::SETOGE:
7961     case ISD::SETGE:
7962       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7963         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7964       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7965     case ISD::SETUGT:
7966     case ISD::SETGT:
7967       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7968       LLVM_FALLTHROUGH;
7969     case ISD::SETOLE:
7970     case ISD::SETLE:
7971       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7972         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7973       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7974                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7975     }
7976 
7977   SDValue Cmp;
7978   switch (CC) {
7979   default: break;       // SETUO etc aren't handled by fsel.
7980   case ISD::SETNE:
7981     std::swap(TV, FV);
7982     LLVM_FALLTHROUGH;
7983   case ISD::SETEQ:
7984     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7985     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7986       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7987     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7988     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7989       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7990     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7991                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7992   case ISD::SETULT:
7993   case ISD::SETLT:
7994     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7995     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7996       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7997     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7998   case ISD::SETOGE:
7999   case ISD::SETGE:
8000     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8001     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8002       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8003     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8004   case ISD::SETUGT:
8005   case ISD::SETGT:
8006     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8007     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8008       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8009     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8010   case ISD::SETOLE:
8011   case ISD::SETLE:
8012     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8013     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8014       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8015     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8016   }
8017   return Op;
8018 }
8019 
8020 static unsigned getPPCStrictOpcode(unsigned Opc) {
8021   switch (Opc) {
8022   default:
8023     llvm_unreachable("No strict version of this opcode!");
8024   case PPCISD::FCTIDZ:
8025     return PPCISD::STRICT_FCTIDZ;
8026   case PPCISD::FCTIWZ:
8027     return PPCISD::STRICT_FCTIWZ;
8028   case PPCISD::FCTIDUZ:
8029     return PPCISD::STRICT_FCTIDUZ;
8030   case PPCISD::FCTIWUZ:
8031     return PPCISD::STRICT_FCTIWUZ;
8032   case PPCISD::FCFID:
8033     return PPCISD::STRICT_FCFID;
8034   case PPCISD::FCFIDU:
8035     return PPCISD::STRICT_FCFIDU;
8036   case PPCISD::FCFIDS:
8037     return PPCISD::STRICT_FCFIDS;
8038   case PPCISD::FCFIDUS:
8039     return PPCISD::STRICT_FCFIDUS;
8040   }
8041 }
8042 
8043 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8044                               const PPCSubtarget &Subtarget) {
8045   SDLoc dl(Op);
8046   bool IsStrict = Op->isStrictFPOpcode();
8047   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8048                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8049 
8050   // TODO: Any other flags to propagate?
8051   SDNodeFlags Flags;
8052   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8053 
8054   // For strict nodes, source is the second operand.
8055   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8056   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8057   assert(Src.getValueType().isFloatingPoint());
8058   if (Src.getValueType() == MVT::f32) {
8059     if (IsStrict) {
8060       Src =
8061           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8062                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8063       Chain = Src.getValue(1);
8064     } else
8065       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8066   }
8067   SDValue Conv;
8068   unsigned Opc = ISD::DELETED_NODE;
8069   switch (Op.getSimpleValueType().SimpleTy) {
8070   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8071   case MVT::i32:
8072     Opc = IsSigned ? PPCISD::FCTIWZ
8073                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8074     break;
8075   case MVT::i64:
8076     assert((IsSigned || Subtarget.hasFPCVT()) &&
8077            "i64 FP_TO_UINT is supported only with FPCVT");
8078     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8079   }
8080   if (IsStrict) {
8081     Opc = getPPCStrictOpcode(Opc);
8082     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8083                        {Chain, Src}, Flags);
8084   } else {
8085     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8086   }
8087   return Conv;
8088 }
8089 
8090 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8091                                                SelectionDAG &DAG,
8092                                                const SDLoc &dl) const {
8093   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8094   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8095                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8096   bool IsStrict = Op->isStrictFPOpcode();
8097 
8098   // Convert the FP value to an int value through memory.
8099   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8100                   (IsSigned || Subtarget.hasFPCVT());
8101   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8102   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8103   MachinePointerInfo MPI =
8104       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8105 
8106   // Emit a store to the stack slot.
8107   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8108   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8109   if (i32Stack) {
8110     MachineFunction &MF = DAG.getMachineFunction();
8111     Alignment = Align(4);
8112     MachineMemOperand *MMO =
8113         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8114     SDValue Ops[] = { Chain, Tmp, FIPtr };
8115     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8116               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8117   } else
8118     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8119 
8120   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8121   // add in a bias on big endian.
8122   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8123     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8124                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8125     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8126   }
8127 
8128   RLI.Chain = Chain;
8129   RLI.Ptr = FIPtr;
8130   RLI.MPI = MPI;
8131   RLI.Alignment = Alignment;
8132 }
8133 
8134 /// Custom lowers floating point to integer conversions to use
8135 /// the direct move instructions available in ISA 2.07 to avoid the
8136 /// need for load/store combinations.
8137 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8138                                                     SelectionDAG &DAG,
8139                                                     const SDLoc &dl) const {
8140   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8141   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8142   if (Op->isStrictFPOpcode())
8143     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8144   else
8145     return Mov;
8146 }
8147 
8148 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8149                                           const SDLoc &dl) const {
8150   bool IsStrict = Op->isStrictFPOpcode();
8151   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8152                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8153   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8154   EVT SrcVT = Src.getValueType();
8155   EVT DstVT = Op.getValueType();
8156 
8157   // FP to INT conversions are legal for f128.
8158   if (SrcVT == MVT::f128)
8159     return Subtarget.hasP9Vector() ? Op : SDValue();
8160 
8161   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8162   // PPC (the libcall is not available).
8163   if (SrcVT == MVT::ppcf128) {
8164     if (DstVT == MVT::i32) {
8165       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8166       // set other fast-math flags to FP operations in both strict and
8167       // non-strict cases. (FP_TO_SINT, FSUB)
8168       SDNodeFlags Flags;
8169       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8170 
8171       if (IsSigned) {
8172         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8173                                  DAG.getIntPtrConstant(0, dl));
8174         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8175                                  DAG.getIntPtrConstant(1, dl));
8176 
8177         // Add the two halves of the long double in round-to-zero mode, and use
8178         // a smaller FP_TO_SINT.
8179         if (IsStrict) {
8180           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8181                                     DAG.getVTList(MVT::f64, MVT::Other),
8182                                     {Op.getOperand(0), Lo, Hi}, Flags);
8183           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8184                              DAG.getVTList(MVT::i32, MVT::Other),
8185                              {Res.getValue(1), Res}, Flags);
8186         } else {
8187           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8188           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8189         }
8190       } else {
8191         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8192         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8193         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8194         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8195         if (IsStrict) {
8196           // Sel = Src < 0x80000000
8197           // FltOfs = select Sel, 0.0, 0x80000000
8198           // IntOfs = select Sel, 0, 0x80000000
8199           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8200           SDValue Chain = Op.getOperand(0);
8201           EVT SetCCVT =
8202               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8203           EVT DstSetCCVT =
8204               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8205           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8206                                      Chain, true);
8207           Chain = Sel.getValue(1);
8208 
8209           SDValue FltOfs = DAG.getSelect(
8210               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8211           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8212 
8213           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8214                                     DAG.getVTList(SrcVT, MVT::Other),
8215                                     {Chain, Src, FltOfs}, Flags);
8216           Chain = Val.getValue(1);
8217           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8218                                      DAG.getVTList(DstVT, MVT::Other),
8219                                      {Chain, Val}, Flags);
8220           Chain = SInt.getValue(1);
8221           SDValue IntOfs = DAG.getSelect(
8222               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8223           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8224           return DAG.getMergeValues({Result, Chain}, dl);
8225         } else {
8226           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8227           // FIXME: generated code sucks.
8228           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8229           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8230           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8231           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8232           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8233         }
8234       }
8235     }
8236 
8237     return SDValue();
8238   }
8239 
8240   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8241     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8242 
8243   ReuseLoadInfo RLI;
8244   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8245 
8246   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8247                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8248 }
8249 
8250 // We're trying to insert a regular store, S, and then a load, L. If the
8251 // incoming value, O, is a load, we might just be able to have our load use the
8252 // address used by O. However, we don't know if anything else will store to
8253 // that address before we can load from it. To prevent this situation, we need
8254 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8255 // the same chain operand as O, we create a token factor from the chain results
8256 // of O and L, and we replace all uses of O's chain result with that token
8257 // factor (see spliceIntoChain below for this last part).
8258 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8259                                             ReuseLoadInfo &RLI,
8260                                             SelectionDAG &DAG,
8261                                             ISD::LoadExtType ET) const {
8262   // Conservatively skip reusing for constrained FP nodes.
8263   if (Op->isStrictFPOpcode())
8264     return false;
8265 
8266   SDLoc dl(Op);
8267   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8268                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8269   if (ET == ISD::NON_EXTLOAD &&
8270       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8271       isOperationLegalOrCustom(Op.getOpcode(),
8272                                Op.getOperand(0).getValueType())) {
8273 
8274     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8275     return true;
8276   }
8277 
8278   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8279   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8280       LD->isNonTemporal())
8281     return false;
8282   if (LD->getMemoryVT() != MemVT)
8283     return false;
8284 
8285   // If the result of the load is an illegal type, then we can't build a
8286   // valid chain for reuse since the legalised loads and token factor node that
8287   // ties the legalised loads together uses a different output chain then the
8288   // illegal load.
8289   if (!isTypeLegal(LD->getValueType(0)))
8290     return false;
8291 
8292   RLI.Ptr = LD->getBasePtr();
8293   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8294     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8295            "Non-pre-inc AM on PPC?");
8296     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8297                           LD->getOffset());
8298   }
8299 
8300   RLI.Chain = LD->getChain();
8301   RLI.MPI = LD->getPointerInfo();
8302   RLI.IsDereferenceable = LD->isDereferenceable();
8303   RLI.IsInvariant = LD->isInvariant();
8304   RLI.Alignment = LD->getAlign();
8305   RLI.AAInfo = LD->getAAInfo();
8306   RLI.Ranges = LD->getRanges();
8307 
8308   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8309   return true;
8310 }
8311 
8312 // Given the head of the old chain, ResChain, insert a token factor containing
8313 // it and NewResChain, and make users of ResChain now be users of that token
8314 // factor.
8315 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8316 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8317                                         SDValue NewResChain,
8318                                         SelectionDAG &DAG) const {
8319   if (!ResChain)
8320     return;
8321 
8322   SDLoc dl(NewResChain);
8323 
8324   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8325                            NewResChain, DAG.getUNDEF(MVT::Other));
8326   assert(TF.getNode() != NewResChain.getNode() &&
8327          "A new TF really is required here");
8328 
8329   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8330   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8331 }
8332 
8333 /// Analyze profitability of direct move
8334 /// prefer float load to int load plus direct move
8335 /// when there is no integer use of int load
8336 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8337   SDNode *Origin = Op.getOperand(0).getNode();
8338   if (Origin->getOpcode() != ISD::LOAD)
8339     return true;
8340 
8341   // If there is no LXSIBZX/LXSIHZX, like Power8,
8342   // prefer direct move if the memory size is 1 or 2 bytes.
8343   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8344   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8345     return true;
8346 
8347   for (SDNode::use_iterator UI = Origin->use_begin(),
8348                             UE = Origin->use_end();
8349        UI != UE; ++UI) {
8350 
8351     // Only look at the users of the loaded value.
8352     if (UI.getUse().get().getResNo() != 0)
8353       continue;
8354 
8355     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8356         UI->getOpcode() != ISD::UINT_TO_FP &&
8357         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8358         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8359       return true;
8360   }
8361 
8362   return false;
8363 }
8364 
8365 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8366                               const PPCSubtarget &Subtarget,
8367                               SDValue Chain = SDValue()) {
8368   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8369                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8370   SDLoc dl(Op);
8371 
8372   // TODO: Any other flags to propagate?
8373   SDNodeFlags Flags;
8374   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8375 
8376   // If we have FCFIDS, then use it when converting to single-precision.
8377   // Otherwise, convert to double-precision and then round.
8378   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8379   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8380                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8381   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8382   if (Op->isStrictFPOpcode()) {
8383     if (!Chain)
8384       Chain = Op.getOperand(0);
8385     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8386                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8387   } else
8388     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8389 }
8390 
8391 /// Custom lowers integer to floating point conversions to use
8392 /// the direct move instructions available in ISA 2.07 to avoid the
8393 /// need for load/store combinations.
8394 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8395                                                     SelectionDAG &DAG,
8396                                                     const SDLoc &dl) const {
8397   assert((Op.getValueType() == MVT::f32 ||
8398           Op.getValueType() == MVT::f64) &&
8399          "Invalid floating point type as target of conversion");
8400   assert(Subtarget.hasFPCVT() &&
8401          "Int to FP conversions with direct moves require FPCVT");
8402   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8403   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8404   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8405                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8406   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8407   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8408   return convertIntToFP(Op, Mov, DAG, Subtarget);
8409 }
8410 
8411 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8412 
8413   EVT VecVT = Vec.getValueType();
8414   assert(VecVT.isVector() && "Expected a vector type.");
8415   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8416 
8417   EVT EltVT = VecVT.getVectorElementType();
8418   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8419   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8420 
8421   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8422   SmallVector<SDValue, 16> Ops(NumConcat);
8423   Ops[0] = Vec;
8424   SDValue UndefVec = DAG.getUNDEF(VecVT);
8425   for (unsigned i = 1; i < NumConcat; ++i)
8426     Ops[i] = UndefVec;
8427 
8428   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8429 }
8430 
8431 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8432                                                 const SDLoc &dl) const {
8433   bool IsStrict = Op->isStrictFPOpcode();
8434   unsigned Opc = Op.getOpcode();
8435   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8436   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8437           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8438          "Unexpected conversion type");
8439   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8440          "Supports conversions to v2f64/v4f32 only.");
8441 
8442   // TODO: Any other flags to propagate?
8443   SDNodeFlags Flags;
8444   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8445 
8446   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8447   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8448 
8449   SDValue Wide = widenVec(DAG, Src, dl);
8450   EVT WideVT = Wide.getValueType();
8451   unsigned WideNumElts = WideVT.getVectorNumElements();
8452   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8453 
8454   SmallVector<int, 16> ShuffV;
8455   for (unsigned i = 0; i < WideNumElts; ++i)
8456     ShuffV.push_back(i + WideNumElts);
8457 
8458   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8459   int SaveElts = FourEltRes ? 4 : 2;
8460   if (Subtarget.isLittleEndian())
8461     for (int i = 0; i < SaveElts; i++)
8462       ShuffV[i * Stride] = i;
8463   else
8464     for (int i = 1; i <= SaveElts; i++)
8465       ShuffV[i * Stride - 1] = i - 1;
8466 
8467   SDValue ShuffleSrc2 =
8468       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8469   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8470 
8471   SDValue Extend;
8472   if (SignedConv) {
8473     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8474     EVT ExtVT = Src.getValueType();
8475     if (Subtarget.hasP9Altivec())
8476       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8477                                IntermediateVT.getVectorNumElements());
8478 
8479     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8480                          DAG.getValueType(ExtVT));
8481   } else
8482     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8483 
8484   if (IsStrict)
8485     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8486                        {Op.getOperand(0), Extend}, Flags);
8487 
8488   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8489 }
8490 
8491 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8492                                           SelectionDAG &DAG) const {
8493   SDLoc dl(Op);
8494   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8495                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8496   bool IsStrict = Op->isStrictFPOpcode();
8497   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8498   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8499 
8500   // TODO: Any other flags to propagate?
8501   SDNodeFlags Flags;
8502   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8503 
8504   EVT InVT = Src.getValueType();
8505   EVT OutVT = Op.getValueType();
8506   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8507       isOperationCustom(Op.getOpcode(), InVT))
8508     return LowerINT_TO_FPVector(Op, DAG, dl);
8509 
8510   // Conversions to f128 are legal.
8511   if (Op.getValueType() == MVT::f128)
8512     return Subtarget.hasP9Vector() ? Op : SDValue();
8513 
8514   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8515   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8516     return SDValue();
8517 
8518   if (Src.getValueType() == MVT::i1) {
8519     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8520                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8521                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8522     if (IsStrict)
8523       return DAG.getMergeValues({Sel, Chain}, dl);
8524     else
8525       return Sel;
8526   }
8527 
8528   // If we have direct moves, we can do all the conversion, skip the store/load
8529   // however, without FPCVT we can't do most conversions.
8530   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8531       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8532     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8533 
8534   assert((IsSigned || Subtarget.hasFPCVT()) &&
8535          "UINT_TO_FP is supported only with FPCVT");
8536 
8537   if (Src.getValueType() == MVT::i64) {
8538     SDValue SINT = Src;
8539     // When converting to single-precision, we actually need to convert
8540     // to double-precision first and then round to single-precision.
8541     // To avoid double-rounding effects during that operation, we have
8542     // to prepare the input operand.  Bits that might be truncated when
8543     // converting to double-precision are replaced by a bit that won't
8544     // be lost at this stage, but is below the single-precision rounding
8545     // position.
8546     //
8547     // However, if -enable-unsafe-fp-math is in effect, accept double
8548     // rounding to avoid the extra overhead.
8549     if (Op.getValueType() == MVT::f32 &&
8550         !Subtarget.hasFPCVT() &&
8551         !DAG.getTarget().Options.UnsafeFPMath) {
8552 
8553       // Twiddle input to make sure the low 11 bits are zero.  (If this
8554       // is the case, we are guaranteed the value will fit into the 53 bit
8555       // mantissa of an IEEE double-precision value without rounding.)
8556       // If any of those low 11 bits were not zero originally, make sure
8557       // bit 12 (value 2048) is set instead, so that the final rounding
8558       // to single-precision gets the correct result.
8559       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8560                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8561       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8562                           Round, DAG.getConstant(2047, dl, MVT::i64));
8563       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8564       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8565                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8566 
8567       // However, we cannot use that value unconditionally: if the magnitude
8568       // of the input value is small, the bit-twiddling we did above might
8569       // end up visibly changing the output.  Fortunately, in that case, we
8570       // don't need to twiddle bits since the original input will convert
8571       // exactly to double-precision floating-point already.  Therefore,
8572       // construct a conditional to use the original value if the top 11
8573       // bits are all sign-bit copies, and use the rounded value computed
8574       // above otherwise.
8575       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8576                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8577       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8578                          Cond, DAG.getConstant(1, dl, MVT::i64));
8579       Cond = DAG.getSetCC(
8580           dl,
8581           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8582           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8583 
8584       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8585     }
8586 
8587     ReuseLoadInfo RLI;
8588     SDValue Bits;
8589 
8590     MachineFunction &MF = DAG.getMachineFunction();
8591     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8592       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8593                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8594       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8595     } else if (Subtarget.hasLFIWAX() &&
8596                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8597       MachineMemOperand *MMO =
8598         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8599                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8600       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8601       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8602                                      DAG.getVTList(MVT::f64, MVT::Other),
8603                                      Ops, MVT::i32, MMO);
8604       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8605     } else if (Subtarget.hasFPCVT() &&
8606                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8607       MachineMemOperand *MMO =
8608         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8609                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8610       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8611       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8612                                      DAG.getVTList(MVT::f64, MVT::Other),
8613                                      Ops, MVT::i32, MMO);
8614       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8615     } else if (((Subtarget.hasLFIWAX() &&
8616                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8617                 (Subtarget.hasFPCVT() &&
8618                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8619                SINT.getOperand(0).getValueType() == MVT::i32) {
8620       MachineFrameInfo &MFI = MF.getFrameInfo();
8621       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8622 
8623       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8624       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8625 
8626       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8627                                    MachinePointerInfo::getFixedStack(
8628                                        DAG.getMachineFunction(), FrameIdx));
8629       Chain = Store;
8630 
8631       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8632              "Expected an i32 store");
8633 
8634       RLI.Ptr = FIdx;
8635       RLI.Chain = Chain;
8636       RLI.MPI =
8637           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8638       RLI.Alignment = Align(4);
8639 
8640       MachineMemOperand *MMO =
8641         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8642                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8643       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8644       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8645                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8646                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8647                                      Ops, MVT::i32, MMO);
8648       Chain = Bits.getValue(1);
8649     } else
8650       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8651 
8652     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8653     if (IsStrict)
8654       Chain = FP.getValue(1);
8655 
8656     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8657       if (IsStrict)
8658         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8659                          DAG.getVTList(MVT::f32, MVT::Other),
8660                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8661       else
8662         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8663                          DAG.getIntPtrConstant(0, dl));
8664     }
8665     return FP;
8666   }
8667 
8668   assert(Src.getValueType() == MVT::i32 &&
8669          "Unhandled INT_TO_FP type in custom expander!");
8670   // Since we only generate this in 64-bit mode, we can take advantage of
8671   // 64-bit registers.  In particular, sign extend the input value into the
8672   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8673   // then lfd it and fcfid it.
8674   MachineFunction &MF = DAG.getMachineFunction();
8675   MachineFrameInfo &MFI = MF.getFrameInfo();
8676   EVT PtrVT = getPointerTy(MF.getDataLayout());
8677 
8678   SDValue Ld;
8679   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8680     ReuseLoadInfo RLI;
8681     bool ReusingLoad;
8682     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8683       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8684       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8685 
8686       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8687                                    MachinePointerInfo::getFixedStack(
8688                                        DAG.getMachineFunction(), FrameIdx));
8689       Chain = Store;
8690 
8691       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8692              "Expected an i32 store");
8693 
8694       RLI.Ptr = FIdx;
8695       RLI.Chain = Chain;
8696       RLI.MPI =
8697           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8698       RLI.Alignment = Align(4);
8699     }
8700 
8701     MachineMemOperand *MMO =
8702       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8703                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8704     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8705     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8706                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8707                                  MVT::i32, MMO);
8708     Chain = Ld.getValue(1);
8709     if (ReusingLoad)
8710       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8711   } else {
8712     assert(Subtarget.isPPC64() &&
8713            "i32->FP without LFIWAX supported only on PPC64");
8714 
8715     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8716     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8717 
8718     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8719 
8720     // STD the extended value into the stack slot.
8721     SDValue Store = DAG.getStore(
8722         Chain, dl, Ext64, FIdx,
8723         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8724     Chain = Store;
8725 
8726     // Load the value as a double.
8727     Ld = DAG.getLoad(
8728         MVT::f64, dl, Chain, FIdx,
8729         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8730     Chain = Ld.getValue(1);
8731   }
8732 
8733   // FCFID it and return it.
8734   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8735   if (IsStrict)
8736     Chain = FP.getValue(1);
8737   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8738     if (IsStrict)
8739       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8740                        DAG.getVTList(MVT::f32, MVT::Other),
8741                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8742     else
8743       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8744                        DAG.getIntPtrConstant(0, dl));
8745   }
8746   return FP;
8747 }
8748 
8749 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8750                                             SelectionDAG &DAG) const {
8751   SDLoc dl(Op);
8752   /*
8753    The rounding mode is in bits 30:31 of FPSR, and has the following
8754    settings:
8755      00 Round to nearest
8756      01 Round to 0
8757      10 Round to +inf
8758      11 Round to -inf
8759 
8760   FLT_ROUNDS, on the other hand, expects the following:
8761     -1 Undefined
8762      0 Round to 0
8763      1 Round to nearest
8764      2 Round to +inf
8765      3 Round to -inf
8766 
8767   To perform the conversion, we do:
8768     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8769   */
8770 
8771   MachineFunction &MF = DAG.getMachineFunction();
8772   EVT VT = Op.getValueType();
8773   EVT PtrVT = getPointerTy(MF.getDataLayout());
8774 
8775   // Save FP Control Word to register
8776   SDValue Chain = Op.getOperand(0);
8777   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8778   Chain = MFFS.getValue(1);
8779 
8780   SDValue CWD;
8781   if (isTypeLegal(MVT::i64)) {
8782     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8783                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8784   } else {
8785     // Save FP register to stack slot
8786     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8787     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8788     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8789 
8790     // Load FP Control Word from low 32 bits of stack slot.
8791     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8792            "Stack slot adjustment is valid only on big endian subtargets!");
8793     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8794     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8795     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8796     Chain = CWD.getValue(1);
8797   }
8798 
8799   // Transform as necessary
8800   SDValue CWD1 =
8801     DAG.getNode(ISD::AND, dl, MVT::i32,
8802                 CWD, DAG.getConstant(3, dl, MVT::i32));
8803   SDValue CWD2 =
8804     DAG.getNode(ISD::SRL, dl, MVT::i32,
8805                 DAG.getNode(ISD::AND, dl, MVT::i32,
8806                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8807                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8808                             DAG.getConstant(3, dl, MVT::i32)),
8809                 DAG.getConstant(1, dl, MVT::i32));
8810 
8811   SDValue RetVal =
8812     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8813 
8814   RetVal =
8815       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8816                   dl, VT, RetVal);
8817 
8818   return DAG.getMergeValues({RetVal, Chain}, dl);
8819 }
8820 
8821 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8822   EVT VT = Op.getValueType();
8823   unsigned BitWidth = VT.getSizeInBits();
8824   SDLoc dl(Op);
8825   assert(Op.getNumOperands() == 3 &&
8826          VT == Op.getOperand(1).getValueType() &&
8827          "Unexpected SHL!");
8828 
8829   // Expand into a bunch of logical ops.  Note that these ops
8830   // depend on the PPC behavior for oversized shift amounts.
8831   SDValue Lo = Op.getOperand(0);
8832   SDValue Hi = Op.getOperand(1);
8833   SDValue Amt = Op.getOperand(2);
8834   EVT AmtVT = Amt.getValueType();
8835 
8836   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8837                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8838   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8839   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8840   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8841   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8842                              DAG.getConstant(-BitWidth, dl, AmtVT));
8843   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8844   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8845   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8846   SDValue OutOps[] = { OutLo, OutHi };
8847   return DAG.getMergeValues(OutOps, dl);
8848 }
8849 
8850 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8851   EVT VT = Op.getValueType();
8852   SDLoc dl(Op);
8853   unsigned BitWidth = VT.getSizeInBits();
8854   assert(Op.getNumOperands() == 3 &&
8855          VT == Op.getOperand(1).getValueType() &&
8856          "Unexpected SRL!");
8857 
8858   // Expand into a bunch of logical ops.  Note that these ops
8859   // depend on the PPC behavior for oversized shift amounts.
8860   SDValue Lo = Op.getOperand(0);
8861   SDValue Hi = Op.getOperand(1);
8862   SDValue Amt = Op.getOperand(2);
8863   EVT AmtVT = Amt.getValueType();
8864 
8865   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8866                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8867   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8868   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8869   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8870   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8871                              DAG.getConstant(-BitWidth, dl, AmtVT));
8872   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8873   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8874   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8875   SDValue OutOps[] = { OutLo, OutHi };
8876   return DAG.getMergeValues(OutOps, dl);
8877 }
8878 
8879 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8880   SDLoc dl(Op);
8881   EVT VT = Op.getValueType();
8882   unsigned BitWidth = VT.getSizeInBits();
8883   assert(Op.getNumOperands() == 3 &&
8884          VT == Op.getOperand(1).getValueType() &&
8885          "Unexpected SRA!");
8886 
8887   // Expand into a bunch of logical ops, followed by a select_cc.
8888   SDValue Lo = Op.getOperand(0);
8889   SDValue Hi = Op.getOperand(1);
8890   SDValue Amt = Op.getOperand(2);
8891   EVT AmtVT = Amt.getValueType();
8892 
8893   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8894                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8895   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8896   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8897   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8898   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8899                              DAG.getConstant(-BitWidth, dl, AmtVT));
8900   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8901   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8902   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8903                                   Tmp4, Tmp6, ISD::SETLE);
8904   SDValue OutOps[] = { OutLo, OutHi };
8905   return DAG.getMergeValues(OutOps, dl);
8906 }
8907 
8908 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8909                                             SelectionDAG &DAG) const {
8910   SDLoc dl(Op);
8911   EVT VT = Op.getValueType();
8912   unsigned BitWidth = VT.getSizeInBits();
8913 
8914   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8915   SDValue X = Op.getOperand(0);
8916   SDValue Y = Op.getOperand(1);
8917   SDValue Z = Op.getOperand(2);
8918   EVT AmtVT = Z.getValueType();
8919 
8920   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8921   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8922   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8923   // on PowerPC shift by BW being well defined.
8924   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8925                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8926   SDValue SubZ =
8927       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8928   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8929   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8930   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8931 }
8932 
8933 //===----------------------------------------------------------------------===//
8934 // Vector related lowering.
8935 //
8936 
8937 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8938 /// element size of SplatSize. Cast the result to VT.
8939 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8940                                       SelectionDAG &DAG, const SDLoc &dl) {
8941   static const MVT VTys[] = { // canonical VT to use for each size.
8942     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8943   };
8944 
8945   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8946 
8947   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8948   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8949     SplatSize = 1;
8950     Val = 0xFF;
8951   }
8952 
8953   EVT CanonicalVT = VTys[SplatSize-1];
8954 
8955   // Build a canonical splat for this value.
8956   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8957 }
8958 
8959 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8960 /// specified intrinsic ID.
8961 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8962                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8963   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8964   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8965                      DAG.getConstant(IID, dl, MVT::i32), Op);
8966 }
8967 
8968 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8969 /// specified intrinsic ID.
8970 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8971                                 SelectionDAG &DAG, const SDLoc &dl,
8972                                 EVT DestVT = MVT::Other) {
8973   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8974   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8975                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8976 }
8977 
8978 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8979 /// specified intrinsic ID.
8980 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8981                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8982                                 EVT DestVT = MVT::Other) {
8983   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8984   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8985                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8986 }
8987 
8988 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8989 /// amount.  The result has the specified value type.
8990 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8991                            SelectionDAG &DAG, const SDLoc &dl) {
8992   // Force LHS/RHS to be the right type.
8993   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8994   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8995 
8996   int Ops[16];
8997   for (unsigned i = 0; i != 16; ++i)
8998     Ops[i] = i + Amt;
8999   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9000   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9001 }
9002 
9003 /// Do we have an efficient pattern in a .td file for this node?
9004 ///
9005 /// \param V - pointer to the BuildVectorSDNode being matched
9006 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9007 ///
9008 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9009 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9010 /// the opposite is true (expansion is beneficial) are:
9011 /// - The node builds a vector out of integers that are not 32 or 64-bits
9012 /// - The node builds a vector out of constants
9013 /// - The node is a "load-and-splat"
9014 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9015 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9016                                             bool HasDirectMove,
9017                                             bool HasP8Vector) {
9018   EVT VecVT = V->getValueType(0);
9019   bool RightType = VecVT == MVT::v2f64 ||
9020     (HasP8Vector && VecVT == MVT::v4f32) ||
9021     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9022   if (!RightType)
9023     return false;
9024 
9025   bool IsSplat = true;
9026   bool IsLoad = false;
9027   SDValue Op0 = V->getOperand(0);
9028 
9029   // This function is called in a block that confirms the node is not a constant
9030   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9031   // different constants.
9032   if (V->isConstant())
9033     return false;
9034   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9035     if (V->getOperand(i).isUndef())
9036       return false;
9037     // We want to expand nodes that represent load-and-splat even if the
9038     // loaded value is a floating point truncation or conversion to int.
9039     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9040         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9041          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9042         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9043          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9044         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9045          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9046       IsLoad = true;
9047     // If the operands are different or the input is not a load and has more
9048     // uses than just this BV node, then it isn't a splat.
9049     if (V->getOperand(i) != Op0 ||
9050         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9051       IsSplat = false;
9052   }
9053   return !(IsSplat && IsLoad);
9054 }
9055 
9056 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9057 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9058 
9059   SDLoc dl(Op);
9060   SDValue Op0 = Op->getOperand(0);
9061 
9062   if ((Op.getValueType() != MVT::f128) ||
9063       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9064       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9065       (Op0.getOperand(1).getValueType() != MVT::i64))
9066     return SDValue();
9067 
9068   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9069                      Op0.getOperand(1));
9070 }
9071 
9072 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9073   const SDValue *InputLoad = &Op;
9074   if (InputLoad->getOpcode() == ISD::BITCAST)
9075     InputLoad = &InputLoad->getOperand(0);
9076   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9077       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9078     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9079     InputLoad = &InputLoad->getOperand(0);
9080   }
9081   if (InputLoad->getOpcode() != ISD::LOAD)
9082     return nullptr;
9083   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9084   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9085 }
9086 
9087 // Convert the argument APFloat to a single precision APFloat if there is no
9088 // loss in information during the conversion to single precision APFloat and the
9089 // resulting number is not a denormal number. Return true if successful.
9090 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9091   APFloat APFloatToConvert = ArgAPFloat;
9092   bool LosesInfo = true;
9093   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9094                            &LosesInfo);
9095   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9096   if (Success)
9097     ArgAPFloat = APFloatToConvert;
9098   return Success;
9099 }
9100 
9101 // Bitcast the argument APInt to a double and convert it to a single precision
9102 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9103 // argument if there is no loss in information during the conversion from
9104 // double to single precision APFloat and the resulting number is not a denormal
9105 // number. Return true if successful.
9106 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9107   double DpValue = ArgAPInt.bitsToDouble();
9108   APFloat APFloatDp(DpValue);
9109   bool Success = convertToNonDenormSingle(APFloatDp);
9110   if (Success)
9111     ArgAPInt = APFloatDp.bitcastToAPInt();
9112   return Success;
9113 }
9114 
9115 // Nondestructive check for convertTonNonDenormSingle.
9116 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9117   // Only convert if it loses info, since XXSPLTIDP should
9118   // handle the other case.
9119   APFloat APFloatToConvert = ArgAPFloat;
9120   bool LosesInfo = true;
9121   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9122                            &LosesInfo);
9123 
9124   return (!LosesInfo && !APFloatToConvert.isDenormal());
9125 }
9126 
9127 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9128                              unsigned &Opcode) {
9129   LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9130   if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9131     return false;
9132 
9133   EVT Ty = Op->getValueType(0);
9134   // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9135   // as we cannot handle extending loads for these types.
9136   if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9137       ISD::isNON_EXTLoad(InputNode))
9138     return true;
9139 
9140   EVT MemVT = InputNode->getMemoryVT();
9141   // For v8i16 and v16i8 types, extending loads can be handled as long as the
9142   // memory VT is the same vector element VT type.
9143   // The loads feeding into the v8i16 and v16i8 types will be extending because
9144   // scalar i8/i16 are not legal types.
9145   if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9146       (MemVT == Ty.getVectorElementType()))
9147     return true;
9148 
9149   if (Ty == MVT::v2i64) {
9150     // Check the extend type, when the input type is i32, and the output vector
9151     // type is v2i64.
9152     if (MemVT == MVT::i32) {
9153       if (ISD::isZEXTLoad(InputNode))
9154         Opcode = PPCISD::ZEXT_LD_SPLAT;
9155       if (ISD::isSEXTLoad(InputNode))
9156         Opcode = PPCISD::SEXT_LD_SPLAT;
9157     }
9158     return true;
9159   }
9160   return false;
9161 }
9162 
9163 // If this is a case we can't handle, return null and let the default
9164 // expansion code take care of it.  If we CAN select this case, and if it
9165 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9166 // this case more efficiently than a constant pool load, lower it to the
9167 // sequence of ops that should be used.
9168 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9169                                              SelectionDAG &DAG) const {
9170   SDLoc dl(Op);
9171   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9172   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9173 
9174   // Check if this is a splat of a constant value.
9175   APInt APSplatBits, APSplatUndef;
9176   unsigned SplatBitSize;
9177   bool HasAnyUndefs;
9178   bool BVNIsConstantSplat =
9179       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9180                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9181 
9182   // If it is a splat of a double, check if we can shrink it to a 32 bit
9183   // non-denormal float which when converted back to double gives us the same
9184   // double. This is to exploit the XXSPLTIDP instruction.
9185   // If we lose precision, we use XXSPLTI32DX.
9186   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9187       Subtarget.hasPrefixInstrs()) {
9188     // Check the type first to short-circuit so we don't modify APSplatBits if
9189     // this block isn't executed.
9190     if ((Op->getValueType(0) == MVT::v2f64) &&
9191         convertToNonDenormSingle(APSplatBits)) {
9192       SDValue SplatNode = DAG.getNode(
9193           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9194           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9195       return DAG.getBitcast(Op.getValueType(), SplatNode);
9196     } else {
9197       // We may lose precision, so we have to use XXSPLTI32DX.
9198 
9199       uint32_t Hi =
9200           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9201       uint32_t Lo =
9202           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9203       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9204 
9205       if (!Hi || !Lo)
9206         // If either load is 0, then we should generate XXLXOR to set to 0.
9207         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9208 
9209       if (Hi)
9210         SplatNode = DAG.getNode(
9211             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9212             DAG.getTargetConstant(0, dl, MVT::i32),
9213             DAG.getTargetConstant(Hi, dl, MVT::i32));
9214 
9215       if (Lo)
9216         SplatNode =
9217             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9218                         DAG.getTargetConstant(1, dl, MVT::i32),
9219                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9220 
9221       return DAG.getBitcast(Op.getValueType(), SplatNode);
9222     }
9223   }
9224 
9225   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9226     unsigned NewOpcode = PPCISD::LD_SPLAT;
9227 
9228     // Handle load-and-splat patterns as we have instructions that will do this
9229     // in one go.
9230     if (DAG.isSplatValue(Op, true) &&
9231         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9232       const SDValue *InputLoad = &Op.getOperand(0);
9233       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9234 
9235       // If the input load is an extending load, it will be an i32 -> i64
9236       // extending load and isValidSplatLoad() will update NewOpcode.
9237       unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9238       unsigned ElementSize =
9239           MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9240 
9241       assert(((ElementSize == 2 * MemorySize)
9242                   ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9243                      NewOpcode == PPCISD::SEXT_LD_SPLAT)
9244                   : (NewOpcode == PPCISD::LD_SPLAT)) &&
9245              "Unmatched element size and opcode!\n");
9246 
9247       // Checking for a single use of this load, we have to check for vector
9248       // width (128 bits) / ElementSize uses (since each operand of the
9249       // BUILD_VECTOR is a separate use of the value.
9250       unsigned NumUsesOfInputLD = 128 / ElementSize;
9251       for (SDValue BVInOp : Op->ops())
9252         if (BVInOp.isUndef())
9253           NumUsesOfInputLD--;
9254 
9255       // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9256       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9257       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9258       // 15", but funciton IsValidSplatLoad() now will only return true when
9259       // the data at index 0 is not nullptr. So we will not get into trouble for
9260       // these cases.
9261       //
9262       // case 1 - lfiwzx/lfiwax
9263       // 1.1: load result is i32 and is sign/zero extend to i64;
9264       // 1.2: build a v2i64 vector type with above loaded value;
9265       // 1.3: the vector has only one value at index 0, others are all undef;
9266       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9267       if (NumUsesOfInputLD == 1 &&
9268           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9269            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9270            Subtarget.hasLFIWAX()))
9271         return SDValue();
9272 
9273       // case 2 - lxvr[hb]x
9274       // 2.1: load result is at most i16;
9275       // 2.2: build a vector with above loaded value;
9276       // 2.3: the vector has only one value at index 0, others are all undef;
9277       // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9278       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9279           Subtarget.isISA3_1() && ElementSize <= 16)
9280         return SDValue();
9281 
9282       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9283       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9284           Subtarget.hasVSX()) {
9285         SDValue Ops[] = {
9286           LD->getChain(),    // Chain
9287           LD->getBasePtr(),  // Ptr
9288           DAG.getValueType(Op.getValueType()) // VT
9289         };
9290         SDValue LdSplt = DAG.getMemIntrinsicNode(
9291             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9292             LD->getMemoryVT(), LD->getMemOperand());
9293         // Replace all uses of the output chain of the original load with the
9294         // output chain of the new load.
9295         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9296                                       LdSplt.getValue(1));
9297         return LdSplt;
9298       }
9299     }
9300 
9301     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9302     // 32-bits can be lowered to VSX instructions under certain conditions.
9303     // Without VSX, there is no pattern more efficient than expanding the node.
9304     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9305         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9306                                         Subtarget.hasP8Vector()))
9307       return Op;
9308     return SDValue();
9309   }
9310 
9311   uint64_t SplatBits = APSplatBits.getZExtValue();
9312   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9313   unsigned SplatSize = SplatBitSize / 8;
9314 
9315   // First, handle single instruction cases.
9316 
9317   // All zeros?
9318   if (SplatBits == 0) {
9319     // Canonicalize all zero vectors to be v4i32.
9320     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9321       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9322       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9323     }
9324     return Op;
9325   }
9326 
9327   // We have XXSPLTIW for constant splats four bytes wide.
9328   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9329   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9330   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9331   // turned into a 4-byte splat of 0xABABABAB.
9332   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9333     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9334                                   Op.getValueType(), DAG, dl);
9335 
9336   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9337     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9338                                   dl);
9339 
9340   // We have XXSPLTIB for constant splats one byte wide.
9341   if (Subtarget.hasP9Vector() && SplatSize == 1)
9342     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9343                                   dl);
9344 
9345   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9346   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9347                     (32-SplatBitSize));
9348   if (SextVal >= -16 && SextVal <= 15)
9349     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9350                                   dl);
9351 
9352   // Two instruction sequences.
9353 
9354   // If this value is in the range [-32,30] and is even, use:
9355   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9356   // If this value is in the range [17,31] and is odd, use:
9357   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9358   // If this value is in the range [-31,-17] and is odd, use:
9359   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9360   // Note the last two are three-instruction sequences.
9361   if (SextVal >= -32 && SextVal <= 31) {
9362     // To avoid having these optimizations undone by constant folding,
9363     // we convert to a pseudo that will be expanded later into one of
9364     // the above forms.
9365     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9366     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9367               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9368     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9369     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9370     if (VT == Op.getValueType())
9371       return RetVal;
9372     else
9373       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9374   }
9375 
9376   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9377   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9378   // for fneg/fabs.
9379   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9380     // Make -1 and vspltisw -1:
9381     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9382 
9383     // Make the VSLW intrinsic, computing 0x8000_0000.
9384     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9385                                    OnesV, DAG, dl);
9386 
9387     // xor by OnesV to invert it.
9388     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9389     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9390   }
9391 
9392   // Check to see if this is a wide variety of vsplti*, binop self cases.
9393   static const signed char SplatCsts[] = {
9394     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9395     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9396   };
9397 
9398   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9399     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9400     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9401     int i = SplatCsts[idx];
9402 
9403     // Figure out what shift amount will be used by altivec if shifted by i in
9404     // this splat size.
9405     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9406 
9407     // vsplti + shl self.
9408     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9409       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9410       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9411         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9412         Intrinsic::ppc_altivec_vslw
9413       };
9414       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9415       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9416     }
9417 
9418     // vsplti + srl self.
9419     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9420       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9421       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9422         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9423         Intrinsic::ppc_altivec_vsrw
9424       };
9425       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9426       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9427     }
9428 
9429     // vsplti + rol self.
9430     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9431                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9432       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9433       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9434         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9435         Intrinsic::ppc_altivec_vrlw
9436       };
9437       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9438       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9439     }
9440 
9441     // t = vsplti c, result = vsldoi t, t, 1
9442     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9443       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9444       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9445       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9446     }
9447     // t = vsplti c, result = vsldoi t, t, 2
9448     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9449       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9450       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9451       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9452     }
9453     // t = vsplti c, result = vsldoi t, t, 3
9454     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9455       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9456       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9457       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9458     }
9459   }
9460 
9461   return SDValue();
9462 }
9463 
9464 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9465 /// the specified operations to build the shuffle.
9466 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9467                                       SDValue RHS, SelectionDAG &DAG,
9468                                       const SDLoc &dl) {
9469   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9470   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9471   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9472 
9473   enum {
9474     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9475     OP_VMRGHW,
9476     OP_VMRGLW,
9477     OP_VSPLTISW0,
9478     OP_VSPLTISW1,
9479     OP_VSPLTISW2,
9480     OP_VSPLTISW3,
9481     OP_VSLDOI4,
9482     OP_VSLDOI8,
9483     OP_VSLDOI12
9484   };
9485 
9486   if (OpNum == OP_COPY) {
9487     if (LHSID == (1*9+2)*9+3) return LHS;
9488     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9489     return RHS;
9490   }
9491 
9492   SDValue OpLHS, OpRHS;
9493   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9494   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9495 
9496   int ShufIdxs[16];
9497   switch (OpNum) {
9498   default: llvm_unreachable("Unknown i32 permute!");
9499   case OP_VMRGHW:
9500     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9501     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9502     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9503     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9504     break;
9505   case OP_VMRGLW:
9506     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9507     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9508     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9509     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9510     break;
9511   case OP_VSPLTISW0:
9512     for (unsigned i = 0; i != 16; ++i)
9513       ShufIdxs[i] = (i&3)+0;
9514     break;
9515   case OP_VSPLTISW1:
9516     for (unsigned i = 0; i != 16; ++i)
9517       ShufIdxs[i] = (i&3)+4;
9518     break;
9519   case OP_VSPLTISW2:
9520     for (unsigned i = 0; i != 16; ++i)
9521       ShufIdxs[i] = (i&3)+8;
9522     break;
9523   case OP_VSPLTISW3:
9524     for (unsigned i = 0; i != 16; ++i)
9525       ShufIdxs[i] = (i&3)+12;
9526     break;
9527   case OP_VSLDOI4:
9528     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9529   case OP_VSLDOI8:
9530     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9531   case OP_VSLDOI12:
9532     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9533   }
9534   EVT VT = OpLHS.getValueType();
9535   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9536   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9537   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9538   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9539 }
9540 
9541 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9542 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9543 /// SDValue.
9544 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9545                                            SelectionDAG &DAG) const {
9546   const unsigned BytesInVector = 16;
9547   bool IsLE = Subtarget.isLittleEndian();
9548   SDLoc dl(N);
9549   SDValue V1 = N->getOperand(0);
9550   SDValue V2 = N->getOperand(1);
9551   unsigned ShiftElts = 0, InsertAtByte = 0;
9552   bool Swap = false;
9553 
9554   // Shifts required to get the byte we want at element 7.
9555   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9556                                    0, 15, 14, 13, 12, 11, 10, 9};
9557   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9558                                 1, 2,  3,  4,  5,  6,  7,  8};
9559 
9560   ArrayRef<int> Mask = N->getMask();
9561   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9562 
9563   // For each mask element, find out if we're just inserting something
9564   // from V2 into V1 or vice versa.
9565   // Possible permutations inserting an element from V2 into V1:
9566   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9567   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9568   //   ...
9569   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9570   // Inserting from V1 into V2 will be similar, except mask range will be
9571   // [16,31].
9572 
9573   bool FoundCandidate = false;
9574   // If both vector operands for the shuffle are the same vector, the mask
9575   // will contain only elements from the first one and the second one will be
9576   // undef.
9577   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9578   // Go through the mask of half-words to find an element that's being moved
9579   // from one vector to the other.
9580   for (unsigned i = 0; i < BytesInVector; ++i) {
9581     unsigned CurrentElement = Mask[i];
9582     // If 2nd operand is undefined, we should only look for element 7 in the
9583     // Mask.
9584     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9585       continue;
9586 
9587     bool OtherElementsInOrder = true;
9588     // Examine the other elements in the Mask to see if they're in original
9589     // order.
9590     for (unsigned j = 0; j < BytesInVector; ++j) {
9591       if (j == i)
9592         continue;
9593       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9594       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9595       // in which we always assume we're always picking from the 1st operand.
9596       int MaskOffset =
9597           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9598       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9599         OtherElementsInOrder = false;
9600         break;
9601       }
9602     }
9603     // If other elements are in original order, we record the number of shifts
9604     // we need to get the element we want into element 7. Also record which byte
9605     // in the vector we should insert into.
9606     if (OtherElementsInOrder) {
9607       // If 2nd operand is undefined, we assume no shifts and no swapping.
9608       if (V2.isUndef()) {
9609         ShiftElts = 0;
9610         Swap = false;
9611       } else {
9612         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9613         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9614                          : BigEndianShifts[CurrentElement & 0xF];
9615         Swap = CurrentElement < BytesInVector;
9616       }
9617       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9618       FoundCandidate = true;
9619       break;
9620     }
9621   }
9622 
9623   if (!FoundCandidate)
9624     return SDValue();
9625 
9626   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9627   // optionally with VECSHL if shift is required.
9628   if (Swap)
9629     std::swap(V1, V2);
9630   if (V2.isUndef())
9631     V2 = V1;
9632   if (ShiftElts) {
9633     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9634                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9635     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9636                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9637   }
9638   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9639                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9640 }
9641 
9642 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9643 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9644 /// SDValue.
9645 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9646                                            SelectionDAG &DAG) const {
9647   const unsigned NumHalfWords = 8;
9648   const unsigned BytesInVector = NumHalfWords * 2;
9649   // Check that the shuffle is on half-words.
9650   if (!isNByteElemShuffleMask(N, 2, 1))
9651     return SDValue();
9652 
9653   bool IsLE = Subtarget.isLittleEndian();
9654   SDLoc dl(N);
9655   SDValue V1 = N->getOperand(0);
9656   SDValue V2 = N->getOperand(1);
9657   unsigned ShiftElts = 0, InsertAtByte = 0;
9658   bool Swap = false;
9659 
9660   // Shifts required to get the half-word we want at element 3.
9661   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9662   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9663 
9664   uint32_t Mask = 0;
9665   uint32_t OriginalOrderLow = 0x1234567;
9666   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9667   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9668   // 32-bit space, only need 4-bit nibbles per element.
9669   for (unsigned i = 0; i < NumHalfWords; ++i) {
9670     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9671     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9672   }
9673 
9674   // For each mask element, find out if we're just inserting something
9675   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9676   // from V2 into V1:
9677   //   X, 1, 2, 3, 4, 5, 6, 7
9678   //   0, X, 2, 3, 4, 5, 6, 7
9679   //   0, 1, X, 3, 4, 5, 6, 7
9680   //   0, 1, 2, X, 4, 5, 6, 7
9681   //   0, 1, 2, 3, X, 5, 6, 7
9682   //   0, 1, 2, 3, 4, X, 6, 7
9683   //   0, 1, 2, 3, 4, 5, X, 7
9684   //   0, 1, 2, 3, 4, 5, 6, X
9685   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9686 
9687   bool FoundCandidate = false;
9688   // Go through the mask of half-words to find an element that's being moved
9689   // from one vector to the other.
9690   for (unsigned i = 0; i < NumHalfWords; ++i) {
9691     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9692     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9693     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9694     uint32_t TargetOrder = 0x0;
9695 
9696     // If both vector operands for the shuffle are the same vector, the mask
9697     // will contain only elements from the first one and the second one will be
9698     // undef.
9699     if (V2.isUndef()) {
9700       ShiftElts = 0;
9701       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9702       TargetOrder = OriginalOrderLow;
9703       Swap = false;
9704       // Skip if not the correct element or mask of other elements don't equal
9705       // to our expected order.
9706       if (MaskOneElt == VINSERTHSrcElem &&
9707           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9708         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9709         FoundCandidate = true;
9710         break;
9711       }
9712     } else { // If both operands are defined.
9713       // Target order is [8,15] if the current mask is between [0,7].
9714       TargetOrder =
9715           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9716       // Skip if mask of other elements don't equal our expected order.
9717       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9718         // We only need the last 3 bits for the number of shifts.
9719         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9720                          : BigEndianShifts[MaskOneElt & 0x7];
9721         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9722         Swap = MaskOneElt < NumHalfWords;
9723         FoundCandidate = true;
9724         break;
9725       }
9726     }
9727   }
9728 
9729   if (!FoundCandidate)
9730     return SDValue();
9731 
9732   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9733   // optionally with VECSHL if shift is required.
9734   if (Swap)
9735     std::swap(V1, V2);
9736   if (V2.isUndef())
9737     V2 = V1;
9738   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9739   if (ShiftElts) {
9740     // Double ShiftElts because we're left shifting on v16i8 type.
9741     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9742                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9743     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9744     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9745                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9746     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9747   }
9748   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9749   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9750                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9751   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9752 }
9753 
9754 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9755 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9756 /// return the default SDValue.
9757 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9758                                               SelectionDAG &DAG) const {
9759   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9760   // to v16i8. Peek through the bitcasts to get the actual operands.
9761   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9762   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9763 
9764   auto ShuffleMask = SVN->getMask();
9765   SDValue VecShuffle(SVN, 0);
9766   SDLoc DL(SVN);
9767 
9768   // Check that we have a four byte shuffle.
9769   if (!isNByteElemShuffleMask(SVN, 4, 1))
9770     return SDValue();
9771 
9772   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9773   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9774     std::swap(LHS, RHS);
9775     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9776     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9777   }
9778 
9779   // Ensure that the RHS is a vector of constants.
9780   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9781   if (!BVN)
9782     return SDValue();
9783 
9784   // Check if RHS is a splat of 4-bytes (or smaller).
9785   APInt APSplatValue, APSplatUndef;
9786   unsigned SplatBitSize;
9787   bool HasAnyUndefs;
9788   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9789                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9790       SplatBitSize > 32)
9791     return SDValue();
9792 
9793   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9794   // The instruction splats a constant C into two words of the source vector
9795   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9796   // Thus we check that the shuffle mask is the equivalent  of
9797   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9798   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9799   // within each word are consecutive, so we only need to check the first byte.
9800   SDValue Index;
9801   bool IsLE = Subtarget.isLittleEndian();
9802   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9803       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9804        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9805     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9806   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9807            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9808             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9809     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9810   else
9811     return SDValue();
9812 
9813   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9814   // for XXSPLTI32DX.
9815   unsigned SplatVal = APSplatValue.getZExtValue();
9816   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9817     SplatVal |= (SplatVal << SplatBitSize);
9818 
9819   SDValue SplatNode = DAG.getNode(
9820       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9821       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9822   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9823 }
9824 
9825 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9826 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9827 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9828 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9829 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9830   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9831   assert(Op.getValueType() == MVT::v1i128 &&
9832          "Only set v1i128 as custom, other type shouldn't reach here!");
9833   SDLoc dl(Op);
9834   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9835   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9836   unsigned SHLAmt = N1.getConstantOperandVal(0);
9837   if (SHLAmt % 8 == 0) {
9838     std::array<int, 16> Mask;
9839     std::iota(Mask.begin(), Mask.end(), 0);
9840     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9841     if (SDValue Shuffle =
9842             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9843                                  DAG.getUNDEF(MVT::v16i8), Mask))
9844       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9845   }
9846   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9847   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9848                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9849   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9850                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9851   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9852   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9853 }
9854 
9855 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9856 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9857 /// return the code it can be lowered into.  Worst case, it can always be
9858 /// lowered into a vperm.
9859 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9860                                                SelectionDAG &DAG) const {
9861   SDLoc dl(Op);
9862   SDValue V1 = Op.getOperand(0);
9863   SDValue V2 = Op.getOperand(1);
9864   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9865 
9866   // Any nodes that were combined in the target-independent combiner prior
9867   // to vector legalization will not be sent to the target combine. Try to
9868   // combine it here.
9869   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9870     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9871       return NewShuffle;
9872     Op = NewShuffle;
9873     SVOp = cast<ShuffleVectorSDNode>(Op);
9874     V1 = Op.getOperand(0);
9875     V2 = Op.getOperand(1);
9876   }
9877   EVT VT = Op.getValueType();
9878   bool isLittleEndian = Subtarget.isLittleEndian();
9879 
9880   unsigned ShiftElts, InsertAtByte;
9881   bool Swap = false;
9882 
9883   // If this is a load-and-splat, we can do that with a single instruction
9884   // in some cases. However if the load has multiple uses, we don't want to
9885   // combine it because that will just produce multiple loads.
9886   bool IsPermutedLoad = false;
9887   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9888   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9889       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9890       InputLoad->hasOneUse()) {
9891     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9892     int SplatIdx =
9893       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9894 
9895     // The splat index for permuted loads will be in the left half of the vector
9896     // which is strictly wider than the loaded value by 8 bytes. So we need to
9897     // adjust the splat index to point to the correct address in memory.
9898     if (IsPermutedLoad) {
9899       assert((isLittleEndian || IsFourByte) &&
9900              "Unexpected size for permuted load on big endian target");
9901       SplatIdx += IsFourByte ? 2 : 1;
9902       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9903              "Splat of a value outside of the loaded memory");
9904     }
9905 
9906     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9907     // For 4-byte load-and-splat, we need Power9.
9908     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9909       uint64_t Offset = 0;
9910       if (IsFourByte)
9911         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9912       else
9913         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9914 
9915       // If the width of the load is the same as the width of the splat,
9916       // loading with an offset would load the wrong memory.
9917       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9918         Offset = 0;
9919 
9920       SDValue BasePtr = LD->getBasePtr();
9921       if (Offset != 0)
9922         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9923                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9924       SDValue Ops[] = {
9925         LD->getChain(),    // Chain
9926         BasePtr,           // BasePtr
9927         DAG.getValueType(Op.getValueType()) // VT
9928       };
9929       SDVTList VTL =
9930         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9931       SDValue LdSplt =
9932         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9933                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9934       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9935       if (LdSplt.getValueType() != SVOp->getValueType(0))
9936         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9937       return LdSplt;
9938     }
9939   }
9940 
9941   // All v2i64 and v2f64 shuffles are legal
9942   if (VT == MVT::v2i64 || VT == MVT::v2f64)
9943     return Op;
9944 
9945   if (Subtarget.hasP9Vector() &&
9946       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9947                            isLittleEndian)) {
9948     if (Swap)
9949       std::swap(V1, V2);
9950     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9951     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9952     if (ShiftElts) {
9953       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9954                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9955       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9956                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9957       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9958     }
9959     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9960                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9961     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9962   }
9963 
9964   if (Subtarget.hasPrefixInstrs()) {
9965     SDValue SplatInsertNode;
9966     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9967       return SplatInsertNode;
9968   }
9969 
9970   if (Subtarget.hasP9Altivec()) {
9971     SDValue NewISDNode;
9972     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9973       return NewISDNode;
9974 
9975     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9976       return NewISDNode;
9977   }
9978 
9979   if (Subtarget.hasVSX() &&
9980       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9981     if (Swap)
9982       std::swap(V1, V2);
9983     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9984     SDValue Conv2 =
9985         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9986 
9987     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9988                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9989     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9990   }
9991 
9992   if (Subtarget.hasVSX() &&
9993     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9994     if (Swap)
9995       std::swap(V1, V2);
9996     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9997     SDValue Conv2 =
9998         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9999 
10000     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10001                               DAG.getConstant(ShiftElts, dl, MVT::i32));
10002     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10003   }
10004 
10005   if (Subtarget.hasP9Vector()) {
10006      if (PPC::isXXBRHShuffleMask(SVOp)) {
10007       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10008       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10009       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10010     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10011       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10012       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10013       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10014     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10015       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10016       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10017       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10018     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10019       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10020       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10021       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10022     }
10023   }
10024 
10025   if (Subtarget.hasVSX()) {
10026     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10027       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10028 
10029       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10030       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10031                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10032       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10033     }
10034 
10035     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10036     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10037       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10038       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10039       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10040     }
10041   }
10042 
10043   // Cases that are handled by instructions that take permute immediates
10044   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10045   // selected by the instruction selector.
10046   if (V2.isUndef()) {
10047     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10048         PPC::isSplatShuffleMask(SVOp, 2) ||
10049         PPC::isSplatShuffleMask(SVOp, 4) ||
10050         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10051         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10052         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10053         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10054         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10055         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10056         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10057         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10058         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10059         (Subtarget.hasP8Altivec() && (
10060          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10061          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10062          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10063       return Op;
10064     }
10065   }
10066 
10067   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10068   // and produce a fixed permutation.  If any of these match, do not lower to
10069   // VPERM.
10070   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10071   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10072       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10073       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10074       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10075       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10076       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10077       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10078       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10079       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10080       (Subtarget.hasP8Altivec() && (
10081        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10082        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10083        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10084     return Op;
10085 
10086   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10087   // perfect shuffle table to emit an optimal matching sequence.
10088   ArrayRef<int> PermMask = SVOp->getMask();
10089 
10090   if (!DisablePerfectShuffle && !isLittleEndian) {
10091     unsigned PFIndexes[4];
10092     bool isFourElementShuffle = true;
10093     for (unsigned i = 0; i != 4 && isFourElementShuffle;
10094          ++i) {                           // Element number
10095       unsigned EltNo = 8;                 // Start out undef.
10096       for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10097         if (PermMask[i * 4 + j] < 0)
10098           continue; // Undef, ignore it.
10099 
10100         unsigned ByteSource = PermMask[i * 4 + j];
10101         if ((ByteSource & 3) != j) {
10102           isFourElementShuffle = false;
10103           break;
10104         }
10105 
10106         if (EltNo == 8) {
10107           EltNo = ByteSource / 4;
10108         } else if (EltNo != ByteSource / 4) {
10109           isFourElementShuffle = false;
10110           break;
10111         }
10112       }
10113       PFIndexes[i] = EltNo;
10114     }
10115 
10116     // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10117     // perfect shuffle vector to determine if it is cost effective to do this as
10118     // discrete instructions, or whether we should use a vperm.
10119     // For now, we skip this for little endian until such time as we have a
10120     // little-endian perfect shuffle table.
10121     if (isFourElementShuffle) {
10122       // Compute the index in the perfect shuffle table.
10123       unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10124                               PFIndexes[2] * 9 + PFIndexes[3];
10125 
10126       unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10127       unsigned Cost = (PFEntry >> 30);
10128 
10129       // Determining when to avoid vperm is tricky.  Many things affect the cost
10130       // of vperm, particularly how many times the perm mask needs to be
10131       // computed. For example, if the perm mask can be hoisted out of a loop or
10132       // is already used (perhaps because there are multiple permutes with the
10133       // same shuffle mask?) the vperm has a cost of 1.  OTOH, hoisting the
10134       // permute mask out of the loop requires an extra register.
10135       //
10136       // As a compromise, we only emit discrete instructions if the shuffle can
10137       // be generated in 3 or fewer operations.  When we have loop information
10138       // available, if this block is within a loop, we should avoid using vperm
10139       // for 3-operation perms and use a constant pool load instead.
10140       if (Cost < 3)
10141         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10142     }
10143   }
10144 
10145   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10146   // vector that will get spilled to the constant pool.
10147   if (V2.isUndef()) V2 = V1;
10148 
10149   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10150   // that it is in input element units, not in bytes.  Convert now.
10151 
10152   // For little endian, the order of the input vectors is reversed, and
10153   // the permutation mask is complemented with respect to 31.  This is
10154   // necessary to produce proper semantics with the big-endian-biased vperm
10155   // instruction.
10156   EVT EltVT = V1.getValueType().getVectorElementType();
10157   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10158 
10159   SmallVector<SDValue, 16> ResultMask;
10160   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10161     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10162 
10163     for (unsigned j = 0; j != BytesPerElement; ++j)
10164       if (isLittleEndian)
10165         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10166                                              dl, MVT::i32));
10167       else
10168         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10169                                              MVT::i32));
10170   }
10171 
10172   ShufflesHandledWithVPERM++;
10173   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10174   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10175   LLVM_DEBUG(SVOp->dump());
10176   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10177   LLVM_DEBUG(VPermMask.dump());
10178 
10179   if (isLittleEndian)
10180     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10181                        V2, V1, VPermMask);
10182   else
10183     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10184                        V1, V2, VPermMask);
10185 }
10186 
10187 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10188 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10189 /// information about the intrinsic.
10190 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10191                                  bool &isDot, const PPCSubtarget &Subtarget) {
10192   unsigned IntrinsicID =
10193       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10194   CompareOpc = -1;
10195   isDot = false;
10196   switch (IntrinsicID) {
10197   default:
10198     return false;
10199   // Comparison predicates.
10200   case Intrinsic::ppc_altivec_vcmpbfp_p:
10201     CompareOpc = 966;
10202     isDot = true;
10203     break;
10204   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10205     CompareOpc = 198;
10206     isDot = true;
10207     break;
10208   case Intrinsic::ppc_altivec_vcmpequb_p:
10209     CompareOpc = 6;
10210     isDot = true;
10211     break;
10212   case Intrinsic::ppc_altivec_vcmpequh_p:
10213     CompareOpc = 70;
10214     isDot = true;
10215     break;
10216   case Intrinsic::ppc_altivec_vcmpequw_p:
10217     CompareOpc = 134;
10218     isDot = true;
10219     break;
10220   case Intrinsic::ppc_altivec_vcmpequd_p:
10221     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10222       CompareOpc = 199;
10223       isDot = true;
10224     } else
10225       return false;
10226     break;
10227   case Intrinsic::ppc_altivec_vcmpneb_p:
10228   case Intrinsic::ppc_altivec_vcmpneh_p:
10229   case Intrinsic::ppc_altivec_vcmpnew_p:
10230   case Intrinsic::ppc_altivec_vcmpnezb_p:
10231   case Intrinsic::ppc_altivec_vcmpnezh_p:
10232   case Intrinsic::ppc_altivec_vcmpnezw_p:
10233     if (Subtarget.hasP9Altivec()) {
10234       switch (IntrinsicID) {
10235       default:
10236         llvm_unreachable("Unknown comparison intrinsic.");
10237       case Intrinsic::ppc_altivec_vcmpneb_p:
10238         CompareOpc = 7;
10239         break;
10240       case Intrinsic::ppc_altivec_vcmpneh_p:
10241         CompareOpc = 71;
10242         break;
10243       case Intrinsic::ppc_altivec_vcmpnew_p:
10244         CompareOpc = 135;
10245         break;
10246       case Intrinsic::ppc_altivec_vcmpnezb_p:
10247         CompareOpc = 263;
10248         break;
10249       case Intrinsic::ppc_altivec_vcmpnezh_p:
10250         CompareOpc = 327;
10251         break;
10252       case Intrinsic::ppc_altivec_vcmpnezw_p:
10253         CompareOpc = 391;
10254         break;
10255       }
10256       isDot = true;
10257     } else
10258       return false;
10259     break;
10260   case Intrinsic::ppc_altivec_vcmpgefp_p:
10261     CompareOpc = 454;
10262     isDot = true;
10263     break;
10264   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10265     CompareOpc = 710;
10266     isDot = true;
10267     break;
10268   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10269     CompareOpc = 774;
10270     isDot = true;
10271     break;
10272   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10273     CompareOpc = 838;
10274     isDot = true;
10275     break;
10276   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10277     CompareOpc = 902;
10278     isDot = true;
10279     break;
10280   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10281     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10282       CompareOpc = 967;
10283       isDot = true;
10284     } else
10285       return false;
10286     break;
10287   case Intrinsic::ppc_altivec_vcmpgtub_p:
10288     CompareOpc = 518;
10289     isDot = true;
10290     break;
10291   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10292     CompareOpc = 582;
10293     isDot = true;
10294     break;
10295   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10296     CompareOpc = 646;
10297     isDot = true;
10298     break;
10299   case Intrinsic::ppc_altivec_vcmpgtud_p:
10300     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10301       CompareOpc = 711;
10302       isDot = true;
10303     } else
10304       return false;
10305     break;
10306 
10307   case Intrinsic::ppc_altivec_vcmpequq:
10308   case Intrinsic::ppc_altivec_vcmpgtsq:
10309   case Intrinsic::ppc_altivec_vcmpgtuq:
10310     if (!Subtarget.isISA3_1())
10311       return false;
10312     switch (IntrinsicID) {
10313     default:
10314       llvm_unreachable("Unknown comparison intrinsic.");
10315     case Intrinsic::ppc_altivec_vcmpequq:
10316       CompareOpc = 455;
10317       break;
10318     case Intrinsic::ppc_altivec_vcmpgtsq:
10319       CompareOpc = 903;
10320       break;
10321     case Intrinsic::ppc_altivec_vcmpgtuq:
10322       CompareOpc = 647;
10323       break;
10324     }
10325     break;
10326 
10327   // VSX predicate comparisons use the same infrastructure
10328   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10329   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10330   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10331   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10332   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10333   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10334     if (Subtarget.hasVSX()) {
10335       switch (IntrinsicID) {
10336       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10337         CompareOpc = 99;
10338         break;
10339       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10340         CompareOpc = 115;
10341         break;
10342       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10343         CompareOpc = 107;
10344         break;
10345       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10346         CompareOpc = 67;
10347         break;
10348       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10349         CompareOpc = 83;
10350         break;
10351       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10352         CompareOpc = 75;
10353         break;
10354       }
10355       isDot = true;
10356     } else
10357       return false;
10358     break;
10359 
10360   // Normal Comparisons.
10361   case Intrinsic::ppc_altivec_vcmpbfp:
10362     CompareOpc = 966;
10363     break;
10364   case Intrinsic::ppc_altivec_vcmpeqfp:
10365     CompareOpc = 198;
10366     break;
10367   case Intrinsic::ppc_altivec_vcmpequb:
10368     CompareOpc = 6;
10369     break;
10370   case Intrinsic::ppc_altivec_vcmpequh:
10371     CompareOpc = 70;
10372     break;
10373   case Intrinsic::ppc_altivec_vcmpequw:
10374     CompareOpc = 134;
10375     break;
10376   case Intrinsic::ppc_altivec_vcmpequd:
10377     if (Subtarget.hasP8Altivec())
10378       CompareOpc = 199;
10379     else
10380       return false;
10381     break;
10382   case Intrinsic::ppc_altivec_vcmpneb:
10383   case Intrinsic::ppc_altivec_vcmpneh:
10384   case Intrinsic::ppc_altivec_vcmpnew:
10385   case Intrinsic::ppc_altivec_vcmpnezb:
10386   case Intrinsic::ppc_altivec_vcmpnezh:
10387   case Intrinsic::ppc_altivec_vcmpnezw:
10388     if (Subtarget.hasP9Altivec())
10389       switch (IntrinsicID) {
10390       default:
10391         llvm_unreachable("Unknown comparison intrinsic.");
10392       case Intrinsic::ppc_altivec_vcmpneb:
10393         CompareOpc = 7;
10394         break;
10395       case Intrinsic::ppc_altivec_vcmpneh:
10396         CompareOpc = 71;
10397         break;
10398       case Intrinsic::ppc_altivec_vcmpnew:
10399         CompareOpc = 135;
10400         break;
10401       case Intrinsic::ppc_altivec_vcmpnezb:
10402         CompareOpc = 263;
10403         break;
10404       case Intrinsic::ppc_altivec_vcmpnezh:
10405         CompareOpc = 327;
10406         break;
10407       case Intrinsic::ppc_altivec_vcmpnezw:
10408         CompareOpc = 391;
10409         break;
10410       }
10411     else
10412       return false;
10413     break;
10414   case Intrinsic::ppc_altivec_vcmpgefp:
10415     CompareOpc = 454;
10416     break;
10417   case Intrinsic::ppc_altivec_vcmpgtfp:
10418     CompareOpc = 710;
10419     break;
10420   case Intrinsic::ppc_altivec_vcmpgtsb:
10421     CompareOpc = 774;
10422     break;
10423   case Intrinsic::ppc_altivec_vcmpgtsh:
10424     CompareOpc = 838;
10425     break;
10426   case Intrinsic::ppc_altivec_vcmpgtsw:
10427     CompareOpc = 902;
10428     break;
10429   case Intrinsic::ppc_altivec_vcmpgtsd:
10430     if (Subtarget.hasP8Altivec())
10431       CompareOpc = 967;
10432     else
10433       return false;
10434     break;
10435   case Intrinsic::ppc_altivec_vcmpgtub:
10436     CompareOpc = 518;
10437     break;
10438   case Intrinsic::ppc_altivec_vcmpgtuh:
10439     CompareOpc = 582;
10440     break;
10441   case Intrinsic::ppc_altivec_vcmpgtuw:
10442     CompareOpc = 646;
10443     break;
10444   case Intrinsic::ppc_altivec_vcmpgtud:
10445     if (Subtarget.hasP8Altivec())
10446       CompareOpc = 711;
10447     else
10448       return false;
10449     break;
10450   case Intrinsic::ppc_altivec_vcmpequq_p:
10451   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10452   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10453     if (!Subtarget.isISA3_1())
10454       return false;
10455     switch (IntrinsicID) {
10456     default:
10457       llvm_unreachable("Unknown comparison intrinsic.");
10458     case Intrinsic::ppc_altivec_vcmpequq_p:
10459       CompareOpc = 455;
10460       break;
10461     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10462       CompareOpc = 903;
10463       break;
10464     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10465       CompareOpc = 647;
10466       break;
10467     }
10468     isDot = true;
10469     break;
10470   }
10471   return true;
10472 }
10473 
10474 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10475 /// lower, do it, otherwise return null.
10476 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10477                                                    SelectionDAG &DAG) const {
10478   unsigned IntrinsicID =
10479     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10480 
10481   SDLoc dl(Op);
10482 
10483   switch (IntrinsicID) {
10484   case Intrinsic::thread_pointer:
10485     // Reads the thread pointer register, used for __builtin_thread_pointer.
10486     if (Subtarget.isPPC64())
10487       return DAG.getRegister(PPC::X13, MVT::i64);
10488     return DAG.getRegister(PPC::R2, MVT::i32);
10489 
10490   case Intrinsic::ppc_mma_disassemble_acc:
10491   case Intrinsic::ppc_vsx_disassemble_pair: {
10492     int NumVecs = 2;
10493     SDValue WideVec = Op.getOperand(1);
10494     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10495       NumVecs = 4;
10496       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10497     }
10498     SmallVector<SDValue, 4> RetOps;
10499     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10500       SDValue Extract = DAG.getNode(
10501           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10502           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10503                                                      : VecNo,
10504                           dl, getPointerTy(DAG.getDataLayout())));
10505       RetOps.push_back(Extract);
10506     }
10507     return DAG.getMergeValues(RetOps, dl);
10508   }
10509 
10510   case Intrinsic::ppc_unpack_longdouble: {
10511     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10512     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10513            "Argument of long double unpack must be 0 or 1!");
10514     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10515                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10516                                        Idx->getValueType(0)));
10517   }
10518 
10519   case Intrinsic::ppc_compare_exp_lt:
10520   case Intrinsic::ppc_compare_exp_gt:
10521   case Intrinsic::ppc_compare_exp_eq:
10522   case Intrinsic::ppc_compare_exp_uo: {
10523     unsigned Pred;
10524     switch (IntrinsicID) {
10525     case Intrinsic::ppc_compare_exp_lt:
10526       Pred = PPC::PRED_LT;
10527       break;
10528     case Intrinsic::ppc_compare_exp_gt:
10529       Pred = PPC::PRED_GT;
10530       break;
10531     case Intrinsic::ppc_compare_exp_eq:
10532       Pred = PPC::PRED_EQ;
10533       break;
10534     case Intrinsic::ppc_compare_exp_uo:
10535       Pred = PPC::PRED_UN;
10536       break;
10537     }
10538     return SDValue(
10539         DAG.getMachineNode(
10540             PPC::SELECT_CC_I4, dl, MVT::i32,
10541             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10542                                         Op.getOperand(1), Op.getOperand(2)),
10543                      0),
10544              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10545              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10546         0);
10547   }
10548   case Intrinsic::ppc_test_data_class_d:
10549   case Intrinsic::ppc_test_data_class_f: {
10550     unsigned CmprOpc = PPC::XSTSTDCDP;
10551     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10552       CmprOpc = PPC::XSTSTDCSP;
10553     return SDValue(
10554         DAG.getMachineNode(
10555             PPC::SELECT_CC_I4, dl, MVT::i32,
10556             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10557                                         Op.getOperand(1)),
10558                      0),
10559              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10560              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10561         0);
10562   }
10563   case Intrinsic::ppc_fnmsub: {
10564     EVT VT = Op.getOperand(1).getValueType();
10565     if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
10566       return DAG.getNode(
10567           ISD::FNEG, dl, VT,
10568           DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
10569                       DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
10570     return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
10571                        Op.getOperand(2), Op.getOperand(3));
10572   }
10573   case Intrinsic::ppc_convert_f128_to_ppcf128:
10574   case Intrinsic::ppc_convert_ppcf128_to_f128: {
10575     RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10576                             ? RTLIB::CONVERT_PPCF128_F128
10577                             : RTLIB::CONVERT_F128_PPCF128;
10578     MakeLibCallOptions CallOptions;
10579     std::pair<SDValue, SDValue> Result =
10580         makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10581                     dl, SDValue());
10582     return Result.first;
10583   }
10584   case Intrinsic::ppc_maxfe:
10585   case Intrinsic::ppc_maxfl:
10586   case Intrinsic::ppc_maxfs:
10587   case Intrinsic::ppc_minfe:
10588   case Intrinsic::ppc_minfl:
10589   case Intrinsic::ppc_minfs: {
10590     EVT VT = Op.getValueType();
10591     assert(
10592         all_of(Op->ops().drop_front(4),
10593                [VT](const SDUse &Use) { return Use.getValueType() == VT; }) &&
10594         "ppc_[max|min]f[e|l|s] must have uniform type arguments");
10595     (void)VT;
10596     ISD::CondCode CC = ISD::SETGT;
10597     if (IntrinsicID == Intrinsic::ppc_minfe ||
10598         IntrinsicID == Intrinsic::ppc_minfl ||
10599         IntrinsicID == Intrinsic::ppc_minfs)
10600       CC = ISD::SETLT;
10601     unsigned I = Op.getNumOperands() - 2, Cnt = I;
10602     SDValue Res = Op.getOperand(I);
10603     for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) {
10604       Res =
10605           DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC);
10606     }
10607     return Res;
10608   }
10609   }
10610 
10611   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10612   // opcode number of the comparison.
10613   int CompareOpc;
10614   bool isDot;
10615   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10616     return SDValue();    // Don't custom lower most intrinsics.
10617 
10618   // If this is a non-dot comparison, make the VCMP node and we are done.
10619   if (!isDot) {
10620     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10621                               Op.getOperand(1), Op.getOperand(2),
10622                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10623     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10624   }
10625 
10626   // Create the PPCISD altivec 'dot' comparison node.
10627   SDValue Ops[] = {
10628     Op.getOperand(2),  // LHS
10629     Op.getOperand(3),  // RHS
10630     DAG.getConstant(CompareOpc, dl, MVT::i32)
10631   };
10632   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10633   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10634 
10635   // Now that we have the comparison, emit a copy from the CR to a GPR.
10636   // This is flagged to the above dot comparison.
10637   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10638                                 DAG.getRegister(PPC::CR6, MVT::i32),
10639                                 CompNode.getValue(1));
10640 
10641   // Unpack the result based on how the target uses it.
10642   unsigned BitNo;   // Bit # of CR6.
10643   bool InvertBit;   // Invert result?
10644   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10645   default:  // Can't happen, don't crash on invalid number though.
10646   case 0:   // Return the value of the EQ bit of CR6.
10647     BitNo = 0; InvertBit = false;
10648     break;
10649   case 1:   // Return the inverted value of the EQ bit of CR6.
10650     BitNo = 0; InvertBit = true;
10651     break;
10652   case 2:   // Return the value of the LT bit of CR6.
10653     BitNo = 2; InvertBit = false;
10654     break;
10655   case 3:   // Return the inverted value of the LT bit of CR6.
10656     BitNo = 2; InvertBit = true;
10657     break;
10658   }
10659 
10660   // Shift the bit into the low position.
10661   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10662                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10663   // Isolate the bit.
10664   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10665                       DAG.getConstant(1, dl, MVT::i32));
10666 
10667   // If we are supposed to, toggle the bit.
10668   if (InvertBit)
10669     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10670                         DAG.getConstant(1, dl, MVT::i32));
10671   return Flags;
10672 }
10673 
10674 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10675                                                SelectionDAG &DAG) const {
10676   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10677   // the beginning of the argument list.
10678   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10679   SDLoc DL(Op);
10680   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10681   case Intrinsic::ppc_cfence: {
10682     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10683     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10684     SDValue Val = Op.getOperand(ArgStart + 1);
10685     EVT Ty = Val.getValueType();
10686     if (Ty == MVT::i128) {
10687       // FIXME: Testing one of two paired registers is sufficient to guarantee
10688       // ordering?
10689       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10690     }
10691     return SDValue(
10692         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10693                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10694                            Op.getOperand(0)),
10695         0);
10696   }
10697   default:
10698     break;
10699   }
10700   return SDValue();
10701 }
10702 
10703 // Lower scalar BSWAP64 to xxbrd.
10704 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10705   SDLoc dl(Op);
10706   if (!Subtarget.isPPC64())
10707     return Op;
10708   // MTVSRDD
10709   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10710                    Op.getOperand(0));
10711   // XXBRD
10712   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10713   // MFVSRD
10714   int VectorIndex = 0;
10715   if (Subtarget.isLittleEndian())
10716     VectorIndex = 1;
10717   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10718                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10719   return Op;
10720 }
10721 
10722 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10723 // compared to a value that is atomically loaded (atomic loads zero-extend).
10724 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10725                                                 SelectionDAG &DAG) const {
10726   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10727          "Expecting an atomic compare-and-swap here.");
10728   SDLoc dl(Op);
10729   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10730   EVT MemVT = AtomicNode->getMemoryVT();
10731   if (MemVT.getSizeInBits() >= 32)
10732     return Op;
10733 
10734   SDValue CmpOp = Op.getOperand(2);
10735   // If this is already correctly zero-extended, leave it alone.
10736   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10737   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10738     return Op;
10739 
10740   // Clear the high bits of the compare operand.
10741   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10742   SDValue NewCmpOp =
10743     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10744                 DAG.getConstant(MaskVal, dl, MVT::i32));
10745 
10746   // Replace the existing compare operand with the properly zero-extended one.
10747   SmallVector<SDValue, 4> Ops;
10748   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10749     Ops.push_back(AtomicNode->getOperand(i));
10750   Ops[2] = NewCmpOp;
10751   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10752   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10753   auto NodeTy =
10754     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10755   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10756 }
10757 
10758 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10759                                                   SelectionDAG &DAG) const {
10760   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10761   EVT MemVT = N->getMemoryVT();
10762   assert(MemVT.getSimpleVT() == MVT::i128 &&
10763          "Expect quadword atomic operations");
10764   SDLoc dl(N);
10765   unsigned Opc = N->getOpcode();
10766   switch (Opc) {
10767   case ISD::ATOMIC_LOAD: {
10768     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10769     // lowered to ppc instructions by pattern matching instruction selector.
10770     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10771     SmallVector<SDValue, 4> Ops{
10772         N->getOperand(0),
10773         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10774     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10775       Ops.push_back(N->getOperand(I));
10776     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10777                                                 Ops, MemVT, N->getMemOperand());
10778     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10779     SDValue ValHi =
10780         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10781     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10782                         DAG.getConstant(64, dl, MVT::i32));
10783     SDValue Val =
10784         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10785     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10786                        {Val, LoadedVal.getValue(2)});
10787   }
10788   case ISD::ATOMIC_STORE: {
10789     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10790     // lowered to ppc instructions by pattern matching instruction selector.
10791     SDVTList Tys = DAG.getVTList(MVT::Other);
10792     SmallVector<SDValue, 4> Ops{
10793         N->getOperand(0),
10794         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10795     SDValue Val = N->getOperand(2);
10796     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10797     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10798                                 DAG.getConstant(64, dl, MVT::i32));
10799     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10800     Ops.push_back(ValLo);
10801     Ops.push_back(ValHi);
10802     Ops.push_back(N->getOperand(1));
10803     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10804                                    N->getMemOperand());
10805   }
10806   default:
10807     llvm_unreachable("Unexpected atomic opcode");
10808   }
10809 }
10810 
10811 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10812                                                  SelectionDAG &DAG) const {
10813   SDLoc dl(Op);
10814   // Create a stack slot that is 16-byte aligned.
10815   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10816   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10817   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10818   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10819 
10820   // Store the input value into Value#0 of the stack slot.
10821   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10822                                MachinePointerInfo());
10823   // Load it out.
10824   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10825 }
10826 
10827 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10828                                                   SelectionDAG &DAG) const {
10829   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10830          "Should only be called for ISD::INSERT_VECTOR_ELT");
10831 
10832   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10833 
10834   EVT VT = Op.getValueType();
10835   SDLoc dl(Op);
10836   SDValue V1 = Op.getOperand(0);
10837   SDValue V2 = Op.getOperand(1);
10838 
10839   if (VT == MVT::v2f64 && C)
10840     return Op;
10841 
10842   if (Subtarget.hasP9Vector()) {
10843     // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
10844     // because on P10, it allows this specific insert_vector_elt load pattern to
10845     // utilize the refactored load and store infrastructure in order to exploit
10846     // prefixed loads.
10847     // On targets with inexpensive direct moves (Power9 and up), a
10848     // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
10849     // load since a single precision load will involve conversion to double
10850     // precision on the load followed by another conversion to single precision.
10851     if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
10852         (isa<LoadSDNode>(V2))) {
10853       SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
10854       SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
10855       SDValue InsVecElt =
10856           DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
10857                       BitcastLoad, Op.getOperand(2));
10858       return DAG.getBitcast(MVT::v4f32, InsVecElt);
10859     }
10860   }
10861 
10862   if (Subtarget.isISA3_1()) {
10863     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10864       return SDValue();
10865     // On P10, we have legal lowering for constant and variable indices for
10866     // all vectors.
10867     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10868         VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
10869       return Op;
10870   }
10871 
10872   // Before P10, we have legal lowering for constant indices but not for
10873   // variable ones.
10874   if (!C)
10875     return SDValue();
10876 
10877   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10878   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10879     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10880     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10881     unsigned InsertAtElement = C->getZExtValue();
10882     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10883     if (Subtarget.isLittleEndian()) {
10884       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10885     }
10886     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10887                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10888   }
10889   return Op;
10890 }
10891 
10892 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10893                                            SelectionDAG &DAG) const {
10894   SDLoc dl(Op);
10895   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10896   SDValue LoadChain = LN->getChain();
10897   SDValue BasePtr = LN->getBasePtr();
10898   EVT VT = Op.getValueType();
10899 
10900   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10901     return Op;
10902 
10903   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10904   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10905   // 2 or 4 vsx registers.
10906   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10907          "Type unsupported without MMA");
10908   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10909          "Type unsupported without paired vector support");
10910   Align Alignment = LN->getAlign();
10911   SmallVector<SDValue, 4> Loads;
10912   SmallVector<SDValue, 4> LoadChains;
10913   unsigned NumVecs = VT.getSizeInBits() / 128;
10914   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10915     SDValue Load =
10916         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10917                     LN->getPointerInfo().getWithOffset(Idx * 16),
10918                     commonAlignment(Alignment, Idx * 16),
10919                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10920     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10921                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10922     Loads.push_back(Load);
10923     LoadChains.push_back(Load.getValue(1));
10924   }
10925   if (Subtarget.isLittleEndian()) {
10926     std::reverse(Loads.begin(), Loads.end());
10927     std::reverse(LoadChains.begin(), LoadChains.end());
10928   }
10929   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10930   SDValue Value =
10931       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10932                   dl, VT, Loads);
10933   SDValue RetOps[] = {Value, TF};
10934   return DAG.getMergeValues(RetOps, dl);
10935 }
10936 
10937 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10938                                             SelectionDAG &DAG) const {
10939   SDLoc dl(Op);
10940   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10941   SDValue StoreChain = SN->getChain();
10942   SDValue BasePtr = SN->getBasePtr();
10943   SDValue Value = SN->getValue();
10944   EVT StoreVT = Value.getValueType();
10945 
10946   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10947     return Op;
10948 
10949   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10950   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10951   // underlying registers individually.
10952   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10953          "Type unsupported without MMA");
10954   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10955          "Type unsupported without paired vector support");
10956   Align Alignment = SN->getAlign();
10957   SmallVector<SDValue, 4> Stores;
10958   unsigned NumVecs = 2;
10959   if (StoreVT == MVT::v512i1) {
10960     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10961     NumVecs = 4;
10962   }
10963   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10964     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10965     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10966                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10967     SDValue Store =
10968         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10969                      SN->getPointerInfo().getWithOffset(Idx * 16),
10970                      commonAlignment(Alignment, Idx * 16),
10971                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10972     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10973                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10974     Stores.push_back(Store);
10975   }
10976   SDValue TF = DAG.getTokenFactor(dl, Stores);
10977   return TF;
10978 }
10979 
10980 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10981   SDLoc dl(Op);
10982   if (Op.getValueType() == MVT::v4i32) {
10983     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10984 
10985     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10986     // +16 as shift amt.
10987     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10988     SDValue RHSSwap =   // = vrlw RHS, 16
10989       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10990 
10991     // Shrinkify inputs to v8i16.
10992     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10993     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10994     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10995 
10996     // Low parts multiplied together, generating 32-bit results (we ignore the
10997     // top parts).
10998     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10999                                         LHS, RHS, DAG, dl, MVT::v4i32);
11000 
11001     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
11002                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
11003     // Shift the high parts up 16 bits.
11004     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
11005                               Neg16, DAG, dl);
11006     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
11007   } else if (Op.getValueType() == MVT::v16i8) {
11008     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
11009     bool isLittleEndian = Subtarget.isLittleEndian();
11010 
11011     // Multiply the even 8-bit parts, producing 16-bit sums.
11012     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
11013                                            LHS, RHS, DAG, dl, MVT::v8i16);
11014     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
11015 
11016     // Multiply the odd 8-bit parts, producing 16-bit sums.
11017     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
11018                                           LHS, RHS, DAG, dl, MVT::v8i16);
11019     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
11020 
11021     // Merge the results together.  Because vmuleub and vmuloub are
11022     // instructions with a big-endian bias, we must reverse the
11023     // element numbering and reverse the meaning of "odd" and "even"
11024     // when generating little endian code.
11025     int Ops[16];
11026     for (unsigned i = 0; i != 8; ++i) {
11027       if (isLittleEndian) {
11028         Ops[i*2  ] = 2*i;
11029         Ops[i*2+1] = 2*i+16;
11030       } else {
11031         Ops[i*2  ] = 2*i+1;
11032         Ops[i*2+1] = 2*i+1+16;
11033       }
11034     }
11035     if (isLittleEndian)
11036       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
11037     else
11038       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
11039   } else {
11040     llvm_unreachable("Unknown mul to lower!");
11041   }
11042 }
11043 
11044 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11045   bool IsStrict = Op->isStrictFPOpcode();
11046   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
11047       !Subtarget.hasP9Vector())
11048     return SDValue();
11049 
11050   return Op;
11051 }
11052 
11053 // Custom lowering for fpext vf32 to v2f64
11054 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11055 
11056   assert(Op.getOpcode() == ISD::FP_EXTEND &&
11057          "Should only be called for ISD::FP_EXTEND");
11058 
11059   // FIXME: handle extends from half precision float vectors on P9.
11060   // We only want to custom lower an extend from v2f32 to v2f64.
11061   if (Op.getValueType() != MVT::v2f64 ||
11062       Op.getOperand(0).getValueType() != MVT::v2f32)
11063     return SDValue();
11064 
11065   SDLoc dl(Op);
11066   SDValue Op0 = Op.getOperand(0);
11067 
11068   switch (Op0.getOpcode()) {
11069   default:
11070     return SDValue();
11071   case ISD::EXTRACT_SUBVECTOR: {
11072     assert(Op0.getNumOperands() == 2 &&
11073            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11074            "Node should have 2 operands with second one being a constant!");
11075 
11076     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11077       return SDValue();
11078 
11079     // Custom lower is only done for high or low doubleword.
11080     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11081     if (Idx % 2 != 0)
11082       return SDValue();
11083 
11084     // Since input is v4f32, at this point Idx is either 0 or 2.
11085     // Shift to get the doubleword position we want.
11086     int DWord = Idx >> 1;
11087 
11088     // High and low word positions are different on little endian.
11089     if (Subtarget.isLittleEndian())
11090       DWord ^= 0x1;
11091 
11092     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11093                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11094   }
11095   case ISD::FADD:
11096   case ISD::FMUL:
11097   case ISD::FSUB: {
11098     SDValue NewLoad[2];
11099     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11100       // Ensure both input are loads.
11101       SDValue LdOp = Op0.getOperand(i);
11102       if (LdOp.getOpcode() != ISD::LOAD)
11103         return SDValue();
11104       // Generate new load node.
11105       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11106       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11107       NewLoad[i] = DAG.getMemIntrinsicNode(
11108           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11109           LD->getMemoryVT(), LD->getMemOperand());
11110     }
11111     SDValue NewOp =
11112         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11113                     NewLoad[1], Op0.getNode()->getFlags());
11114     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11115                        DAG.getConstant(0, dl, MVT::i32));
11116   }
11117   case ISD::LOAD: {
11118     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11119     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11120     SDValue NewLd = DAG.getMemIntrinsicNode(
11121         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11122         LD->getMemoryVT(), LD->getMemOperand());
11123     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11124                        DAG.getConstant(0, dl, MVT::i32));
11125   }
11126   }
11127   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11128 }
11129 
11130 /// LowerOperation - Provide custom lowering hooks for some operations.
11131 ///
11132 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11133   switch (Op.getOpcode()) {
11134   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11135   case ISD::FPOW:               return lowerPow(Op, DAG);
11136   case ISD::FSIN:               return lowerSin(Op, DAG);
11137   case ISD::FCOS:               return lowerCos(Op, DAG);
11138   case ISD::FLOG:               return lowerLog(Op, DAG);
11139   case ISD::FLOG10:             return lowerLog10(Op, DAG);
11140   case ISD::FEXP:               return lowerExp(Op, DAG);
11141   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11142   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11143   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11144   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11145   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11146   case ISD::STRICT_FSETCC:
11147   case ISD::STRICT_FSETCCS:
11148   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11149   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11150   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11151 
11152   case ISD::INLINEASM:
11153   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11154   // Variable argument lowering.
11155   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11156   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11157   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11158 
11159   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11160   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11161   case ISD::GET_DYNAMIC_AREA_OFFSET:
11162     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11163 
11164   // Exception handling lowering.
11165   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11166   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11167   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11168 
11169   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11170   case ISD::STORE:              return LowerSTORE(Op, DAG);
11171   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11172   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11173   case ISD::STRICT_FP_TO_UINT:
11174   case ISD::STRICT_FP_TO_SINT:
11175   case ISD::FP_TO_UINT:
11176   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11177   case ISD::STRICT_UINT_TO_FP:
11178   case ISD::STRICT_SINT_TO_FP:
11179   case ISD::UINT_TO_FP:
11180   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11181   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11182 
11183   // Lower 64-bit shifts.
11184   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11185   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11186   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11187 
11188   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11189   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11190 
11191   // Vector-related lowering.
11192   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11193   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11194   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11195   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11196   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11197   case ISD::MUL:                return LowerMUL(Op, DAG);
11198   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11199   case ISD::STRICT_FP_ROUND:
11200   case ISD::FP_ROUND:
11201     return LowerFP_ROUND(Op, DAG);
11202   case ISD::ROTL:               return LowerROTL(Op, DAG);
11203 
11204   // For counter-based loop handling.
11205   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11206 
11207   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11208 
11209   // Frame & Return address.
11210   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11211   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11212 
11213   case ISD::INTRINSIC_VOID:
11214     return LowerINTRINSIC_VOID(Op, DAG);
11215   case ISD::BSWAP:
11216     return LowerBSWAP(Op, DAG);
11217   case ISD::ATOMIC_CMP_SWAP:
11218     return LowerATOMIC_CMP_SWAP(Op, DAG);
11219   case ISD::ATOMIC_STORE:
11220     return LowerATOMIC_LOAD_STORE(Op, DAG);
11221   }
11222 }
11223 
11224 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11225                                            SmallVectorImpl<SDValue>&Results,
11226                                            SelectionDAG &DAG) const {
11227   SDLoc dl(N);
11228   switch (N->getOpcode()) {
11229   default:
11230     llvm_unreachable("Do not know how to custom type legalize this operation!");
11231   case ISD::ATOMIC_LOAD: {
11232     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11233     Results.push_back(Res);
11234     Results.push_back(Res.getValue(1));
11235     break;
11236   }
11237   case ISD::READCYCLECOUNTER: {
11238     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11239     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11240 
11241     Results.push_back(
11242         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11243     Results.push_back(RTB.getValue(2));
11244     break;
11245   }
11246   case ISD::INTRINSIC_W_CHAIN: {
11247     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11248         Intrinsic::loop_decrement)
11249       break;
11250 
11251     assert(N->getValueType(0) == MVT::i1 &&
11252            "Unexpected result type for CTR decrement intrinsic");
11253     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11254                                  N->getValueType(0));
11255     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11256     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11257                                  N->getOperand(1));
11258 
11259     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11260     Results.push_back(NewInt.getValue(1));
11261     break;
11262   }
11263   case ISD::INTRINSIC_WO_CHAIN: {
11264     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11265     case Intrinsic::ppc_pack_longdouble:
11266       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11267                                     N->getOperand(2), N->getOperand(1)));
11268       break;
11269     case Intrinsic::ppc_maxfe:
11270     case Intrinsic::ppc_minfe:
11271     case Intrinsic::ppc_fnmsub:
11272     case Intrinsic::ppc_convert_f128_to_ppcf128:
11273       Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11274       break;
11275     }
11276     break;
11277   }
11278   case ISD::VAARG: {
11279     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11280       return;
11281 
11282     EVT VT = N->getValueType(0);
11283 
11284     if (VT == MVT::i64) {
11285       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11286 
11287       Results.push_back(NewNode);
11288       Results.push_back(NewNode.getValue(1));
11289     }
11290     return;
11291   }
11292   case ISD::STRICT_FP_TO_SINT:
11293   case ISD::STRICT_FP_TO_UINT:
11294   case ISD::FP_TO_SINT:
11295   case ISD::FP_TO_UINT: {
11296     // LowerFP_TO_INT() can only handle f32 and f64.
11297     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11298         MVT::ppcf128)
11299       return;
11300     SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11301     Results.push_back(LoweredValue);
11302     if (N->isStrictFPOpcode())
11303       Results.push_back(LoweredValue.getValue(1));
11304     return;
11305   }
11306   case ISD::TRUNCATE: {
11307     if (!N->getValueType(0).isVector())
11308       return;
11309     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11310     if (Lowered)
11311       Results.push_back(Lowered);
11312     return;
11313   }
11314   case ISD::FSHL:
11315   case ISD::FSHR:
11316     // Don't handle funnel shifts here.
11317     return;
11318   case ISD::BITCAST:
11319     // Don't handle bitcast here.
11320     return;
11321   case ISD::FP_EXTEND:
11322     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11323     if (Lowered)
11324       Results.push_back(Lowered);
11325     return;
11326   }
11327 }
11328 
11329 //===----------------------------------------------------------------------===//
11330 //  Other Lowering Code
11331 //===----------------------------------------------------------------------===//
11332 
11333 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11334   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11335   Function *Func = Intrinsic::getDeclaration(M, Id);
11336   return Builder.CreateCall(Func, {});
11337 }
11338 
11339 // The mappings for emitLeading/TrailingFence is taken from
11340 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11341 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11342                                                  Instruction *Inst,
11343                                                  AtomicOrdering Ord) const {
11344   if (Ord == AtomicOrdering::SequentiallyConsistent)
11345     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11346   if (isReleaseOrStronger(Ord))
11347     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11348   return nullptr;
11349 }
11350 
11351 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11352                                                   Instruction *Inst,
11353                                                   AtomicOrdering Ord) const {
11354   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11355     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11356     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11357     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11358     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11359       return Builder.CreateCall(
11360           Intrinsic::getDeclaration(
11361               Builder.GetInsertBlock()->getParent()->getParent(),
11362               Intrinsic::ppc_cfence, {Inst->getType()}),
11363           {Inst});
11364     // FIXME: Can use isync for rmw operation.
11365     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11366   }
11367   return nullptr;
11368 }
11369 
11370 MachineBasicBlock *
11371 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11372                                     unsigned AtomicSize,
11373                                     unsigned BinOpcode,
11374                                     unsigned CmpOpcode,
11375                                     unsigned CmpPred) const {
11376   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11377   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11378 
11379   auto LoadMnemonic = PPC::LDARX;
11380   auto StoreMnemonic = PPC::STDCX;
11381   switch (AtomicSize) {
11382   default:
11383     llvm_unreachable("Unexpected size of atomic entity");
11384   case 1:
11385     LoadMnemonic = PPC::LBARX;
11386     StoreMnemonic = PPC::STBCX;
11387     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11388     break;
11389   case 2:
11390     LoadMnemonic = PPC::LHARX;
11391     StoreMnemonic = PPC::STHCX;
11392     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11393     break;
11394   case 4:
11395     LoadMnemonic = PPC::LWARX;
11396     StoreMnemonic = PPC::STWCX;
11397     break;
11398   case 8:
11399     LoadMnemonic = PPC::LDARX;
11400     StoreMnemonic = PPC::STDCX;
11401     break;
11402   }
11403 
11404   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11405   MachineFunction *F = BB->getParent();
11406   MachineFunction::iterator It = ++BB->getIterator();
11407 
11408   Register dest = MI.getOperand(0).getReg();
11409   Register ptrA = MI.getOperand(1).getReg();
11410   Register ptrB = MI.getOperand(2).getReg();
11411   Register incr = MI.getOperand(3).getReg();
11412   DebugLoc dl = MI.getDebugLoc();
11413 
11414   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11415   MachineBasicBlock *loop2MBB =
11416     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11417   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11418   F->insert(It, loopMBB);
11419   if (CmpOpcode)
11420     F->insert(It, loop2MBB);
11421   F->insert(It, exitMBB);
11422   exitMBB->splice(exitMBB->begin(), BB,
11423                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11424   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11425 
11426   MachineRegisterInfo &RegInfo = F->getRegInfo();
11427   Register TmpReg = (!BinOpcode) ? incr :
11428     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11429                                            : &PPC::GPRCRegClass);
11430 
11431   //  thisMBB:
11432   //   ...
11433   //   fallthrough --> loopMBB
11434   BB->addSuccessor(loopMBB);
11435 
11436   //  loopMBB:
11437   //   l[wd]arx dest, ptr
11438   //   add r0, dest, incr
11439   //   st[wd]cx. r0, ptr
11440   //   bne- loopMBB
11441   //   fallthrough --> exitMBB
11442 
11443   // For max/min...
11444   //  loopMBB:
11445   //   l[wd]arx dest, ptr
11446   //   cmpl?[wd] incr, dest
11447   //   bgt exitMBB
11448   //  loop2MBB:
11449   //   st[wd]cx. dest, ptr
11450   //   bne- loopMBB
11451   //   fallthrough --> exitMBB
11452 
11453   BB = loopMBB;
11454   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11455     .addReg(ptrA).addReg(ptrB);
11456   if (BinOpcode)
11457     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11458   if (CmpOpcode) {
11459     // Signed comparisons of byte or halfword values must be sign-extended.
11460     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11461       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11462       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11463               ExtReg).addReg(dest);
11464       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11465         .addReg(incr).addReg(ExtReg);
11466     } else
11467       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11468         .addReg(incr).addReg(dest);
11469 
11470     BuildMI(BB, dl, TII->get(PPC::BCC))
11471       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11472     BB->addSuccessor(loop2MBB);
11473     BB->addSuccessor(exitMBB);
11474     BB = loop2MBB;
11475   }
11476   BuildMI(BB, dl, TII->get(StoreMnemonic))
11477     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11478   BuildMI(BB, dl, TII->get(PPC::BCC))
11479     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11480   BB->addSuccessor(loopMBB);
11481   BB->addSuccessor(exitMBB);
11482 
11483   //  exitMBB:
11484   //   ...
11485   BB = exitMBB;
11486   return BB;
11487 }
11488 
11489 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11490   switch(MI.getOpcode()) {
11491   default:
11492     return false;
11493   case PPC::COPY:
11494     return TII->isSignExtended(MI);
11495   case PPC::LHA:
11496   case PPC::LHA8:
11497   case PPC::LHAU:
11498   case PPC::LHAU8:
11499   case PPC::LHAUX:
11500   case PPC::LHAUX8:
11501   case PPC::LHAX:
11502   case PPC::LHAX8:
11503   case PPC::LWA:
11504   case PPC::LWAUX:
11505   case PPC::LWAX:
11506   case PPC::LWAX_32:
11507   case PPC::LWA_32:
11508   case PPC::PLHA:
11509   case PPC::PLHA8:
11510   case PPC::PLHA8pc:
11511   case PPC::PLHApc:
11512   case PPC::PLWA:
11513   case PPC::PLWA8:
11514   case PPC::PLWA8pc:
11515   case PPC::PLWApc:
11516   case PPC::EXTSB:
11517   case PPC::EXTSB8:
11518   case PPC::EXTSB8_32_64:
11519   case PPC::EXTSB8_rec:
11520   case PPC::EXTSB_rec:
11521   case PPC::EXTSH:
11522   case PPC::EXTSH8:
11523   case PPC::EXTSH8_32_64:
11524   case PPC::EXTSH8_rec:
11525   case PPC::EXTSH_rec:
11526   case PPC::EXTSW:
11527   case PPC::EXTSWSLI:
11528   case PPC::EXTSWSLI_32_64:
11529   case PPC::EXTSWSLI_32_64_rec:
11530   case PPC::EXTSWSLI_rec:
11531   case PPC::EXTSW_32:
11532   case PPC::EXTSW_32_64:
11533   case PPC::EXTSW_32_64_rec:
11534   case PPC::EXTSW_rec:
11535   case PPC::SRAW:
11536   case PPC::SRAWI:
11537   case PPC::SRAWI_rec:
11538   case PPC::SRAW_rec:
11539     return true;
11540   }
11541   return false;
11542 }
11543 
11544 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11545     MachineInstr &MI, MachineBasicBlock *BB,
11546     bool is8bit, // operation
11547     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11548   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11549   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11550 
11551   // If this is a signed comparison and the value being compared is not known
11552   // to be sign extended, sign extend it here.
11553   DebugLoc dl = MI.getDebugLoc();
11554   MachineFunction *F = BB->getParent();
11555   MachineRegisterInfo &RegInfo = F->getRegInfo();
11556   Register incr = MI.getOperand(3).getReg();
11557   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11558     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11559 
11560   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11561     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11562     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11563         .addReg(MI.getOperand(3).getReg());
11564     MI.getOperand(3).setReg(ValueReg);
11565   }
11566   // If we support part-word atomic mnemonics, just use them
11567   if (Subtarget.hasPartwordAtomics())
11568     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11569                             CmpPred);
11570 
11571   // In 64 bit mode we have to use 64 bits for addresses, even though the
11572   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11573   // registers without caring whether they're 32 or 64, but here we're
11574   // doing actual arithmetic on the addresses.
11575   bool is64bit = Subtarget.isPPC64();
11576   bool isLittleEndian = Subtarget.isLittleEndian();
11577   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11578 
11579   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11580   MachineFunction::iterator It = ++BB->getIterator();
11581 
11582   Register dest = MI.getOperand(0).getReg();
11583   Register ptrA = MI.getOperand(1).getReg();
11584   Register ptrB = MI.getOperand(2).getReg();
11585 
11586   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11587   MachineBasicBlock *loop2MBB =
11588       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11589   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11590   F->insert(It, loopMBB);
11591   if (CmpOpcode)
11592     F->insert(It, loop2MBB);
11593   F->insert(It, exitMBB);
11594   exitMBB->splice(exitMBB->begin(), BB,
11595                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11596   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11597 
11598   const TargetRegisterClass *RC =
11599       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11600   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11601 
11602   Register PtrReg = RegInfo.createVirtualRegister(RC);
11603   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11604   Register ShiftReg =
11605       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11606   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11607   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11608   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11609   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11610   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11611   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11612   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11613   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11614   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11615   Register Ptr1Reg;
11616   Register TmpReg =
11617       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11618 
11619   //  thisMBB:
11620   //   ...
11621   //   fallthrough --> loopMBB
11622   BB->addSuccessor(loopMBB);
11623 
11624   // The 4-byte load must be aligned, while a char or short may be
11625   // anywhere in the word.  Hence all this nasty bookkeeping code.
11626   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11627   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11628   //   xori shift, shift1, 24 [16]
11629   //   rlwinm ptr, ptr1, 0, 0, 29
11630   //   slw incr2, incr, shift
11631   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11632   //   slw mask, mask2, shift
11633   //  loopMBB:
11634   //   lwarx tmpDest, ptr
11635   //   add tmp, tmpDest, incr2
11636   //   andc tmp2, tmpDest, mask
11637   //   and tmp3, tmp, mask
11638   //   or tmp4, tmp3, tmp2
11639   //   stwcx. tmp4, ptr
11640   //   bne- loopMBB
11641   //   fallthrough --> exitMBB
11642   //   srw SrwDest, tmpDest, shift
11643   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11644   if (ptrA != ZeroReg) {
11645     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11646     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11647         .addReg(ptrA)
11648         .addReg(ptrB);
11649   } else {
11650     Ptr1Reg = ptrB;
11651   }
11652   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11653   // mode.
11654   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11655       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11656       .addImm(3)
11657       .addImm(27)
11658       .addImm(is8bit ? 28 : 27);
11659   if (!isLittleEndian)
11660     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11661         .addReg(Shift1Reg)
11662         .addImm(is8bit ? 24 : 16);
11663   if (is64bit)
11664     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11665         .addReg(Ptr1Reg)
11666         .addImm(0)
11667         .addImm(61);
11668   else
11669     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11670         .addReg(Ptr1Reg)
11671         .addImm(0)
11672         .addImm(0)
11673         .addImm(29);
11674   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11675   if (is8bit)
11676     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11677   else {
11678     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11679     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11680         .addReg(Mask3Reg)
11681         .addImm(65535);
11682   }
11683   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11684       .addReg(Mask2Reg)
11685       .addReg(ShiftReg);
11686 
11687   BB = loopMBB;
11688   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11689       .addReg(ZeroReg)
11690       .addReg(PtrReg);
11691   if (BinOpcode)
11692     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11693         .addReg(Incr2Reg)
11694         .addReg(TmpDestReg);
11695   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11696       .addReg(TmpDestReg)
11697       .addReg(MaskReg);
11698   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11699   if (CmpOpcode) {
11700     // For unsigned comparisons, we can directly compare the shifted values.
11701     // For signed comparisons we shift and sign extend.
11702     Register SReg = RegInfo.createVirtualRegister(GPRC);
11703     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11704         .addReg(TmpDestReg)
11705         .addReg(MaskReg);
11706     unsigned ValueReg = SReg;
11707     unsigned CmpReg = Incr2Reg;
11708     if (CmpOpcode == PPC::CMPW) {
11709       ValueReg = RegInfo.createVirtualRegister(GPRC);
11710       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11711           .addReg(SReg)
11712           .addReg(ShiftReg);
11713       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11714       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11715           .addReg(ValueReg);
11716       ValueReg = ValueSReg;
11717       CmpReg = incr;
11718     }
11719     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11720         .addReg(CmpReg)
11721         .addReg(ValueReg);
11722     BuildMI(BB, dl, TII->get(PPC::BCC))
11723         .addImm(CmpPred)
11724         .addReg(PPC::CR0)
11725         .addMBB(exitMBB);
11726     BB->addSuccessor(loop2MBB);
11727     BB->addSuccessor(exitMBB);
11728     BB = loop2MBB;
11729   }
11730   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11731   BuildMI(BB, dl, TII->get(PPC::STWCX))
11732       .addReg(Tmp4Reg)
11733       .addReg(ZeroReg)
11734       .addReg(PtrReg);
11735   BuildMI(BB, dl, TII->get(PPC::BCC))
11736       .addImm(PPC::PRED_NE)
11737       .addReg(PPC::CR0)
11738       .addMBB(loopMBB);
11739   BB->addSuccessor(loopMBB);
11740   BB->addSuccessor(exitMBB);
11741 
11742   //  exitMBB:
11743   //   ...
11744   BB = exitMBB;
11745   // Since the shift amount is not a constant, we need to clear
11746   // the upper bits with a separate RLWINM.
11747   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11748       .addReg(SrwDestReg)
11749       .addImm(0)
11750       .addImm(is8bit ? 24 : 16)
11751       .addImm(31);
11752   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11753       .addReg(TmpDestReg)
11754       .addReg(ShiftReg);
11755   return BB;
11756 }
11757 
11758 llvm::MachineBasicBlock *
11759 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11760                                     MachineBasicBlock *MBB) const {
11761   DebugLoc DL = MI.getDebugLoc();
11762   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11763   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11764 
11765   MachineFunction *MF = MBB->getParent();
11766   MachineRegisterInfo &MRI = MF->getRegInfo();
11767 
11768   const BasicBlock *BB = MBB->getBasicBlock();
11769   MachineFunction::iterator I = ++MBB->getIterator();
11770 
11771   Register DstReg = MI.getOperand(0).getReg();
11772   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11773   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11774   Register mainDstReg = MRI.createVirtualRegister(RC);
11775   Register restoreDstReg = MRI.createVirtualRegister(RC);
11776 
11777   MVT PVT = getPointerTy(MF->getDataLayout());
11778   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11779          "Invalid Pointer Size!");
11780   // For v = setjmp(buf), we generate
11781   //
11782   // thisMBB:
11783   //  SjLjSetup mainMBB
11784   //  bl mainMBB
11785   //  v_restore = 1
11786   //  b sinkMBB
11787   //
11788   // mainMBB:
11789   //  buf[LabelOffset] = LR
11790   //  v_main = 0
11791   //
11792   // sinkMBB:
11793   //  v = phi(main, restore)
11794   //
11795 
11796   MachineBasicBlock *thisMBB = MBB;
11797   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11798   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11799   MF->insert(I, mainMBB);
11800   MF->insert(I, sinkMBB);
11801 
11802   MachineInstrBuilder MIB;
11803 
11804   // Transfer the remainder of BB and its successor edges to sinkMBB.
11805   sinkMBB->splice(sinkMBB->begin(), MBB,
11806                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11807   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11808 
11809   // Note that the structure of the jmp_buf used here is not compatible
11810   // with that used by libc, and is not designed to be. Specifically, it
11811   // stores only those 'reserved' registers that LLVM does not otherwise
11812   // understand how to spill. Also, by convention, by the time this
11813   // intrinsic is called, Clang has already stored the frame address in the
11814   // first slot of the buffer and stack address in the third. Following the
11815   // X86 target code, we'll store the jump address in the second slot. We also
11816   // need to save the TOC pointer (R2) to handle jumps between shared
11817   // libraries, and that will be stored in the fourth slot. The thread
11818   // identifier (R13) is not affected.
11819 
11820   // thisMBB:
11821   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11822   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11823   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11824 
11825   // Prepare IP either in reg.
11826   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11827   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11828   Register BufReg = MI.getOperand(1).getReg();
11829 
11830   if (Subtarget.is64BitELFABI()) {
11831     setUsesTOCBasePtr(*MBB->getParent());
11832     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11833               .addReg(PPC::X2)
11834               .addImm(TOCOffset)
11835               .addReg(BufReg)
11836               .cloneMemRefs(MI);
11837   }
11838 
11839   // Naked functions never have a base pointer, and so we use r1. For all
11840   // other functions, this decision must be delayed until during PEI.
11841   unsigned BaseReg;
11842   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11843     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11844   else
11845     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11846 
11847   MIB = BuildMI(*thisMBB, MI, DL,
11848                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11849             .addReg(BaseReg)
11850             .addImm(BPOffset)
11851             .addReg(BufReg)
11852             .cloneMemRefs(MI);
11853 
11854   // Setup
11855   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11856   MIB.addRegMask(TRI->getNoPreservedMask());
11857 
11858   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11859 
11860   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11861           .addMBB(mainMBB);
11862   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11863 
11864   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11865   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11866 
11867   // mainMBB:
11868   //  mainDstReg = 0
11869   MIB =
11870       BuildMI(mainMBB, DL,
11871               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11872 
11873   // Store IP
11874   if (Subtarget.isPPC64()) {
11875     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11876             .addReg(LabelReg)
11877             .addImm(LabelOffset)
11878             .addReg(BufReg);
11879   } else {
11880     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11881             .addReg(LabelReg)
11882             .addImm(LabelOffset)
11883             .addReg(BufReg);
11884   }
11885   MIB.cloneMemRefs(MI);
11886 
11887   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11888   mainMBB->addSuccessor(sinkMBB);
11889 
11890   // sinkMBB:
11891   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11892           TII->get(PPC::PHI), DstReg)
11893     .addReg(mainDstReg).addMBB(mainMBB)
11894     .addReg(restoreDstReg).addMBB(thisMBB);
11895 
11896   MI.eraseFromParent();
11897   return sinkMBB;
11898 }
11899 
11900 MachineBasicBlock *
11901 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11902                                      MachineBasicBlock *MBB) const {
11903   DebugLoc DL = MI.getDebugLoc();
11904   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11905 
11906   MachineFunction *MF = MBB->getParent();
11907   MachineRegisterInfo &MRI = MF->getRegInfo();
11908 
11909   MVT PVT = getPointerTy(MF->getDataLayout());
11910   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11911          "Invalid Pointer Size!");
11912 
11913   const TargetRegisterClass *RC =
11914     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11915   Register Tmp = MRI.createVirtualRegister(RC);
11916   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11917   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11918   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11919   unsigned BP =
11920       (PVT == MVT::i64)
11921           ? PPC::X30
11922           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11923                                                               : PPC::R30);
11924 
11925   MachineInstrBuilder MIB;
11926 
11927   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11928   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11929   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11930   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11931 
11932   Register BufReg = MI.getOperand(0).getReg();
11933 
11934   // Reload FP (the jumped-to function may not have had a
11935   // frame pointer, and if so, then its r31 will be restored
11936   // as necessary).
11937   if (PVT == MVT::i64) {
11938     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11939             .addImm(0)
11940             .addReg(BufReg);
11941   } else {
11942     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11943             .addImm(0)
11944             .addReg(BufReg);
11945   }
11946   MIB.cloneMemRefs(MI);
11947 
11948   // Reload IP
11949   if (PVT == MVT::i64) {
11950     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11951             .addImm(LabelOffset)
11952             .addReg(BufReg);
11953   } else {
11954     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11955             .addImm(LabelOffset)
11956             .addReg(BufReg);
11957   }
11958   MIB.cloneMemRefs(MI);
11959 
11960   // Reload SP
11961   if (PVT == MVT::i64) {
11962     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11963             .addImm(SPOffset)
11964             .addReg(BufReg);
11965   } else {
11966     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11967             .addImm(SPOffset)
11968             .addReg(BufReg);
11969   }
11970   MIB.cloneMemRefs(MI);
11971 
11972   // Reload BP
11973   if (PVT == MVT::i64) {
11974     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11975             .addImm(BPOffset)
11976             .addReg(BufReg);
11977   } else {
11978     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11979             .addImm(BPOffset)
11980             .addReg(BufReg);
11981   }
11982   MIB.cloneMemRefs(MI);
11983 
11984   // Reload TOC
11985   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11986     setUsesTOCBasePtr(*MBB->getParent());
11987     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11988               .addImm(TOCOffset)
11989               .addReg(BufReg)
11990               .cloneMemRefs(MI);
11991   }
11992 
11993   // Jump
11994   BuildMI(*MBB, MI, DL,
11995           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11996   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11997 
11998   MI.eraseFromParent();
11999   return MBB;
12000 }
12001 
12002 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
12003   // If the function specifically requests inline stack probes, emit them.
12004   if (MF.getFunction().hasFnAttribute("probe-stack"))
12005     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
12006            "inline-asm";
12007   return false;
12008 }
12009 
12010 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
12011   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
12012   unsigned StackAlign = TFI->getStackAlignment();
12013   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
12014          "Unexpected stack alignment");
12015   // The default stack probe size is 4096 if the function has no
12016   // stack-probe-size attribute.
12017   unsigned StackProbeSize = 4096;
12018   const Function &Fn = MF.getFunction();
12019   if (Fn.hasFnAttribute("stack-probe-size"))
12020     Fn.getFnAttribute("stack-probe-size")
12021         .getValueAsString()
12022         .getAsInteger(0, StackProbeSize);
12023   // Round down to the stack alignment.
12024   StackProbeSize &= ~(StackAlign - 1);
12025   return StackProbeSize ? StackProbeSize : StackAlign;
12026 }
12027 
12028 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
12029 // into three phases. In the first phase, it uses pseudo instruction
12030 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
12031 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
12032 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
12033 // MaxCallFrameSize so that it can calculate correct data area pointer.
12034 MachineBasicBlock *
12035 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
12036                                     MachineBasicBlock *MBB) const {
12037   const bool isPPC64 = Subtarget.isPPC64();
12038   MachineFunction *MF = MBB->getParent();
12039   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12040   DebugLoc DL = MI.getDebugLoc();
12041   const unsigned ProbeSize = getStackProbeSize(*MF);
12042   const BasicBlock *ProbedBB = MBB->getBasicBlock();
12043   MachineRegisterInfo &MRI = MF->getRegInfo();
12044   // The CFG of probing stack looks as
12045   //         +-----+
12046   //         | MBB |
12047   //         +--+--+
12048   //            |
12049   //       +----v----+
12050   //  +--->+ TestMBB +---+
12051   //  |    +----+----+   |
12052   //  |         |        |
12053   //  |   +-----v----+   |
12054   //  +---+ BlockMBB |   |
12055   //      +----------+   |
12056   //                     |
12057   //       +---------+   |
12058   //       | TailMBB +<--+
12059   //       +---------+
12060   // In MBB, calculate previous frame pointer and final stack pointer.
12061   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
12062   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
12063   // TailMBB is spliced via \p MI.
12064   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
12065   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
12066   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
12067 
12068   MachineFunction::iterator MBBIter = ++MBB->getIterator();
12069   MF->insert(MBBIter, TestMBB);
12070   MF->insert(MBBIter, BlockMBB);
12071   MF->insert(MBBIter, TailMBB);
12072 
12073   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
12074   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12075 
12076   Register DstReg = MI.getOperand(0).getReg();
12077   Register NegSizeReg = MI.getOperand(1).getReg();
12078   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12079   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12080   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12081   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12082 
12083   // Since value of NegSizeReg might be realigned in prologepilog, insert a
12084   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
12085   // NegSize.
12086   unsigned ProbeOpc;
12087   if (!MRI.hasOneNonDBGUse(NegSizeReg))
12088     ProbeOpc =
12089         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
12090   else
12091     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
12092     // and NegSizeReg will be allocated in the same phyreg to avoid
12093     // redundant copy when NegSizeReg has only one use which is current MI and
12094     // will be replaced by PREPARE_PROBED_ALLOCA then.
12095     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
12096                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
12097   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
12098       .addDef(ActualNegSizeReg)
12099       .addReg(NegSizeReg)
12100       .add(MI.getOperand(2))
12101       .add(MI.getOperand(3));
12102 
12103   // Calculate final stack pointer, which equals to SP + ActualNegSize.
12104   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12105           FinalStackPtr)
12106       .addReg(SPReg)
12107       .addReg(ActualNegSizeReg);
12108 
12109   // Materialize a scratch register for update.
12110   int64_t NegProbeSize = -(int64_t)ProbeSize;
12111   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
12112   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12113   if (!isInt<16>(NegProbeSize)) {
12114     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12115     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12116         .addImm(NegProbeSize >> 16);
12117     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12118             ScratchReg)
12119         .addReg(TempReg)
12120         .addImm(NegProbeSize & 0xFFFF);
12121   } else
12122     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12123         .addImm(NegProbeSize);
12124 
12125   {
12126     // Probing leading residual part.
12127     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12128     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12129         .addReg(ActualNegSizeReg)
12130         .addReg(ScratchReg);
12131     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12132     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12133         .addReg(Div)
12134         .addReg(ScratchReg);
12135     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12136     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12137         .addReg(Mul)
12138         .addReg(ActualNegSizeReg);
12139     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12140         .addReg(FramePointer)
12141         .addReg(SPReg)
12142         .addReg(NegMod);
12143   }
12144 
12145   {
12146     // Remaining part should be multiple of ProbeSize.
12147     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12148     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12149         .addReg(SPReg)
12150         .addReg(FinalStackPtr);
12151     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12152         .addImm(PPC::PRED_EQ)
12153         .addReg(CmpResult)
12154         .addMBB(TailMBB);
12155     TestMBB->addSuccessor(BlockMBB);
12156     TestMBB->addSuccessor(TailMBB);
12157   }
12158 
12159   {
12160     // Touch the block.
12161     // |P...|P...|P...
12162     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12163         .addReg(FramePointer)
12164         .addReg(SPReg)
12165         .addReg(ScratchReg);
12166     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12167     BlockMBB->addSuccessor(TestMBB);
12168   }
12169 
12170   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12171   // DYNAREAOFFSET pseudo instruction to get the future result.
12172   Register MaxCallFrameSizeReg =
12173       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12174   BuildMI(TailMBB, DL,
12175           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12176           MaxCallFrameSizeReg)
12177       .add(MI.getOperand(2))
12178       .add(MI.getOperand(3));
12179   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12180       .addReg(SPReg)
12181       .addReg(MaxCallFrameSizeReg);
12182 
12183   // Splice instructions after MI to TailMBB.
12184   TailMBB->splice(TailMBB->end(), MBB,
12185                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12186   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12187   MBB->addSuccessor(TestMBB);
12188 
12189   // Delete the pseudo instruction.
12190   MI.eraseFromParent();
12191 
12192   ++NumDynamicAllocaProbed;
12193   return TailMBB;
12194 }
12195 
12196 MachineBasicBlock *
12197 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12198                                                MachineBasicBlock *BB) const {
12199   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12200       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12201     if (Subtarget.is64BitELFABI() &&
12202         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12203         !Subtarget.isUsingPCRelativeCalls()) {
12204       // Call lowering should have added an r2 operand to indicate a dependence
12205       // on the TOC base pointer value. It can't however, because there is no
12206       // way to mark the dependence as implicit there, and so the stackmap code
12207       // will confuse it with a regular operand. Instead, add the dependence
12208       // here.
12209       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12210     }
12211 
12212     return emitPatchPoint(MI, BB);
12213   }
12214 
12215   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12216       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12217     return emitEHSjLjSetJmp(MI, BB);
12218   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12219              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12220     return emitEHSjLjLongJmp(MI, BB);
12221   }
12222 
12223   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12224 
12225   // To "insert" these instructions we actually have to insert their
12226   // control-flow patterns.
12227   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12228   MachineFunction::iterator It = ++BB->getIterator();
12229 
12230   MachineFunction *F = BB->getParent();
12231   MachineRegisterInfo &MRI = F->getRegInfo();
12232 
12233   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12234       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12235       MI.getOpcode() == PPC::SELECT_I8) {
12236     SmallVector<MachineOperand, 2> Cond;
12237     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12238         MI.getOpcode() == PPC::SELECT_CC_I8)
12239       Cond.push_back(MI.getOperand(4));
12240     else
12241       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12242     Cond.push_back(MI.getOperand(1));
12243 
12244     DebugLoc dl = MI.getDebugLoc();
12245     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12246                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12247   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12248              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12249              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12250              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12251              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12252              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12253              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12254              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12255              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12256              MI.getOpcode() == PPC::SELECT_F4 ||
12257              MI.getOpcode() == PPC::SELECT_F8 ||
12258              MI.getOpcode() == PPC::SELECT_F16 ||
12259              MI.getOpcode() == PPC::SELECT_SPE ||
12260              MI.getOpcode() == PPC::SELECT_SPE4 ||
12261              MI.getOpcode() == PPC::SELECT_VRRC ||
12262              MI.getOpcode() == PPC::SELECT_VSFRC ||
12263              MI.getOpcode() == PPC::SELECT_VSSRC ||
12264              MI.getOpcode() == PPC::SELECT_VSRC) {
12265     // The incoming instruction knows the destination vreg to set, the
12266     // condition code register to branch on, the true/false values to
12267     // select between, and a branch opcode to use.
12268 
12269     //  thisMBB:
12270     //  ...
12271     //   TrueVal = ...
12272     //   cmpTY ccX, r1, r2
12273     //   bCC copy1MBB
12274     //   fallthrough --> copy0MBB
12275     MachineBasicBlock *thisMBB = BB;
12276     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12277     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12278     DebugLoc dl = MI.getDebugLoc();
12279     F->insert(It, copy0MBB);
12280     F->insert(It, sinkMBB);
12281 
12282     // Transfer the remainder of BB and its successor edges to sinkMBB.
12283     sinkMBB->splice(sinkMBB->begin(), BB,
12284                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12285     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12286 
12287     // Next, add the true and fallthrough blocks as its successors.
12288     BB->addSuccessor(copy0MBB);
12289     BB->addSuccessor(sinkMBB);
12290 
12291     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12292         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12293         MI.getOpcode() == PPC::SELECT_F16 ||
12294         MI.getOpcode() == PPC::SELECT_SPE4 ||
12295         MI.getOpcode() == PPC::SELECT_SPE ||
12296         MI.getOpcode() == PPC::SELECT_VRRC ||
12297         MI.getOpcode() == PPC::SELECT_VSFRC ||
12298         MI.getOpcode() == PPC::SELECT_VSSRC ||
12299         MI.getOpcode() == PPC::SELECT_VSRC) {
12300       BuildMI(BB, dl, TII->get(PPC::BC))
12301           .addReg(MI.getOperand(1).getReg())
12302           .addMBB(sinkMBB);
12303     } else {
12304       unsigned SelectPred = MI.getOperand(4).getImm();
12305       BuildMI(BB, dl, TII->get(PPC::BCC))
12306           .addImm(SelectPred)
12307           .addReg(MI.getOperand(1).getReg())
12308           .addMBB(sinkMBB);
12309     }
12310 
12311     //  copy0MBB:
12312     //   %FalseValue = ...
12313     //   # fallthrough to sinkMBB
12314     BB = copy0MBB;
12315 
12316     // Update machine-CFG edges
12317     BB->addSuccessor(sinkMBB);
12318 
12319     //  sinkMBB:
12320     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12321     //  ...
12322     BB = sinkMBB;
12323     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12324         .addReg(MI.getOperand(3).getReg())
12325         .addMBB(copy0MBB)
12326         .addReg(MI.getOperand(2).getReg())
12327         .addMBB(thisMBB);
12328   } else if (MI.getOpcode() == PPC::ReadTB) {
12329     // To read the 64-bit time-base register on a 32-bit target, we read the
12330     // two halves. Should the counter have wrapped while it was being read, we
12331     // need to try again.
12332     // ...
12333     // readLoop:
12334     // mfspr Rx,TBU # load from TBU
12335     // mfspr Ry,TB  # load from TB
12336     // mfspr Rz,TBU # load from TBU
12337     // cmpw crX,Rx,Rz # check if 'old'='new'
12338     // bne readLoop   # branch if they're not equal
12339     // ...
12340 
12341     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12342     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12343     DebugLoc dl = MI.getDebugLoc();
12344     F->insert(It, readMBB);
12345     F->insert(It, sinkMBB);
12346 
12347     // Transfer the remainder of BB and its successor edges to sinkMBB.
12348     sinkMBB->splice(sinkMBB->begin(), BB,
12349                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12350     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12351 
12352     BB->addSuccessor(readMBB);
12353     BB = readMBB;
12354 
12355     MachineRegisterInfo &RegInfo = F->getRegInfo();
12356     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12357     Register LoReg = MI.getOperand(0).getReg();
12358     Register HiReg = MI.getOperand(1).getReg();
12359 
12360     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12361     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12362     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12363 
12364     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12365 
12366     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12367         .addReg(HiReg)
12368         .addReg(ReadAgainReg);
12369     BuildMI(BB, dl, TII->get(PPC::BCC))
12370         .addImm(PPC::PRED_NE)
12371         .addReg(CmpReg)
12372         .addMBB(readMBB);
12373 
12374     BB->addSuccessor(readMBB);
12375     BB->addSuccessor(sinkMBB);
12376   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12377     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12378   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12379     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12380   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12381     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12382   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12383     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12384 
12385   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12386     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12387   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12388     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12389   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12390     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12391   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12392     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12393 
12394   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12395     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12396   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12397     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12398   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12399     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12400   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12401     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12402 
12403   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12404     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12405   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12406     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12407   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12408     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12409   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12410     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12411 
12412   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12413     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12414   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12415     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12416   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12417     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12418   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12419     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12420 
12421   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12422     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12423   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12424     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12425   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12426     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12427   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12428     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12429 
12430   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12431     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12432   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12433     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12434   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12435     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12436   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12437     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12438 
12439   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12440     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12441   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12442     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12443   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12444     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12445   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12446     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12447 
12448   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12449     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12450   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12451     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12452   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12453     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12454   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12455     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12456 
12457   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12458     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12459   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12460     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12461   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12462     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12463   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12464     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12465 
12466   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12467     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12468   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12469     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12470   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12471     BB = EmitAtomicBinary(MI, BB, 4, 0);
12472   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12473     BB = EmitAtomicBinary(MI, BB, 8, 0);
12474   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12475            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12476            (Subtarget.hasPartwordAtomics() &&
12477             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12478            (Subtarget.hasPartwordAtomics() &&
12479             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12480     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12481 
12482     auto LoadMnemonic = PPC::LDARX;
12483     auto StoreMnemonic = PPC::STDCX;
12484     switch (MI.getOpcode()) {
12485     default:
12486       llvm_unreachable("Compare and swap of unknown size");
12487     case PPC::ATOMIC_CMP_SWAP_I8:
12488       LoadMnemonic = PPC::LBARX;
12489       StoreMnemonic = PPC::STBCX;
12490       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12491       break;
12492     case PPC::ATOMIC_CMP_SWAP_I16:
12493       LoadMnemonic = PPC::LHARX;
12494       StoreMnemonic = PPC::STHCX;
12495       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12496       break;
12497     case PPC::ATOMIC_CMP_SWAP_I32:
12498       LoadMnemonic = PPC::LWARX;
12499       StoreMnemonic = PPC::STWCX;
12500       break;
12501     case PPC::ATOMIC_CMP_SWAP_I64:
12502       LoadMnemonic = PPC::LDARX;
12503       StoreMnemonic = PPC::STDCX;
12504       break;
12505     }
12506     Register dest = MI.getOperand(0).getReg();
12507     Register ptrA = MI.getOperand(1).getReg();
12508     Register ptrB = MI.getOperand(2).getReg();
12509     Register oldval = MI.getOperand(3).getReg();
12510     Register newval = MI.getOperand(4).getReg();
12511     DebugLoc dl = MI.getDebugLoc();
12512 
12513     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12514     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12515     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12516     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12517     F->insert(It, loop1MBB);
12518     F->insert(It, loop2MBB);
12519     F->insert(It, midMBB);
12520     F->insert(It, exitMBB);
12521     exitMBB->splice(exitMBB->begin(), BB,
12522                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12523     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12524 
12525     //  thisMBB:
12526     //   ...
12527     //   fallthrough --> loopMBB
12528     BB->addSuccessor(loop1MBB);
12529 
12530     // loop1MBB:
12531     //   l[bhwd]arx dest, ptr
12532     //   cmp[wd] dest, oldval
12533     //   bne- midMBB
12534     // loop2MBB:
12535     //   st[bhwd]cx. newval, ptr
12536     //   bne- loopMBB
12537     //   b exitBB
12538     // midMBB:
12539     //   st[bhwd]cx. dest, ptr
12540     // exitBB:
12541     BB = loop1MBB;
12542     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12543     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12544         .addReg(oldval)
12545         .addReg(dest);
12546     BuildMI(BB, dl, TII->get(PPC::BCC))
12547         .addImm(PPC::PRED_NE)
12548         .addReg(PPC::CR0)
12549         .addMBB(midMBB);
12550     BB->addSuccessor(loop2MBB);
12551     BB->addSuccessor(midMBB);
12552 
12553     BB = loop2MBB;
12554     BuildMI(BB, dl, TII->get(StoreMnemonic))
12555         .addReg(newval)
12556         .addReg(ptrA)
12557         .addReg(ptrB);
12558     BuildMI(BB, dl, TII->get(PPC::BCC))
12559         .addImm(PPC::PRED_NE)
12560         .addReg(PPC::CR0)
12561         .addMBB(loop1MBB);
12562     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12563     BB->addSuccessor(loop1MBB);
12564     BB->addSuccessor(exitMBB);
12565 
12566     BB = midMBB;
12567     BuildMI(BB, dl, TII->get(StoreMnemonic))
12568         .addReg(dest)
12569         .addReg(ptrA)
12570         .addReg(ptrB);
12571     BB->addSuccessor(exitMBB);
12572 
12573     //  exitMBB:
12574     //   ...
12575     BB = exitMBB;
12576   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12577              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12578     // We must use 64-bit registers for addresses when targeting 64-bit,
12579     // since we're actually doing arithmetic on them.  Other registers
12580     // can be 32-bit.
12581     bool is64bit = Subtarget.isPPC64();
12582     bool isLittleEndian = Subtarget.isLittleEndian();
12583     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12584 
12585     Register dest = MI.getOperand(0).getReg();
12586     Register ptrA = MI.getOperand(1).getReg();
12587     Register ptrB = MI.getOperand(2).getReg();
12588     Register oldval = MI.getOperand(3).getReg();
12589     Register newval = MI.getOperand(4).getReg();
12590     DebugLoc dl = MI.getDebugLoc();
12591 
12592     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12593     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12594     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12595     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12596     F->insert(It, loop1MBB);
12597     F->insert(It, loop2MBB);
12598     F->insert(It, midMBB);
12599     F->insert(It, exitMBB);
12600     exitMBB->splice(exitMBB->begin(), BB,
12601                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12602     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12603 
12604     MachineRegisterInfo &RegInfo = F->getRegInfo();
12605     const TargetRegisterClass *RC =
12606         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12607     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12608 
12609     Register PtrReg = RegInfo.createVirtualRegister(RC);
12610     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12611     Register ShiftReg =
12612         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12613     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12614     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12615     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12616     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12617     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12618     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12619     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12620     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12621     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12622     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12623     Register Ptr1Reg;
12624     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12625     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12626     //  thisMBB:
12627     //   ...
12628     //   fallthrough --> loopMBB
12629     BB->addSuccessor(loop1MBB);
12630 
12631     // The 4-byte load must be aligned, while a char or short may be
12632     // anywhere in the word.  Hence all this nasty bookkeeping code.
12633     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12634     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12635     //   xori shift, shift1, 24 [16]
12636     //   rlwinm ptr, ptr1, 0, 0, 29
12637     //   slw newval2, newval, shift
12638     //   slw oldval2, oldval,shift
12639     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12640     //   slw mask, mask2, shift
12641     //   and newval3, newval2, mask
12642     //   and oldval3, oldval2, mask
12643     // loop1MBB:
12644     //   lwarx tmpDest, ptr
12645     //   and tmp, tmpDest, mask
12646     //   cmpw tmp, oldval3
12647     //   bne- midMBB
12648     // loop2MBB:
12649     //   andc tmp2, tmpDest, mask
12650     //   or tmp4, tmp2, newval3
12651     //   stwcx. tmp4, ptr
12652     //   bne- loop1MBB
12653     //   b exitBB
12654     // midMBB:
12655     //   stwcx. tmpDest, ptr
12656     // exitBB:
12657     //   srw dest, tmpDest, shift
12658     if (ptrA != ZeroReg) {
12659       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12660       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12661           .addReg(ptrA)
12662           .addReg(ptrB);
12663     } else {
12664       Ptr1Reg = ptrB;
12665     }
12666 
12667     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12668     // mode.
12669     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12670         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12671         .addImm(3)
12672         .addImm(27)
12673         .addImm(is8bit ? 28 : 27);
12674     if (!isLittleEndian)
12675       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12676           .addReg(Shift1Reg)
12677           .addImm(is8bit ? 24 : 16);
12678     if (is64bit)
12679       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12680           .addReg(Ptr1Reg)
12681           .addImm(0)
12682           .addImm(61);
12683     else
12684       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12685           .addReg(Ptr1Reg)
12686           .addImm(0)
12687           .addImm(0)
12688           .addImm(29);
12689     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12690         .addReg(newval)
12691         .addReg(ShiftReg);
12692     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12693         .addReg(oldval)
12694         .addReg(ShiftReg);
12695     if (is8bit)
12696       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12697     else {
12698       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12699       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12700           .addReg(Mask3Reg)
12701           .addImm(65535);
12702     }
12703     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12704         .addReg(Mask2Reg)
12705         .addReg(ShiftReg);
12706     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12707         .addReg(NewVal2Reg)
12708         .addReg(MaskReg);
12709     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12710         .addReg(OldVal2Reg)
12711         .addReg(MaskReg);
12712 
12713     BB = loop1MBB;
12714     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12715         .addReg(ZeroReg)
12716         .addReg(PtrReg);
12717     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12718         .addReg(TmpDestReg)
12719         .addReg(MaskReg);
12720     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12721         .addReg(TmpReg)
12722         .addReg(OldVal3Reg);
12723     BuildMI(BB, dl, TII->get(PPC::BCC))
12724         .addImm(PPC::PRED_NE)
12725         .addReg(PPC::CR0)
12726         .addMBB(midMBB);
12727     BB->addSuccessor(loop2MBB);
12728     BB->addSuccessor(midMBB);
12729 
12730     BB = loop2MBB;
12731     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12732         .addReg(TmpDestReg)
12733         .addReg(MaskReg);
12734     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12735         .addReg(Tmp2Reg)
12736         .addReg(NewVal3Reg);
12737     BuildMI(BB, dl, TII->get(PPC::STWCX))
12738         .addReg(Tmp4Reg)
12739         .addReg(ZeroReg)
12740         .addReg(PtrReg);
12741     BuildMI(BB, dl, TII->get(PPC::BCC))
12742         .addImm(PPC::PRED_NE)
12743         .addReg(PPC::CR0)
12744         .addMBB(loop1MBB);
12745     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12746     BB->addSuccessor(loop1MBB);
12747     BB->addSuccessor(exitMBB);
12748 
12749     BB = midMBB;
12750     BuildMI(BB, dl, TII->get(PPC::STWCX))
12751         .addReg(TmpDestReg)
12752         .addReg(ZeroReg)
12753         .addReg(PtrReg);
12754     BB->addSuccessor(exitMBB);
12755 
12756     //  exitMBB:
12757     //   ...
12758     BB = exitMBB;
12759     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12760         .addReg(TmpReg)
12761         .addReg(ShiftReg);
12762   } else if (MI.getOpcode() == PPC::FADDrtz) {
12763     // This pseudo performs an FADD with rounding mode temporarily forced
12764     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12765     // is not modeled at the SelectionDAG level.
12766     Register Dest = MI.getOperand(0).getReg();
12767     Register Src1 = MI.getOperand(1).getReg();
12768     Register Src2 = MI.getOperand(2).getReg();
12769     DebugLoc dl = MI.getDebugLoc();
12770 
12771     MachineRegisterInfo &RegInfo = F->getRegInfo();
12772     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12773 
12774     // Save FPSCR value.
12775     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12776 
12777     // Set rounding mode to round-to-zero.
12778     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12779         .addImm(31)
12780         .addReg(PPC::RM, RegState::ImplicitDefine);
12781 
12782     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12783         .addImm(30)
12784         .addReg(PPC::RM, RegState::ImplicitDefine);
12785 
12786     // Perform addition.
12787     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12788                    .addReg(Src1)
12789                    .addReg(Src2);
12790     if (MI.getFlag(MachineInstr::NoFPExcept))
12791       MIB.setMIFlag(MachineInstr::NoFPExcept);
12792 
12793     // Restore FPSCR value.
12794     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12795   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12796              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12797              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12798              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12799     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12800                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12801                           ? PPC::ANDI8_rec
12802                           : PPC::ANDI_rec;
12803     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12804                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12805 
12806     MachineRegisterInfo &RegInfo = F->getRegInfo();
12807     Register Dest = RegInfo.createVirtualRegister(
12808         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12809 
12810     DebugLoc Dl = MI.getDebugLoc();
12811     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12812         .addReg(MI.getOperand(1).getReg())
12813         .addImm(1);
12814     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12815             MI.getOperand(0).getReg())
12816         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12817   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12818     DebugLoc Dl = MI.getDebugLoc();
12819     MachineRegisterInfo &RegInfo = F->getRegInfo();
12820     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12821     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12822     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12823             MI.getOperand(0).getReg())
12824         .addReg(CRReg);
12825   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12826     DebugLoc Dl = MI.getDebugLoc();
12827     unsigned Imm = MI.getOperand(1).getImm();
12828     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12829     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12830             MI.getOperand(0).getReg())
12831         .addReg(PPC::CR0EQ);
12832   } else if (MI.getOpcode() == PPC::SETRNDi) {
12833     DebugLoc dl = MI.getDebugLoc();
12834     Register OldFPSCRReg = MI.getOperand(0).getReg();
12835 
12836     // Save FPSCR value.
12837     if (MRI.use_empty(OldFPSCRReg))
12838       BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12839     else
12840       BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12841 
12842     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12843     // the following settings:
12844     //   00 Round to nearest
12845     //   01 Round to 0
12846     //   10 Round to +inf
12847     //   11 Round to -inf
12848 
12849     // When the operand is immediate, using the two least significant bits of
12850     // the immediate to set the bits 62:63 of FPSCR.
12851     unsigned Mode = MI.getOperand(1).getImm();
12852     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12853         .addImm(31)
12854         .addReg(PPC::RM, RegState::ImplicitDefine);
12855 
12856     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12857         .addImm(30)
12858         .addReg(PPC::RM, RegState::ImplicitDefine);
12859   } else if (MI.getOpcode() == PPC::SETRND) {
12860     DebugLoc dl = MI.getDebugLoc();
12861 
12862     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12863     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12864     // If the target doesn't have DirectMove, we should use stack to do the
12865     // conversion, because the target doesn't have the instructions like mtvsrd
12866     // or mfvsrd to do this conversion directly.
12867     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12868       if (Subtarget.hasDirectMove()) {
12869         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12870           .addReg(SrcReg);
12871       } else {
12872         // Use stack to do the register copy.
12873         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12874         MachineRegisterInfo &RegInfo = F->getRegInfo();
12875         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12876         if (RC == &PPC::F8RCRegClass) {
12877           // Copy register from F8RCRegClass to G8RCRegclass.
12878           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12879                  "Unsupported RegClass.");
12880 
12881           StoreOp = PPC::STFD;
12882           LoadOp = PPC::LD;
12883         } else {
12884           // Copy register from G8RCRegClass to F8RCRegclass.
12885           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12886                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12887                  "Unsupported RegClass.");
12888         }
12889 
12890         MachineFrameInfo &MFI = F->getFrameInfo();
12891         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12892 
12893         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12894             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12895             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12896             MFI.getObjectAlign(FrameIdx));
12897 
12898         // Store the SrcReg into the stack.
12899         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12900           .addReg(SrcReg)
12901           .addImm(0)
12902           .addFrameIndex(FrameIdx)
12903           .addMemOperand(MMOStore);
12904 
12905         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12906             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12907             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12908             MFI.getObjectAlign(FrameIdx));
12909 
12910         // Load from the stack where SrcReg is stored, and save to DestReg,
12911         // so we have done the RegClass conversion from RegClass::SrcReg to
12912         // RegClass::DestReg.
12913         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12914           .addImm(0)
12915           .addFrameIndex(FrameIdx)
12916           .addMemOperand(MMOLoad);
12917       }
12918     };
12919 
12920     Register OldFPSCRReg = MI.getOperand(0).getReg();
12921 
12922     // Save FPSCR value.
12923     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12924 
12925     // When the operand is gprc register, use two least significant bits of the
12926     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12927     //
12928     // copy OldFPSCRTmpReg, OldFPSCRReg
12929     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12930     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12931     // copy NewFPSCRReg, NewFPSCRTmpReg
12932     // mtfsf 255, NewFPSCRReg
12933     MachineOperand SrcOp = MI.getOperand(1);
12934     MachineRegisterInfo &RegInfo = F->getRegInfo();
12935     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12936 
12937     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12938 
12939     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12940     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12941 
12942     // The first operand of INSERT_SUBREG should be a register which has
12943     // subregisters, we only care about its RegClass, so we should use an
12944     // IMPLICIT_DEF register.
12945     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12946     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12947       .addReg(ImDefReg)
12948       .add(SrcOp)
12949       .addImm(1);
12950 
12951     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12952     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12953       .addReg(OldFPSCRTmpReg)
12954       .addReg(ExtSrcReg)
12955       .addImm(0)
12956       .addImm(62);
12957 
12958     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12959     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12960 
12961     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12962     // bits of FPSCR.
12963     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12964       .addImm(255)
12965       .addReg(NewFPSCRReg)
12966       .addImm(0)
12967       .addImm(0);
12968   } else if (MI.getOpcode() == PPC::SETFLM) {
12969     DebugLoc Dl = MI.getDebugLoc();
12970 
12971     // Result of setflm is previous FPSCR content, so we need to save it first.
12972     Register OldFPSCRReg = MI.getOperand(0).getReg();
12973     if (MRI.use_empty(OldFPSCRReg))
12974       BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12975     else
12976       BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12977 
12978     // Put bits in 32:63 to FPSCR.
12979     Register NewFPSCRReg = MI.getOperand(1).getReg();
12980     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12981         .addImm(255)
12982         .addReg(NewFPSCRReg)
12983         .addImm(0)
12984         .addImm(0);
12985   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12986              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12987     return emitProbedAlloca(MI, BB);
12988   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12989     DebugLoc DL = MI.getDebugLoc();
12990     Register Src = MI.getOperand(2).getReg();
12991     Register Lo = MI.getOperand(0).getReg();
12992     Register Hi = MI.getOperand(1).getReg();
12993     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12994         .addDef(Lo)
12995         .addUse(Src, 0, PPC::sub_gp8_x1);
12996     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12997         .addDef(Hi)
12998         .addUse(Src, 0, PPC::sub_gp8_x0);
12999   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
13000              MI.getOpcode() == PPC::STQX_PSEUDO) {
13001     DebugLoc DL = MI.getDebugLoc();
13002     // Ptr is used as the ptr_rc_no_r0 part
13003     // of LQ/STQ's memory operand and adding result of RA and RB,
13004     // so it has to be g8rc_and_g8rc_nox0.
13005     Register Ptr =
13006         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
13007     Register Val = MI.getOperand(0).getReg();
13008     Register RA = MI.getOperand(1).getReg();
13009     Register RB = MI.getOperand(2).getReg();
13010     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
13011     BuildMI(*BB, MI, DL,
13012             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
13013                                               : TII->get(PPC::STQ))
13014         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
13015         .addImm(0)
13016         .addReg(Ptr);
13017   } else {
13018     llvm_unreachable("Unexpected instr type to insert");
13019   }
13020 
13021   MI.eraseFromParent(); // The pseudo instruction is gone now.
13022   return BB;
13023 }
13024 
13025 //===----------------------------------------------------------------------===//
13026 // Target Optimization Hooks
13027 //===----------------------------------------------------------------------===//
13028 
13029 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
13030   // For the estimates, convergence is quadratic, so we essentially double the
13031   // number of digits correct after every iteration. For both FRE and FRSQRTE,
13032   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
13033   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
13034   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
13035   if (VT.getScalarType() == MVT::f64)
13036     RefinementSteps++;
13037   return RefinementSteps;
13038 }
13039 
13040 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
13041                                             const DenormalMode &Mode) const {
13042   // We only have VSX Vector Test for software Square Root.
13043   EVT VT = Op.getValueType();
13044   if (!isTypeLegal(MVT::i1) ||
13045       (VT != MVT::f64 &&
13046        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
13047     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
13048 
13049   SDLoc DL(Op);
13050   // The output register of FTSQRT is CR field.
13051   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
13052   // ftsqrt BF,FRB
13053   // Let e_b be the unbiased exponent of the double-precision
13054   // floating-point operand in register FRB.
13055   // fe_flag is set to 1 if either of the following conditions occurs.
13056   //   - The double-precision floating-point operand in register FRB is a zero,
13057   //     a NaN, or an infinity, or a negative value.
13058   //   - e_b is less than or equal to -970.
13059   // Otherwise fe_flag is set to 0.
13060   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
13061   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
13062   // exponent is less than -970)
13063   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
13064   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
13065                                     FTSQRT, SRIdxVal),
13066                  0);
13067 }
13068 
13069 SDValue
13070 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
13071                                                SelectionDAG &DAG) const {
13072   // We only have VSX Vector Square Root.
13073   EVT VT = Op.getValueType();
13074   if (VT != MVT::f64 &&
13075       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
13076     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
13077 
13078   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
13079 }
13080 
13081 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
13082                                            int Enabled, int &RefinementSteps,
13083                                            bool &UseOneConstNR,
13084                                            bool Reciprocal) const {
13085   EVT VT = Operand.getValueType();
13086   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
13087       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
13088       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13089       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13090     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13091       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13092 
13093     // The Newton-Raphson computation with a single constant does not provide
13094     // enough accuracy on some CPUs.
13095     UseOneConstNR = !Subtarget.needsTwoConstNR();
13096     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
13097   }
13098   return SDValue();
13099 }
13100 
13101 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
13102                                             int Enabled,
13103                                             int &RefinementSteps) const {
13104   EVT VT = Operand.getValueType();
13105   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13106       (VT == MVT::f64 && Subtarget.hasFRE()) ||
13107       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13108       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13109     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13110       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13111     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13112   }
13113   return SDValue();
13114 }
13115 
13116 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13117   // Note: This functionality is used only when unsafe-fp-math is enabled, and
13118   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13119   // enabled for division), this functionality is redundant with the default
13120   // combiner logic (once the division -> reciprocal/multiply transformation
13121   // has taken place). As a result, this matters more for older cores than for
13122   // newer ones.
13123 
13124   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13125   // reciprocal if there are two or more FDIVs (for embedded cores with only
13126   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13127   switch (Subtarget.getCPUDirective()) {
13128   default:
13129     return 3;
13130   case PPC::DIR_440:
13131   case PPC::DIR_A2:
13132   case PPC::DIR_E500:
13133   case PPC::DIR_E500mc:
13134   case PPC::DIR_E5500:
13135     return 2;
13136   }
13137 }
13138 
13139 // isConsecutiveLSLoc needs to work even if all adds have not yet been
13140 // collapsed, and so we need to look through chains of them.
13141 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13142                                      int64_t& Offset, SelectionDAG &DAG) {
13143   if (DAG.isBaseWithConstantOffset(Loc)) {
13144     Base = Loc.getOperand(0);
13145     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13146 
13147     // The base might itself be a base plus an offset, and if so, accumulate
13148     // that as well.
13149     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13150   }
13151 }
13152 
13153 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13154                             unsigned Bytes, int Dist,
13155                             SelectionDAG &DAG) {
13156   if (VT.getSizeInBits() / 8 != Bytes)
13157     return false;
13158 
13159   SDValue BaseLoc = Base->getBasePtr();
13160   if (Loc.getOpcode() == ISD::FrameIndex) {
13161     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13162       return false;
13163     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13164     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13165     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13166     int FS  = MFI.getObjectSize(FI);
13167     int BFS = MFI.getObjectSize(BFI);
13168     if (FS != BFS || FS != (int)Bytes) return false;
13169     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13170   }
13171 
13172   SDValue Base1 = Loc, Base2 = BaseLoc;
13173   int64_t Offset1 = 0, Offset2 = 0;
13174   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13175   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13176   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13177     return true;
13178 
13179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13180   const GlobalValue *GV1 = nullptr;
13181   const GlobalValue *GV2 = nullptr;
13182   Offset1 = 0;
13183   Offset2 = 0;
13184   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13185   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13186   if (isGA1 && isGA2 && GV1 == GV2)
13187     return Offset1 == (Offset2 + Dist*Bytes);
13188   return false;
13189 }
13190 
13191 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13192 // not enforce equality of the chain operands.
13193 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13194                             unsigned Bytes, int Dist,
13195                             SelectionDAG &DAG) {
13196   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13197     EVT VT = LS->getMemoryVT();
13198     SDValue Loc = LS->getBasePtr();
13199     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13200   }
13201 
13202   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13203     EVT VT;
13204     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13205     default: return false;
13206     case Intrinsic::ppc_altivec_lvx:
13207     case Intrinsic::ppc_altivec_lvxl:
13208     case Intrinsic::ppc_vsx_lxvw4x:
13209     case Intrinsic::ppc_vsx_lxvw4x_be:
13210       VT = MVT::v4i32;
13211       break;
13212     case Intrinsic::ppc_vsx_lxvd2x:
13213     case Intrinsic::ppc_vsx_lxvd2x_be:
13214       VT = MVT::v2f64;
13215       break;
13216     case Intrinsic::ppc_altivec_lvebx:
13217       VT = MVT::i8;
13218       break;
13219     case Intrinsic::ppc_altivec_lvehx:
13220       VT = MVT::i16;
13221       break;
13222     case Intrinsic::ppc_altivec_lvewx:
13223       VT = MVT::i32;
13224       break;
13225     }
13226 
13227     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13228   }
13229 
13230   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13231     EVT VT;
13232     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13233     default: return false;
13234     case Intrinsic::ppc_altivec_stvx:
13235     case Intrinsic::ppc_altivec_stvxl:
13236     case Intrinsic::ppc_vsx_stxvw4x:
13237       VT = MVT::v4i32;
13238       break;
13239     case Intrinsic::ppc_vsx_stxvd2x:
13240       VT = MVT::v2f64;
13241       break;
13242     case Intrinsic::ppc_vsx_stxvw4x_be:
13243       VT = MVT::v4i32;
13244       break;
13245     case Intrinsic::ppc_vsx_stxvd2x_be:
13246       VT = MVT::v2f64;
13247       break;
13248     case Intrinsic::ppc_altivec_stvebx:
13249       VT = MVT::i8;
13250       break;
13251     case Intrinsic::ppc_altivec_stvehx:
13252       VT = MVT::i16;
13253       break;
13254     case Intrinsic::ppc_altivec_stvewx:
13255       VT = MVT::i32;
13256       break;
13257     }
13258 
13259     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13260   }
13261 
13262   return false;
13263 }
13264 
13265 // Return true is there is a nearyby consecutive load to the one provided
13266 // (regardless of alignment). We search up and down the chain, looking though
13267 // token factors and other loads (but nothing else). As a result, a true result
13268 // indicates that it is safe to create a new consecutive load adjacent to the
13269 // load provided.
13270 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13271   SDValue Chain = LD->getChain();
13272   EVT VT = LD->getMemoryVT();
13273 
13274   SmallSet<SDNode *, 16> LoadRoots;
13275   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13276   SmallSet<SDNode *, 16> Visited;
13277 
13278   // First, search up the chain, branching to follow all token-factor operands.
13279   // If we find a consecutive load, then we're done, otherwise, record all
13280   // nodes just above the top-level loads and token factors.
13281   while (!Queue.empty()) {
13282     SDNode *ChainNext = Queue.pop_back_val();
13283     if (!Visited.insert(ChainNext).second)
13284       continue;
13285 
13286     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13287       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13288         return true;
13289 
13290       if (!Visited.count(ChainLD->getChain().getNode()))
13291         Queue.push_back(ChainLD->getChain().getNode());
13292     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13293       for (const SDUse &O : ChainNext->ops())
13294         if (!Visited.count(O.getNode()))
13295           Queue.push_back(O.getNode());
13296     } else
13297       LoadRoots.insert(ChainNext);
13298   }
13299 
13300   // Second, search down the chain, starting from the top-level nodes recorded
13301   // in the first phase. These top-level nodes are the nodes just above all
13302   // loads and token factors. Starting with their uses, recursively look though
13303   // all loads (just the chain uses) and token factors to find a consecutive
13304   // load.
13305   Visited.clear();
13306   Queue.clear();
13307 
13308   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13309        IE = LoadRoots.end(); I != IE; ++I) {
13310     Queue.push_back(*I);
13311 
13312     while (!Queue.empty()) {
13313       SDNode *LoadRoot = Queue.pop_back_val();
13314       if (!Visited.insert(LoadRoot).second)
13315         continue;
13316 
13317       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13318         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13319           return true;
13320 
13321       for (SDNode *U : LoadRoot->uses())
13322         if (((isa<MemSDNode>(U) &&
13323               cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13324              U->getOpcode() == ISD::TokenFactor) &&
13325             !Visited.count(U))
13326           Queue.push_back(U);
13327     }
13328   }
13329 
13330   return false;
13331 }
13332 
13333 /// This function is called when we have proved that a SETCC node can be replaced
13334 /// by subtraction (and other supporting instructions) so that the result of
13335 /// comparison is kept in a GPR instead of CR. This function is purely for
13336 /// codegen purposes and has some flags to guide the codegen process.
13337 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13338                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13339   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13340 
13341   // Zero extend the operands to the largest legal integer. Originally, they
13342   // must be of a strictly smaller size.
13343   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13344                          DAG.getConstant(Size, DL, MVT::i32));
13345   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13346                          DAG.getConstant(Size, DL, MVT::i32));
13347 
13348   // Swap if needed. Depends on the condition code.
13349   if (Swap)
13350     std::swap(Op0, Op1);
13351 
13352   // Subtract extended integers.
13353   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13354 
13355   // Move the sign bit to the least significant position and zero out the rest.
13356   // Now the least significant bit carries the result of original comparison.
13357   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13358                              DAG.getConstant(Size - 1, DL, MVT::i32));
13359   auto Final = Shifted;
13360 
13361   // Complement the result if needed. Based on the condition code.
13362   if (Complement)
13363     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13364                         DAG.getConstant(1, DL, MVT::i64));
13365 
13366   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13367 }
13368 
13369 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13370                                                   DAGCombinerInfo &DCI) const {
13371   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13372 
13373   SelectionDAG &DAG = DCI.DAG;
13374   SDLoc DL(N);
13375 
13376   // Size of integers being compared has a critical role in the following
13377   // analysis, so we prefer to do this when all types are legal.
13378   if (!DCI.isAfterLegalizeDAG())
13379     return SDValue();
13380 
13381   // If all users of SETCC extend its value to a legal integer type
13382   // then we replace SETCC with a subtraction
13383   for (const SDNode *U : N->uses())
13384     if (U->getOpcode() != ISD::ZERO_EXTEND)
13385       return SDValue();
13386 
13387   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13388   auto OpSize = N->getOperand(0).getValueSizeInBits();
13389 
13390   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13391 
13392   if (OpSize < Size) {
13393     switch (CC) {
13394     default: break;
13395     case ISD::SETULT:
13396       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13397     case ISD::SETULE:
13398       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13399     case ISD::SETUGT:
13400       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13401     case ISD::SETUGE:
13402       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13403     }
13404   }
13405 
13406   return SDValue();
13407 }
13408 
13409 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13410                                                   DAGCombinerInfo &DCI) const {
13411   SelectionDAG &DAG = DCI.DAG;
13412   SDLoc dl(N);
13413 
13414   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13415   // If we're tracking CR bits, we need to be careful that we don't have:
13416   //   trunc(binary-ops(zext(x), zext(y)))
13417   // or
13418   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13419   // such that we're unnecessarily moving things into GPRs when it would be
13420   // better to keep them in CR bits.
13421 
13422   // Note that trunc here can be an actual i1 trunc, or can be the effective
13423   // truncation that comes from a setcc or select_cc.
13424   if (N->getOpcode() == ISD::TRUNCATE &&
13425       N->getValueType(0) != MVT::i1)
13426     return SDValue();
13427 
13428   if (N->getOperand(0).getValueType() != MVT::i32 &&
13429       N->getOperand(0).getValueType() != MVT::i64)
13430     return SDValue();
13431 
13432   if (N->getOpcode() == ISD::SETCC ||
13433       N->getOpcode() == ISD::SELECT_CC) {
13434     // If we're looking at a comparison, then we need to make sure that the
13435     // high bits (all except for the first) don't matter the result.
13436     ISD::CondCode CC =
13437       cast<CondCodeSDNode>(N->getOperand(
13438         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13439     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13440 
13441     if (ISD::isSignedIntSetCC(CC)) {
13442       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13443           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13444         return SDValue();
13445     } else if (ISD::isUnsignedIntSetCC(CC)) {
13446       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13447                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13448           !DAG.MaskedValueIsZero(N->getOperand(1),
13449                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13450         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13451                                              : SDValue());
13452     } else {
13453       // This is neither a signed nor an unsigned comparison, just make sure
13454       // that the high bits are equal.
13455       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13456       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13457 
13458       // We don't really care about what is known about the first bit (if
13459       // anything), so pretend that it is known zero for both to ensure they can
13460       // be compared as constants.
13461       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13462       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13463 
13464       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13465           Op1Known.getConstant() != Op2Known.getConstant())
13466         return SDValue();
13467     }
13468   }
13469 
13470   // We now know that the higher-order bits are irrelevant, we just need to
13471   // make sure that all of the intermediate operations are bit operations, and
13472   // all inputs are extensions.
13473   if (N->getOperand(0).getOpcode() != ISD::AND &&
13474       N->getOperand(0).getOpcode() != ISD::OR  &&
13475       N->getOperand(0).getOpcode() != ISD::XOR &&
13476       N->getOperand(0).getOpcode() != ISD::SELECT &&
13477       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13478       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13479       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13480       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13481       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13482     return SDValue();
13483 
13484   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13485       N->getOperand(1).getOpcode() != ISD::AND &&
13486       N->getOperand(1).getOpcode() != ISD::OR  &&
13487       N->getOperand(1).getOpcode() != ISD::XOR &&
13488       N->getOperand(1).getOpcode() != ISD::SELECT &&
13489       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13490       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13491       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13492       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13493       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13494     return SDValue();
13495 
13496   SmallVector<SDValue, 4> Inputs;
13497   SmallVector<SDValue, 8> BinOps, PromOps;
13498   SmallPtrSet<SDNode *, 16> Visited;
13499 
13500   for (unsigned i = 0; i < 2; ++i) {
13501     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13502           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13503           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13504           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13505         isa<ConstantSDNode>(N->getOperand(i)))
13506       Inputs.push_back(N->getOperand(i));
13507     else
13508       BinOps.push_back(N->getOperand(i));
13509 
13510     if (N->getOpcode() == ISD::TRUNCATE)
13511       break;
13512   }
13513 
13514   // Visit all inputs, collect all binary operations (and, or, xor and
13515   // select) that are all fed by extensions.
13516   while (!BinOps.empty()) {
13517     SDValue BinOp = BinOps.pop_back_val();
13518 
13519     if (!Visited.insert(BinOp.getNode()).second)
13520       continue;
13521 
13522     PromOps.push_back(BinOp);
13523 
13524     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13525       // The condition of the select is not promoted.
13526       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13527         continue;
13528       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13529         continue;
13530 
13531       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13532             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13533             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13534            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13535           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13536         Inputs.push_back(BinOp.getOperand(i));
13537       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13538                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13539                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13540                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13541                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13542                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13543                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13544                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13545                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13546         BinOps.push_back(BinOp.getOperand(i));
13547       } else {
13548         // We have an input that is not an extension or another binary
13549         // operation; we'll abort this transformation.
13550         return SDValue();
13551       }
13552     }
13553   }
13554 
13555   // Make sure that this is a self-contained cluster of operations (which
13556   // is not quite the same thing as saying that everything has only one
13557   // use).
13558   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13559     if (isa<ConstantSDNode>(Inputs[i]))
13560       continue;
13561 
13562     for (const SDNode *User : Inputs[i].getNode()->uses()) {
13563       if (User != N && !Visited.count(User))
13564         return SDValue();
13565 
13566       // Make sure that we're not going to promote the non-output-value
13567       // operand(s) or SELECT or SELECT_CC.
13568       // FIXME: Although we could sometimes handle this, and it does occur in
13569       // practice that one of the condition inputs to the select is also one of
13570       // the outputs, we currently can't deal with this.
13571       if (User->getOpcode() == ISD::SELECT) {
13572         if (User->getOperand(0) == Inputs[i])
13573           return SDValue();
13574       } else if (User->getOpcode() == ISD::SELECT_CC) {
13575         if (User->getOperand(0) == Inputs[i] ||
13576             User->getOperand(1) == Inputs[i])
13577           return SDValue();
13578       }
13579     }
13580   }
13581 
13582   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13583     for (const SDNode *User : PromOps[i].getNode()->uses()) {
13584       if (User != N && !Visited.count(User))
13585         return SDValue();
13586 
13587       // Make sure that we're not going to promote the non-output-value
13588       // operand(s) or SELECT or SELECT_CC.
13589       // FIXME: Although we could sometimes handle this, and it does occur in
13590       // practice that one of the condition inputs to the select is also one of
13591       // the outputs, we currently can't deal with this.
13592       if (User->getOpcode() == ISD::SELECT) {
13593         if (User->getOperand(0) == PromOps[i])
13594           return SDValue();
13595       } else if (User->getOpcode() == ISD::SELECT_CC) {
13596         if (User->getOperand(0) == PromOps[i] ||
13597             User->getOperand(1) == PromOps[i])
13598           return SDValue();
13599       }
13600     }
13601   }
13602 
13603   // Replace all inputs with the extension operand.
13604   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13605     // Constants may have users outside the cluster of to-be-promoted nodes,
13606     // and so we need to replace those as we do the promotions.
13607     if (isa<ConstantSDNode>(Inputs[i]))
13608       continue;
13609     else
13610       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13611   }
13612 
13613   std::list<HandleSDNode> PromOpHandles;
13614   for (auto &PromOp : PromOps)
13615     PromOpHandles.emplace_back(PromOp);
13616 
13617   // Replace all operations (these are all the same, but have a different
13618   // (i1) return type). DAG.getNode will validate that the types of
13619   // a binary operator match, so go through the list in reverse so that
13620   // we've likely promoted both operands first. Any intermediate truncations or
13621   // extensions disappear.
13622   while (!PromOpHandles.empty()) {
13623     SDValue PromOp = PromOpHandles.back().getValue();
13624     PromOpHandles.pop_back();
13625 
13626     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13627         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13628         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13629         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13630       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13631           PromOp.getOperand(0).getValueType() != MVT::i1) {
13632         // The operand is not yet ready (see comment below).
13633         PromOpHandles.emplace_front(PromOp);
13634         continue;
13635       }
13636 
13637       SDValue RepValue = PromOp.getOperand(0);
13638       if (isa<ConstantSDNode>(RepValue))
13639         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13640 
13641       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13642       continue;
13643     }
13644 
13645     unsigned C;
13646     switch (PromOp.getOpcode()) {
13647     default:             C = 0; break;
13648     case ISD::SELECT:    C = 1; break;
13649     case ISD::SELECT_CC: C = 2; break;
13650     }
13651 
13652     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13653          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13654         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13655          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13656       // The to-be-promoted operands of this node have not yet been
13657       // promoted (this should be rare because we're going through the
13658       // list backward, but if one of the operands has several users in
13659       // this cluster of to-be-promoted nodes, it is possible).
13660       PromOpHandles.emplace_front(PromOp);
13661       continue;
13662     }
13663 
13664     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13665                                 PromOp.getNode()->op_end());
13666 
13667     // If there are any constant inputs, make sure they're replaced now.
13668     for (unsigned i = 0; i < 2; ++i)
13669       if (isa<ConstantSDNode>(Ops[C+i]))
13670         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13671 
13672     DAG.ReplaceAllUsesOfValueWith(PromOp,
13673       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13674   }
13675 
13676   // Now we're left with the initial truncation itself.
13677   if (N->getOpcode() == ISD::TRUNCATE)
13678     return N->getOperand(0);
13679 
13680   // Otherwise, this is a comparison. The operands to be compared have just
13681   // changed type (to i1), but everything else is the same.
13682   return SDValue(N, 0);
13683 }
13684 
13685 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13686                                                   DAGCombinerInfo &DCI) const {
13687   SelectionDAG &DAG = DCI.DAG;
13688   SDLoc dl(N);
13689 
13690   // If we're tracking CR bits, we need to be careful that we don't have:
13691   //   zext(binary-ops(trunc(x), trunc(y)))
13692   // or
13693   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13694   // such that we're unnecessarily moving things into CR bits that can more
13695   // efficiently stay in GPRs. Note that if we're not certain that the high
13696   // bits are set as required by the final extension, we still may need to do
13697   // some masking to get the proper behavior.
13698 
13699   // This same functionality is important on PPC64 when dealing with
13700   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13701   // the return values of functions. Because it is so similar, it is handled
13702   // here as well.
13703 
13704   if (N->getValueType(0) != MVT::i32 &&
13705       N->getValueType(0) != MVT::i64)
13706     return SDValue();
13707 
13708   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13709         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13710     return SDValue();
13711 
13712   if (N->getOperand(0).getOpcode() != ISD::AND &&
13713       N->getOperand(0).getOpcode() != ISD::OR  &&
13714       N->getOperand(0).getOpcode() != ISD::XOR &&
13715       N->getOperand(0).getOpcode() != ISD::SELECT &&
13716       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13717     return SDValue();
13718 
13719   SmallVector<SDValue, 4> Inputs;
13720   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13721   SmallPtrSet<SDNode *, 16> Visited;
13722 
13723   // Visit all inputs, collect all binary operations (and, or, xor and
13724   // select) that are all fed by truncations.
13725   while (!BinOps.empty()) {
13726     SDValue BinOp = BinOps.pop_back_val();
13727 
13728     if (!Visited.insert(BinOp.getNode()).second)
13729       continue;
13730 
13731     PromOps.push_back(BinOp);
13732 
13733     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13734       // The condition of the select is not promoted.
13735       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13736         continue;
13737       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13738         continue;
13739 
13740       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13741           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13742         Inputs.push_back(BinOp.getOperand(i));
13743       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13744                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13745                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13746                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13747                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13748         BinOps.push_back(BinOp.getOperand(i));
13749       } else {
13750         // We have an input that is not a truncation or another binary
13751         // operation; we'll abort this transformation.
13752         return SDValue();
13753       }
13754     }
13755   }
13756 
13757   // The operands of a select that must be truncated when the select is
13758   // promoted because the operand is actually part of the to-be-promoted set.
13759   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13760 
13761   // Make sure that this is a self-contained cluster of operations (which
13762   // is not quite the same thing as saying that everything has only one
13763   // use).
13764   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13765     if (isa<ConstantSDNode>(Inputs[i]))
13766       continue;
13767 
13768     for (SDNode *User : Inputs[i].getNode()->uses()) {
13769       if (User != N && !Visited.count(User))
13770         return SDValue();
13771 
13772       // If we're going to promote the non-output-value operand(s) or SELECT or
13773       // SELECT_CC, record them for truncation.
13774       if (User->getOpcode() == ISD::SELECT) {
13775         if (User->getOperand(0) == Inputs[i])
13776           SelectTruncOp[0].insert(std::make_pair(User,
13777                                     User->getOperand(0).getValueType()));
13778       } else if (User->getOpcode() == ISD::SELECT_CC) {
13779         if (User->getOperand(0) == Inputs[i])
13780           SelectTruncOp[0].insert(std::make_pair(User,
13781                                     User->getOperand(0).getValueType()));
13782         if (User->getOperand(1) == Inputs[i])
13783           SelectTruncOp[1].insert(std::make_pair(User,
13784                                     User->getOperand(1).getValueType()));
13785       }
13786     }
13787   }
13788 
13789   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13790     for (SDNode *User : PromOps[i].getNode()->uses()) {
13791       if (User != N && !Visited.count(User))
13792         return SDValue();
13793 
13794       // If we're going to promote the non-output-value operand(s) or SELECT or
13795       // SELECT_CC, record them for truncation.
13796       if (User->getOpcode() == ISD::SELECT) {
13797         if (User->getOperand(0) == PromOps[i])
13798           SelectTruncOp[0].insert(std::make_pair(User,
13799                                     User->getOperand(0).getValueType()));
13800       } else if (User->getOpcode() == ISD::SELECT_CC) {
13801         if (User->getOperand(0) == PromOps[i])
13802           SelectTruncOp[0].insert(std::make_pair(User,
13803                                     User->getOperand(0).getValueType()));
13804         if (User->getOperand(1) == PromOps[i])
13805           SelectTruncOp[1].insert(std::make_pair(User,
13806                                     User->getOperand(1).getValueType()));
13807       }
13808     }
13809   }
13810 
13811   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13812   bool ReallyNeedsExt = false;
13813   if (N->getOpcode() != ISD::ANY_EXTEND) {
13814     // If all of the inputs are not already sign/zero extended, then
13815     // we'll still need to do that at the end.
13816     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13817       if (isa<ConstantSDNode>(Inputs[i]))
13818         continue;
13819 
13820       unsigned OpBits =
13821         Inputs[i].getOperand(0).getValueSizeInBits();
13822       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13823 
13824       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13825            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13826                                   APInt::getHighBitsSet(OpBits,
13827                                                         OpBits-PromBits))) ||
13828           (N->getOpcode() == ISD::SIGN_EXTEND &&
13829            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13830              (OpBits-(PromBits-1)))) {
13831         ReallyNeedsExt = true;
13832         break;
13833       }
13834     }
13835   }
13836 
13837   // Replace all inputs, either with the truncation operand, or a
13838   // truncation or extension to the final output type.
13839   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13840     // Constant inputs need to be replaced with the to-be-promoted nodes that
13841     // use them because they might have users outside of the cluster of
13842     // promoted nodes.
13843     if (isa<ConstantSDNode>(Inputs[i]))
13844       continue;
13845 
13846     SDValue InSrc = Inputs[i].getOperand(0);
13847     if (Inputs[i].getValueType() == N->getValueType(0))
13848       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13849     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13850       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13851         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13852     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13853       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13854         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13855     else
13856       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13857         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13858   }
13859 
13860   std::list<HandleSDNode> PromOpHandles;
13861   for (auto &PromOp : PromOps)
13862     PromOpHandles.emplace_back(PromOp);
13863 
13864   // Replace all operations (these are all the same, but have a different
13865   // (promoted) return type). DAG.getNode will validate that the types of
13866   // a binary operator match, so go through the list in reverse so that
13867   // we've likely promoted both operands first.
13868   while (!PromOpHandles.empty()) {
13869     SDValue PromOp = PromOpHandles.back().getValue();
13870     PromOpHandles.pop_back();
13871 
13872     unsigned C;
13873     switch (PromOp.getOpcode()) {
13874     default:             C = 0; break;
13875     case ISD::SELECT:    C = 1; break;
13876     case ISD::SELECT_CC: C = 2; break;
13877     }
13878 
13879     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13880          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13881         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13882          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13883       // The to-be-promoted operands of this node have not yet been
13884       // promoted (this should be rare because we're going through the
13885       // list backward, but if one of the operands has several users in
13886       // this cluster of to-be-promoted nodes, it is possible).
13887       PromOpHandles.emplace_front(PromOp);
13888       continue;
13889     }
13890 
13891     // For SELECT and SELECT_CC nodes, we do a similar check for any
13892     // to-be-promoted comparison inputs.
13893     if (PromOp.getOpcode() == ISD::SELECT ||
13894         PromOp.getOpcode() == ISD::SELECT_CC) {
13895       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13896            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13897           (SelectTruncOp[1].count(PromOp.getNode()) &&
13898            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13899         PromOpHandles.emplace_front(PromOp);
13900         continue;
13901       }
13902     }
13903 
13904     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13905                                 PromOp.getNode()->op_end());
13906 
13907     // If this node has constant inputs, then they'll need to be promoted here.
13908     for (unsigned i = 0; i < 2; ++i) {
13909       if (!isa<ConstantSDNode>(Ops[C+i]))
13910         continue;
13911       if (Ops[C+i].getValueType() == N->getValueType(0))
13912         continue;
13913 
13914       if (N->getOpcode() == ISD::SIGN_EXTEND)
13915         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13916       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13917         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13918       else
13919         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13920     }
13921 
13922     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13923     // truncate them again to the original value type.
13924     if (PromOp.getOpcode() == ISD::SELECT ||
13925         PromOp.getOpcode() == ISD::SELECT_CC) {
13926       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13927       if (SI0 != SelectTruncOp[0].end())
13928         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13929       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13930       if (SI1 != SelectTruncOp[1].end())
13931         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13932     }
13933 
13934     DAG.ReplaceAllUsesOfValueWith(PromOp,
13935       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13936   }
13937 
13938   // Now we're left with the initial extension itself.
13939   if (!ReallyNeedsExt)
13940     return N->getOperand(0);
13941 
13942   // To zero extend, just mask off everything except for the first bit (in the
13943   // i1 case).
13944   if (N->getOpcode() == ISD::ZERO_EXTEND)
13945     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13946                        DAG.getConstant(APInt::getLowBitsSet(
13947                                          N->getValueSizeInBits(0), PromBits),
13948                                        dl, N->getValueType(0)));
13949 
13950   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13951          "Invalid extension type");
13952   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13953   SDValue ShiftCst =
13954       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13955   return DAG.getNode(
13956       ISD::SRA, dl, N->getValueType(0),
13957       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13958       ShiftCst);
13959 }
13960 
13961 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13962                                         DAGCombinerInfo &DCI) const {
13963   assert(N->getOpcode() == ISD::SETCC &&
13964          "Should be called with a SETCC node");
13965 
13966   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13967   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13968     SDValue LHS = N->getOperand(0);
13969     SDValue RHS = N->getOperand(1);
13970 
13971     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13972     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13973         LHS.hasOneUse())
13974       std::swap(LHS, RHS);
13975 
13976     // x == 0-y --> x+y == 0
13977     // x != 0-y --> x+y != 0
13978     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13979         RHS.hasOneUse()) {
13980       SDLoc DL(N);
13981       SelectionDAG &DAG = DCI.DAG;
13982       EVT VT = N->getValueType(0);
13983       EVT OpVT = LHS.getValueType();
13984       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13985       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13986     }
13987   }
13988 
13989   return DAGCombineTruncBoolExt(N, DCI);
13990 }
13991 
13992 // Is this an extending load from an f32 to an f64?
13993 static bool isFPExtLoad(SDValue Op) {
13994   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13995     return LD->getExtensionType() == ISD::EXTLOAD &&
13996       Op.getValueType() == MVT::f64;
13997   return false;
13998 }
13999 
14000 /// Reduces the number of fp-to-int conversion when building a vector.
14001 ///
14002 /// If this vector is built out of floating to integer conversions,
14003 /// transform it to a vector built out of floating point values followed by a
14004 /// single floating to integer conversion of the vector.
14005 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
14006 /// becomes (fptosi (build_vector ($A, $B, ...)))
14007 SDValue PPCTargetLowering::
14008 combineElementTruncationToVectorTruncation(SDNode *N,
14009                                            DAGCombinerInfo &DCI) const {
14010   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14011          "Should be called with a BUILD_VECTOR node");
14012 
14013   SelectionDAG &DAG = DCI.DAG;
14014   SDLoc dl(N);
14015 
14016   SDValue FirstInput = N->getOperand(0);
14017   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
14018          "The input operand must be an fp-to-int conversion.");
14019 
14020   // This combine happens after legalization so the fp_to_[su]i nodes are
14021   // already converted to PPCSISD nodes.
14022   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
14023   if (FirstConversion == PPCISD::FCTIDZ ||
14024       FirstConversion == PPCISD::FCTIDUZ ||
14025       FirstConversion == PPCISD::FCTIWZ ||
14026       FirstConversion == PPCISD::FCTIWUZ) {
14027     bool IsSplat = true;
14028     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
14029       FirstConversion == PPCISD::FCTIWUZ;
14030     EVT SrcVT = FirstInput.getOperand(0).getValueType();
14031     SmallVector<SDValue, 4> Ops;
14032     EVT TargetVT = N->getValueType(0);
14033     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14034       SDValue NextOp = N->getOperand(i);
14035       if (NextOp.getOpcode() != PPCISD::MFVSR)
14036         return SDValue();
14037       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
14038       if (NextConversion != FirstConversion)
14039         return SDValue();
14040       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
14041       // This is not valid if the input was originally double precision. It is
14042       // also not profitable to do unless this is an extending load in which
14043       // case doing this combine will allow us to combine consecutive loads.
14044       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
14045         return SDValue();
14046       if (N->getOperand(i) != FirstInput)
14047         IsSplat = false;
14048     }
14049 
14050     // If this is a splat, we leave it as-is since there will be only a single
14051     // fp-to-int conversion followed by a splat of the integer. This is better
14052     // for 32-bit and smaller ints and neutral for 64-bit ints.
14053     if (IsSplat)
14054       return SDValue();
14055 
14056     // Now that we know we have the right type of node, get its operands
14057     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14058       SDValue In = N->getOperand(i).getOperand(0);
14059       if (Is32Bit) {
14060         // For 32-bit values, we need to add an FP_ROUND node (if we made it
14061         // here, we know that all inputs are extending loads so this is safe).
14062         if (In.isUndef())
14063           Ops.push_back(DAG.getUNDEF(SrcVT));
14064         else {
14065           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
14066                                       MVT::f32, In.getOperand(0),
14067                                       DAG.getIntPtrConstant(1, dl));
14068           Ops.push_back(Trunc);
14069         }
14070       } else
14071         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
14072     }
14073 
14074     unsigned Opcode;
14075     if (FirstConversion == PPCISD::FCTIDZ ||
14076         FirstConversion == PPCISD::FCTIWZ)
14077       Opcode = ISD::FP_TO_SINT;
14078     else
14079       Opcode = ISD::FP_TO_UINT;
14080 
14081     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
14082     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
14083     return DAG.getNode(Opcode, dl, TargetVT, BV);
14084   }
14085   return SDValue();
14086 }
14087 
14088 /// Reduce the number of loads when building a vector.
14089 ///
14090 /// Building a vector out of multiple loads can be converted to a load
14091 /// of the vector type if the loads are consecutive. If the loads are
14092 /// consecutive but in descending order, a shuffle is added at the end
14093 /// to reorder the vector.
14094 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
14095   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14096          "Should be called with a BUILD_VECTOR node");
14097 
14098   SDLoc dl(N);
14099 
14100   // Return early for non byte-sized type, as they can't be consecutive.
14101   if (!N->getValueType(0).getVectorElementType().isByteSized())
14102     return SDValue();
14103 
14104   bool InputsAreConsecutiveLoads = true;
14105   bool InputsAreReverseConsecutive = true;
14106   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14107   SDValue FirstInput = N->getOperand(0);
14108   bool IsRoundOfExtLoad = false;
14109 
14110   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14111       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14112     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
14113     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
14114   }
14115   // Not a build vector of (possibly fp_rounded) loads.
14116   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14117       N->getNumOperands() == 1)
14118     return SDValue();
14119 
14120   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14121     // If any inputs are fp_round(extload), they all must be.
14122     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14123       return SDValue();
14124 
14125     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14126       N->getOperand(i);
14127     if (NextInput.getOpcode() != ISD::LOAD)
14128       return SDValue();
14129 
14130     SDValue PreviousInput =
14131       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14132     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
14133     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
14134 
14135     // If any inputs are fp_round(extload), they all must be.
14136     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14137       return SDValue();
14138 
14139     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
14140       InputsAreConsecutiveLoads = false;
14141     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14142       InputsAreReverseConsecutive = false;
14143 
14144     // Exit early if the loads are neither consecutive nor reverse consecutive.
14145     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14146       return SDValue();
14147   }
14148 
14149   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14150          "The loads cannot be both consecutive and reverse consecutive.");
14151 
14152   SDValue FirstLoadOp =
14153     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14154   SDValue LastLoadOp =
14155     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14156                        N->getOperand(N->getNumOperands()-1);
14157 
14158   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14159   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14160   if (InputsAreConsecutiveLoads) {
14161     assert(LD1 && "Input needs to be a LoadSDNode.");
14162     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14163                        LD1->getBasePtr(), LD1->getPointerInfo(),
14164                        LD1->getAlignment());
14165   }
14166   if (InputsAreReverseConsecutive) {
14167     assert(LDL && "Input needs to be a LoadSDNode.");
14168     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14169                                LDL->getBasePtr(), LDL->getPointerInfo(),
14170                                LDL->getAlignment());
14171     SmallVector<int, 16> Ops;
14172     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14173       Ops.push_back(i);
14174 
14175     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14176                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14177   }
14178   return SDValue();
14179 }
14180 
14181 // This function adds the required vector_shuffle needed to get
14182 // the elements of the vector extract in the correct position
14183 // as specified by the CorrectElems encoding.
14184 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14185                                       SDValue Input, uint64_t Elems,
14186                                       uint64_t CorrectElems) {
14187   SDLoc dl(N);
14188 
14189   unsigned NumElems = Input.getValueType().getVectorNumElements();
14190   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14191 
14192   // Knowing the element indices being extracted from the original
14193   // vector and the order in which they're being inserted, just put
14194   // them at element indices required for the instruction.
14195   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14196     if (DAG.getDataLayout().isLittleEndian())
14197       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14198     else
14199       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14200     CorrectElems = CorrectElems >> 8;
14201     Elems = Elems >> 8;
14202   }
14203 
14204   SDValue Shuffle =
14205       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14206                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14207 
14208   EVT VT = N->getValueType(0);
14209   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14210 
14211   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14212                                Input.getValueType().getVectorElementType(),
14213                                VT.getVectorNumElements());
14214   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14215                      DAG.getValueType(ExtVT));
14216 }
14217 
14218 // Look for build vector patterns where input operands come from sign
14219 // extended vector_extract elements of specific indices. If the correct indices
14220 // aren't used, add a vector shuffle to fix up the indices and create
14221 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14222 // during instruction selection.
14223 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14224   // This array encodes the indices that the vector sign extend instructions
14225   // extract from when extending from one type to another for both BE and LE.
14226   // The right nibble of each byte corresponds to the LE incides.
14227   // and the left nibble of each byte corresponds to the BE incides.
14228   // For example: 0x3074B8FC  byte->word
14229   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14230   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14231   // For example: 0x000070F8  byte->double word
14232   // For LE: the allowed indices are: 0x0,0x8
14233   // For BE: the allowed indices are: 0x7,0xF
14234   uint64_t TargetElems[] = {
14235       0x3074B8FC, // b->w
14236       0x000070F8, // b->d
14237       0x10325476, // h->w
14238       0x00003074, // h->d
14239       0x00001032, // w->d
14240   };
14241 
14242   uint64_t Elems = 0;
14243   int Index;
14244   SDValue Input;
14245 
14246   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14247     if (!Op)
14248       return false;
14249     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14250         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14251       return false;
14252 
14253     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14254     // of the right width.
14255     SDValue Extract = Op.getOperand(0);
14256     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14257       Extract = Extract.getOperand(0);
14258     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14259       return false;
14260 
14261     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14262     if (!ExtOp)
14263       return false;
14264 
14265     Index = ExtOp->getZExtValue();
14266     if (Input && Input != Extract.getOperand(0))
14267       return false;
14268 
14269     if (!Input)
14270       Input = Extract.getOperand(0);
14271 
14272     Elems = Elems << 8;
14273     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14274     Elems |= Index;
14275 
14276     return true;
14277   };
14278 
14279   // If the build vector operands aren't sign extended vector extracts,
14280   // of the same input vector, then return.
14281   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14282     if (!isSExtOfVecExtract(N->getOperand(i))) {
14283       return SDValue();
14284     }
14285   }
14286 
14287   // If the vector extract indicies are not correct, add the appropriate
14288   // vector_shuffle.
14289   int TgtElemArrayIdx;
14290   int InputSize = Input.getValueType().getScalarSizeInBits();
14291   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14292   if (InputSize + OutputSize == 40)
14293     TgtElemArrayIdx = 0;
14294   else if (InputSize + OutputSize == 72)
14295     TgtElemArrayIdx = 1;
14296   else if (InputSize + OutputSize == 48)
14297     TgtElemArrayIdx = 2;
14298   else if (InputSize + OutputSize == 80)
14299     TgtElemArrayIdx = 3;
14300   else if (InputSize + OutputSize == 96)
14301     TgtElemArrayIdx = 4;
14302   else
14303     return SDValue();
14304 
14305   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14306   CorrectElems = DAG.getDataLayout().isLittleEndian()
14307                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14308                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14309   if (Elems != CorrectElems) {
14310     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14311   }
14312 
14313   // Regular lowering will catch cases where a shuffle is not needed.
14314   return SDValue();
14315 }
14316 
14317 // Look for the pattern of a load from a narrow width to i128, feeding
14318 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14319 // (LXVRZX). This node represents a zero extending load that will be matched
14320 // to the Load VSX Vector Rightmost instructions.
14321 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14322   SDLoc DL(N);
14323 
14324   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14325   if (N->getValueType(0) != MVT::v1i128)
14326     return SDValue();
14327 
14328   SDValue Operand = N->getOperand(0);
14329   // Proceed with the transformation if the operand to the BUILD_VECTOR
14330   // is a load instruction.
14331   if (Operand.getOpcode() != ISD::LOAD)
14332     return SDValue();
14333 
14334   auto *LD = cast<LoadSDNode>(Operand);
14335   EVT MemoryType = LD->getMemoryVT();
14336 
14337   // This transformation is only valid if the we are loading either a byte,
14338   // halfword, word, or doubleword.
14339   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14340                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14341 
14342   // Ensure that the load from the narrow width is being zero extended to i128.
14343   if (!ValidLDType ||
14344       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14345        LD->getExtensionType() != ISD::EXTLOAD))
14346     return SDValue();
14347 
14348   SDValue LoadOps[] = {
14349       LD->getChain(), LD->getBasePtr(),
14350       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14351 
14352   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14353                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14354                                  LoadOps, MemoryType, LD->getMemOperand());
14355 }
14356 
14357 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14358                                                  DAGCombinerInfo &DCI) const {
14359   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14360          "Should be called with a BUILD_VECTOR node");
14361 
14362   SelectionDAG &DAG = DCI.DAG;
14363   SDLoc dl(N);
14364 
14365   if (!Subtarget.hasVSX())
14366     return SDValue();
14367 
14368   // The target independent DAG combiner will leave a build_vector of
14369   // float-to-int conversions intact. We can generate MUCH better code for
14370   // a float-to-int conversion of a vector of floats.
14371   SDValue FirstInput = N->getOperand(0);
14372   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14373     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14374     if (Reduced)
14375       return Reduced;
14376   }
14377 
14378   // If we're building a vector out of consecutive loads, just load that
14379   // vector type.
14380   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14381   if (Reduced)
14382     return Reduced;
14383 
14384   // If we're building a vector out of extended elements from another vector
14385   // we have P9 vector integer extend instructions. The code assumes legal
14386   // input types (i.e. it can't handle things like v4i16) so do not run before
14387   // legalization.
14388   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14389     Reduced = combineBVOfVecSExt(N, DAG);
14390     if (Reduced)
14391       return Reduced;
14392   }
14393 
14394   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14395   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14396   // is a load from <valid narrow width> to i128.
14397   if (Subtarget.isISA3_1()) {
14398     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14399     if (BVOfZLoad)
14400       return BVOfZLoad;
14401   }
14402 
14403   if (N->getValueType(0) != MVT::v2f64)
14404     return SDValue();
14405 
14406   // Looking for:
14407   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14408   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14409       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14410     return SDValue();
14411   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14412       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14413     return SDValue();
14414   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14415     return SDValue();
14416 
14417   SDValue Ext1 = FirstInput.getOperand(0);
14418   SDValue Ext2 = N->getOperand(1).getOperand(0);
14419   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14420      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14421     return SDValue();
14422 
14423   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14424   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14425   if (!Ext1Op || !Ext2Op)
14426     return SDValue();
14427   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14428       Ext1.getOperand(0) != Ext2.getOperand(0))
14429     return SDValue();
14430 
14431   int FirstElem = Ext1Op->getZExtValue();
14432   int SecondElem = Ext2Op->getZExtValue();
14433   int SubvecIdx;
14434   if (FirstElem == 0 && SecondElem == 1)
14435     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14436   else if (FirstElem == 2 && SecondElem == 3)
14437     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14438   else
14439     return SDValue();
14440 
14441   SDValue SrcVec = Ext1.getOperand(0);
14442   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14443     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14444   return DAG.getNode(NodeType, dl, MVT::v2f64,
14445                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14446 }
14447 
14448 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14449                                               DAGCombinerInfo &DCI) const {
14450   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14451           N->getOpcode() == ISD::UINT_TO_FP) &&
14452          "Need an int -> FP conversion node here");
14453 
14454   if (useSoftFloat() || !Subtarget.has64BitSupport())
14455     return SDValue();
14456 
14457   SelectionDAG &DAG = DCI.DAG;
14458   SDLoc dl(N);
14459   SDValue Op(N, 0);
14460 
14461   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14462   // from the hardware.
14463   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14464     return SDValue();
14465   if (!Op.getOperand(0).getValueType().isSimple())
14466     return SDValue();
14467   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14468       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14469     return SDValue();
14470 
14471   SDValue FirstOperand(Op.getOperand(0));
14472   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14473     (FirstOperand.getValueType() == MVT::i8 ||
14474      FirstOperand.getValueType() == MVT::i16);
14475   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14476     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14477     bool DstDouble = Op.getValueType() == MVT::f64;
14478     unsigned ConvOp = Signed ?
14479       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14480       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14481     SDValue WidthConst =
14482       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14483                             dl, false);
14484     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14485     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14486     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14487                                          DAG.getVTList(MVT::f64, MVT::Other),
14488                                          Ops, MVT::i8, LDN->getMemOperand());
14489 
14490     // For signed conversion, we need to sign-extend the value in the VSR
14491     if (Signed) {
14492       SDValue ExtOps[] = { Ld, WidthConst };
14493       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14494       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14495     } else
14496       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14497   }
14498 
14499 
14500   // For i32 intermediate values, unfortunately, the conversion functions
14501   // leave the upper 32 bits of the value are undefined. Within the set of
14502   // scalar instructions, we have no method for zero- or sign-extending the
14503   // value. Thus, we cannot handle i32 intermediate values here.
14504   if (Op.getOperand(0).getValueType() == MVT::i32)
14505     return SDValue();
14506 
14507   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14508          "UINT_TO_FP is supported only with FPCVT");
14509 
14510   // If we have FCFIDS, then use it when converting to single-precision.
14511   // Otherwise, convert to double-precision and then round.
14512   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14513                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14514                                                             : PPCISD::FCFIDS)
14515                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14516                                                             : PPCISD::FCFID);
14517   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14518                   ? MVT::f32
14519                   : MVT::f64;
14520 
14521   // If we're converting from a float, to an int, and back to a float again,
14522   // then we don't need the store/load pair at all.
14523   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14524        Subtarget.hasFPCVT()) ||
14525       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14526     SDValue Src = Op.getOperand(0).getOperand(0);
14527     if (Src.getValueType() == MVT::f32) {
14528       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14529       DCI.AddToWorklist(Src.getNode());
14530     } else if (Src.getValueType() != MVT::f64) {
14531       // Make sure that we don't pick up a ppc_fp128 source value.
14532       return SDValue();
14533     }
14534 
14535     unsigned FCTOp =
14536       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14537                                                         PPCISD::FCTIDUZ;
14538 
14539     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14540     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14541 
14542     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14543       FP = DAG.getNode(ISD::FP_ROUND, dl,
14544                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14545       DCI.AddToWorklist(FP.getNode());
14546     }
14547 
14548     return FP;
14549   }
14550 
14551   return SDValue();
14552 }
14553 
14554 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14555 // builtins) into loads with swaps.
14556 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14557                                               DAGCombinerInfo &DCI) const {
14558   SelectionDAG &DAG = DCI.DAG;
14559   SDLoc dl(N);
14560   SDValue Chain;
14561   SDValue Base;
14562   MachineMemOperand *MMO;
14563 
14564   switch (N->getOpcode()) {
14565   default:
14566     llvm_unreachable("Unexpected opcode for little endian VSX load");
14567   case ISD::LOAD: {
14568     LoadSDNode *LD = cast<LoadSDNode>(N);
14569     Chain = LD->getChain();
14570     Base = LD->getBasePtr();
14571     MMO = LD->getMemOperand();
14572     // If the MMO suggests this isn't a load of a full vector, leave
14573     // things alone.  For a built-in, we have to make the change for
14574     // correctness, so if there is a size problem that will be a bug.
14575     if (MMO->getSize() < 16)
14576       return SDValue();
14577     break;
14578   }
14579   case ISD::INTRINSIC_W_CHAIN: {
14580     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14581     Chain = Intrin->getChain();
14582     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14583     // us what we want. Get operand 2 instead.
14584     Base = Intrin->getOperand(2);
14585     MMO = Intrin->getMemOperand();
14586     break;
14587   }
14588   }
14589 
14590   MVT VecTy = N->getValueType(0).getSimpleVT();
14591 
14592   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14593   // aligned and the type is a vector with elements up to 4 bytes
14594   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14595       VecTy.getScalarSizeInBits() <= 32) {
14596     return SDValue();
14597   }
14598 
14599   SDValue LoadOps[] = { Chain, Base };
14600   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14601                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14602                                          LoadOps, MVT::v2f64, MMO);
14603 
14604   DCI.AddToWorklist(Load.getNode());
14605   Chain = Load.getValue(1);
14606   SDValue Swap = DAG.getNode(
14607       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14608   DCI.AddToWorklist(Swap.getNode());
14609 
14610   // Add a bitcast if the resulting load type doesn't match v2f64.
14611   if (VecTy != MVT::v2f64) {
14612     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14613     DCI.AddToWorklist(N.getNode());
14614     // Package {bitcast value, swap's chain} to match Load's shape.
14615     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14616                        N, Swap.getValue(1));
14617   }
14618 
14619   return Swap;
14620 }
14621 
14622 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14623 // builtins) into stores with swaps.
14624 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14625                                                DAGCombinerInfo &DCI) const {
14626   SelectionDAG &DAG = DCI.DAG;
14627   SDLoc dl(N);
14628   SDValue Chain;
14629   SDValue Base;
14630   unsigned SrcOpnd;
14631   MachineMemOperand *MMO;
14632 
14633   switch (N->getOpcode()) {
14634   default:
14635     llvm_unreachable("Unexpected opcode for little endian VSX store");
14636   case ISD::STORE: {
14637     StoreSDNode *ST = cast<StoreSDNode>(N);
14638     Chain = ST->getChain();
14639     Base = ST->getBasePtr();
14640     MMO = ST->getMemOperand();
14641     SrcOpnd = 1;
14642     // If the MMO suggests this isn't a store of a full vector, leave
14643     // things alone.  For a built-in, we have to make the change for
14644     // correctness, so if there is a size problem that will be a bug.
14645     if (MMO->getSize() < 16)
14646       return SDValue();
14647     break;
14648   }
14649   case ISD::INTRINSIC_VOID: {
14650     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14651     Chain = Intrin->getChain();
14652     // Intrin->getBasePtr() oddly does not get what we want.
14653     Base = Intrin->getOperand(3);
14654     MMO = Intrin->getMemOperand();
14655     SrcOpnd = 2;
14656     break;
14657   }
14658   }
14659 
14660   SDValue Src = N->getOperand(SrcOpnd);
14661   MVT VecTy = Src.getValueType().getSimpleVT();
14662 
14663   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14664   // aligned and the type is a vector with elements up to 4 bytes
14665   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14666       VecTy.getScalarSizeInBits() <= 32) {
14667     return SDValue();
14668   }
14669 
14670   // All stores are done as v2f64 and possible bit cast.
14671   if (VecTy != MVT::v2f64) {
14672     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14673     DCI.AddToWorklist(Src.getNode());
14674   }
14675 
14676   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14677                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14678   DCI.AddToWorklist(Swap.getNode());
14679   Chain = Swap.getValue(1);
14680   SDValue StoreOps[] = { Chain, Swap, Base };
14681   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14682                                           DAG.getVTList(MVT::Other),
14683                                           StoreOps, VecTy, MMO);
14684   DCI.AddToWorklist(Store.getNode());
14685   return Store;
14686 }
14687 
14688 // Handle DAG combine for STORE (FP_TO_INT F).
14689 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14690                                                DAGCombinerInfo &DCI) const {
14691 
14692   SelectionDAG &DAG = DCI.DAG;
14693   SDLoc dl(N);
14694   unsigned Opcode = N->getOperand(1).getOpcode();
14695 
14696   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14697          && "Not a FP_TO_INT Instruction!");
14698 
14699   SDValue Val = N->getOperand(1).getOperand(0);
14700   EVT Op1VT = N->getOperand(1).getValueType();
14701   EVT ResVT = Val.getValueType();
14702 
14703   if (!isTypeLegal(ResVT))
14704     return SDValue();
14705 
14706   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14707   bool ValidTypeForStoreFltAsInt =
14708         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14709          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14710 
14711   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14712     return SDValue();
14713 
14714   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14715       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14716     return SDValue();
14717 
14718   // Extend f32 values to f64
14719   if (ResVT.getScalarSizeInBits() == 32) {
14720     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14721     DCI.AddToWorklist(Val.getNode());
14722   }
14723 
14724   // Set signed or unsigned conversion opcode.
14725   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14726                           PPCISD::FP_TO_SINT_IN_VSR :
14727                           PPCISD::FP_TO_UINT_IN_VSR;
14728 
14729   Val = DAG.getNode(ConvOpcode,
14730                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14731   DCI.AddToWorklist(Val.getNode());
14732 
14733   // Set number of bytes being converted.
14734   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14735   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14736                     DAG.getIntPtrConstant(ByteSize, dl, false),
14737                     DAG.getValueType(Op1VT) };
14738 
14739   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14740           DAG.getVTList(MVT::Other), Ops,
14741           cast<StoreSDNode>(N)->getMemoryVT(),
14742           cast<StoreSDNode>(N)->getMemOperand());
14743 
14744   DCI.AddToWorklist(Val.getNode());
14745   return Val;
14746 }
14747 
14748 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14749   // Check that the source of the element keeps flipping
14750   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14751   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14752   for (int i = 1, e = Mask.size(); i < e; i++) {
14753     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14754       return false;
14755     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14756       return false;
14757     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14758   }
14759   return true;
14760 }
14761 
14762 static bool isSplatBV(SDValue Op) {
14763   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14764     return false;
14765   SDValue FirstOp;
14766 
14767   // Find first non-undef input.
14768   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14769     FirstOp = Op.getOperand(i);
14770     if (!FirstOp.isUndef())
14771       break;
14772   }
14773 
14774   // All inputs are undef or the same as the first non-undef input.
14775   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14776     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14777       return false;
14778   return true;
14779 }
14780 
14781 static SDValue isScalarToVec(SDValue Op) {
14782   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14783     return Op;
14784   if (Op.getOpcode() != ISD::BITCAST)
14785     return SDValue();
14786   Op = Op.getOperand(0);
14787   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14788     return Op;
14789   return SDValue();
14790 }
14791 
14792 // Fix up the shuffle mask to account for the fact that the result of
14793 // scalar_to_vector is not in lane zero. This just takes all values in
14794 // the ranges specified by the min/max indices and adds the number of
14795 // elements required to ensure each element comes from the respective
14796 // position in the valid lane.
14797 // On little endian, that's just the corresponding element in the other
14798 // half of the vector. On big endian, it is in the same half but right
14799 // justified rather than left justified in that half.
14800 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14801                                             int LHSMaxIdx, int RHSMinIdx,
14802                                             int RHSMaxIdx, int HalfVec,
14803                                             unsigned ValidLaneWidth,
14804                                             const PPCSubtarget &Subtarget) {
14805   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14806     int Idx = ShuffV[i];
14807     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14808       ShuffV[i] +=
14809           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14810   }
14811 }
14812 
14813 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14814 // the original is:
14815 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14816 // In such a case, just change the shuffle mask to extract the element
14817 // from the permuted index.
14818 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14819                                const PPCSubtarget &Subtarget) {
14820   SDLoc dl(OrigSToV);
14821   EVT VT = OrigSToV.getValueType();
14822   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14823          "Expecting a SCALAR_TO_VECTOR here");
14824   SDValue Input = OrigSToV.getOperand(0);
14825 
14826   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14827     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14828     SDValue OrigVector = Input.getOperand(0);
14829 
14830     // Can't handle non-const element indices or different vector types
14831     // for the input to the extract and the output of the scalar_to_vector.
14832     if (Idx && VT == OrigVector.getValueType()) {
14833       unsigned NumElts = VT.getVectorNumElements();
14834       assert(
14835           NumElts > 1 &&
14836           "Cannot produce a permuted scalar_to_vector for one element vector");
14837       SmallVector<int, 16> NewMask(NumElts, -1);
14838       unsigned ResultInElt = NumElts / 2;
14839       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14840       NewMask[ResultInElt] = Idx->getZExtValue();
14841       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14842     }
14843   }
14844   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14845                      OrigSToV.getOperand(0));
14846 }
14847 
14848 // On little endian subtargets, combine shuffles such as:
14849 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14850 // into:
14851 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14852 // because the latter can be matched to a single instruction merge.
14853 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14854 // to put the value into element zero. Adjust the shuffle mask so that the
14855 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14856 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14857 // nodes with elements smaller than doubleword because all the ways
14858 // of getting scalar data into a vector register put the value in the
14859 // rightmost element of the left half of the vector.
14860 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14861                                                 SelectionDAG &DAG) const {
14862   SDValue LHS = SVN->getOperand(0);
14863   SDValue RHS = SVN->getOperand(1);
14864   auto Mask = SVN->getMask();
14865   int NumElts = LHS.getValueType().getVectorNumElements();
14866   SDValue Res(SVN, 0);
14867   SDLoc dl(SVN);
14868   bool IsLittleEndian = Subtarget.isLittleEndian();
14869 
14870   // On big endian targets this is only useful for subtargets with direct moves.
14871   // On little endian targets it would be useful for all subtargets with VSX.
14872   // However adding special handling for LE subtargets without direct moves
14873   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14874   // which includes direct moves.
14875   if (!Subtarget.hasDirectMove())
14876     return Res;
14877 
14878   // If this is not a shuffle of a shuffle and the first element comes from
14879   // the second vector, canonicalize to the commuted form. This will make it
14880   // more likely to match one of the single instruction patterns.
14881   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14882       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14883     std::swap(LHS, RHS);
14884     Res = DAG.getCommutedVectorShuffle(*SVN);
14885     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14886   }
14887 
14888   // Adjust the shuffle mask if either input vector comes from a
14889   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14890   // form (to prevent the need for a swap).
14891   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14892   SDValue SToVLHS = isScalarToVec(LHS);
14893   SDValue SToVRHS = isScalarToVec(RHS);
14894   if (SToVLHS || SToVRHS) {
14895     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14896                             : SToVRHS.getValueType().getVectorNumElements();
14897     int NumEltsOut = ShuffV.size();
14898     // The width of the "valid lane" (i.e. the lane that contains the value that
14899     // is vectorized) needs to be expressed in terms of the number of elements
14900     // of the shuffle. It is thereby the ratio of the values before and after
14901     // any bitcast.
14902     unsigned ValidLaneWidth =
14903         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14904                       LHS.getValueType().getScalarSizeInBits()
14905                 : SToVRHS.getValueType().getScalarSizeInBits() /
14906                       RHS.getValueType().getScalarSizeInBits();
14907 
14908     // Initially assume that neither input is permuted. These will be adjusted
14909     // accordingly if either input is.
14910     int LHSMaxIdx = -1;
14911     int RHSMinIdx = -1;
14912     int RHSMaxIdx = -1;
14913     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14914 
14915     // Get the permuted scalar to vector nodes for the source(s) that come from
14916     // ISD::SCALAR_TO_VECTOR.
14917     // On big endian systems, this only makes sense for element sizes smaller
14918     // than 64 bits since for 64-bit elements, all instructions already put
14919     // the value into element zero. Since scalar size of LHS and RHS may differ
14920     // after isScalarToVec, this should be checked using their own sizes.
14921     if (SToVLHS) {
14922       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14923         return Res;
14924       // Set up the values for the shuffle vector fixup.
14925       LHSMaxIdx = NumEltsOut / NumEltsIn;
14926       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14927       if (SToVLHS.getValueType() != LHS.getValueType())
14928         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14929       LHS = SToVLHS;
14930     }
14931     if (SToVRHS) {
14932       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14933         return Res;
14934       RHSMinIdx = NumEltsOut;
14935       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14936       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14937       if (SToVRHS.getValueType() != RHS.getValueType())
14938         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14939       RHS = SToVRHS;
14940     }
14941 
14942     // Fix up the shuffle mask to reflect where the desired element actually is.
14943     // The minimum and maximum indices that correspond to element zero for both
14944     // the LHS and RHS are computed and will control which shuffle mask entries
14945     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14946     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14947     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14948                                     HalfVec, ValidLaneWidth, Subtarget);
14949     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14950 
14951     // We may have simplified away the shuffle. We won't be able to do anything
14952     // further with it here.
14953     if (!isa<ShuffleVectorSDNode>(Res))
14954       return Res;
14955     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14956   }
14957 
14958   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14959   // The common case after we commuted the shuffle is that the RHS is a splat
14960   // and we have elements coming in from the splat at indices that are not
14961   // conducive to using a merge.
14962   // Example:
14963   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14964   if (!isSplatBV(TheSplat))
14965     return Res;
14966 
14967   // We are looking for a mask such that all even elements are from
14968   // one vector and all odd elements from the other.
14969   if (!isAlternatingShuffMask(Mask, NumElts))
14970     return Res;
14971 
14972   // Adjust the mask so we are pulling in the same index from the splat
14973   // as the index from the interesting vector in consecutive elements.
14974   if (IsLittleEndian) {
14975     // Example (even elements from first vector):
14976     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14977     if (Mask[0] < NumElts)
14978       for (int i = 1, e = Mask.size(); i < e; i += 2)
14979         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14980     // Example (odd elements from first vector):
14981     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14982     else
14983       for (int i = 0, e = Mask.size(); i < e; i += 2)
14984         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14985   } else {
14986     // Example (even elements from first vector):
14987     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14988     if (Mask[0] < NumElts)
14989       for (int i = 0, e = Mask.size(); i < e; i += 2)
14990         ShuffV[i] = ShuffV[i + 1] - NumElts;
14991     // Example (odd elements from first vector):
14992     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14993     else
14994       for (int i = 1, e = Mask.size(); i < e; i += 2)
14995         ShuffV[i] = ShuffV[i - 1] - NumElts;
14996   }
14997 
14998   // If the RHS has undefs, we need to remove them since we may have created
14999   // a shuffle that adds those instead of the splat value.
15000   SDValue SplatVal =
15001       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
15002   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
15003 
15004   if (IsLittleEndian)
15005     RHS = TheSplat;
15006   else
15007     LHS = TheSplat;
15008   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
15009 }
15010 
15011 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
15012                                                 LSBaseSDNode *LSBase,
15013                                                 DAGCombinerInfo &DCI) const {
15014   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
15015         "Not a reverse memop pattern!");
15016 
15017   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
15018     auto Mask = SVN->getMask();
15019     int i = 0;
15020     auto I = Mask.rbegin();
15021     auto E = Mask.rend();
15022 
15023     for (; I != E; ++I) {
15024       if (*I != i)
15025         return false;
15026       i++;
15027     }
15028     return true;
15029   };
15030 
15031   SelectionDAG &DAG = DCI.DAG;
15032   EVT VT = SVN->getValueType(0);
15033 
15034   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
15035     return SDValue();
15036 
15037   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
15038   // See comment in PPCVSXSwapRemoval.cpp.
15039   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
15040   if (!Subtarget.hasP9Vector())
15041     return SDValue();
15042 
15043   if(!IsElementReverse(SVN))
15044     return SDValue();
15045 
15046   if (LSBase->getOpcode() == ISD::LOAD) {
15047     // If the load return value 0 has more than one user except the
15048     // shufflevector instruction, it is not profitable to replace the
15049     // shufflevector with a reverse load.
15050     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
15051          UI != UE; ++UI)
15052       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
15053         return SDValue();
15054 
15055     SDLoc dl(LSBase);
15056     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
15057     return DAG.getMemIntrinsicNode(
15058         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
15059         LSBase->getMemoryVT(), LSBase->getMemOperand());
15060   }
15061 
15062   if (LSBase->getOpcode() == ISD::STORE) {
15063     // If there are other uses of the shuffle, the swap cannot be avoided.
15064     // Forcing the use of an X-Form (since swapped stores only have
15065     // X-Forms) without removing the swap is unprofitable.
15066     if (!SVN->hasOneUse())
15067       return SDValue();
15068 
15069     SDLoc dl(LSBase);
15070     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
15071                           LSBase->getBasePtr()};
15072     return DAG.getMemIntrinsicNode(
15073         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
15074         LSBase->getMemoryVT(), LSBase->getMemOperand());
15075   }
15076 
15077   llvm_unreachable("Expected a load or store node here");
15078 }
15079 
15080 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
15081                                              DAGCombinerInfo &DCI) const {
15082   SelectionDAG &DAG = DCI.DAG;
15083   SDLoc dl(N);
15084   switch (N->getOpcode()) {
15085   default: break;
15086   case ISD::ADD:
15087     return combineADD(N, DCI);
15088   case ISD::SHL:
15089     return combineSHL(N, DCI);
15090   case ISD::SRA:
15091     return combineSRA(N, DCI);
15092   case ISD::SRL:
15093     return combineSRL(N, DCI);
15094   case ISD::MUL:
15095     return combineMUL(N, DCI);
15096   case ISD::FMA:
15097   case PPCISD::FNMSUB:
15098     return combineFMALike(N, DCI);
15099   case PPCISD::SHL:
15100     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
15101         return N->getOperand(0);
15102     break;
15103   case PPCISD::SRL:
15104     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15105         return N->getOperand(0);
15106     break;
15107   case PPCISD::SRA:
15108     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15109       if (C->isZero() ||  //  0 >>s V -> 0.
15110           C->isAllOnes()) // -1 >>s V -> -1.
15111         return N->getOperand(0);
15112     }
15113     break;
15114   case ISD::SIGN_EXTEND:
15115   case ISD::ZERO_EXTEND:
15116   case ISD::ANY_EXTEND:
15117     return DAGCombineExtBoolTrunc(N, DCI);
15118   case ISD::TRUNCATE:
15119     return combineTRUNCATE(N, DCI);
15120   case ISD::SETCC:
15121     if (SDValue CSCC = combineSetCC(N, DCI))
15122       return CSCC;
15123     LLVM_FALLTHROUGH;
15124   case ISD::SELECT_CC:
15125     return DAGCombineTruncBoolExt(N, DCI);
15126   case ISD::SINT_TO_FP:
15127   case ISD::UINT_TO_FP:
15128     return combineFPToIntToFP(N, DCI);
15129   case ISD::VECTOR_SHUFFLE:
15130     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15131       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15132       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15133     }
15134     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15135   case ISD::STORE: {
15136 
15137     EVT Op1VT = N->getOperand(1).getValueType();
15138     unsigned Opcode = N->getOperand(1).getOpcode();
15139 
15140     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15141       SDValue Val= combineStoreFPToInt(N, DCI);
15142       if (Val)
15143         return Val;
15144     }
15145 
15146     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15147       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15148       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15149       if (Val)
15150         return Val;
15151     }
15152 
15153     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15154     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15155         N->getOperand(1).getNode()->hasOneUse() &&
15156         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15157          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15158 
15159       // STBRX can only handle simple types and it makes no sense to store less
15160       // two bytes in byte-reversed order.
15161       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15162       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15163         break;
15164 
15165       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15166       // Do an any-extend to 32-bits if this is a half-word input.
15167       if (BSwapOp.getValueType() == MVT::i16)
15168         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15169 
15170       // If the type of BSWAP operand is wider than stored memory width
15171       // it need to be shifted to the right side before STBRX.
15172       if (Op1VT.bitsGT(mVT)) {
15173         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15174         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15175                               DAG.getConstant(Shift, dl, MVT::i32));
15176         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15177         if (Op1VT == MVT::i64)
15178           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15179       }
15180 
15181       SDValue Ops[] = {
15182         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15183       };
15184       return
15185         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15186                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15187                                 cast<StoreSDNode>(N)->getMemOperand());
15188     }
15189 
15190     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15191     // So it can increase the chance of CSE constant construction.
15192     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15193         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15194       // Need to sign-extended to 64-bits to handle negative values.
15195       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15196       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15197                                     MemVT.getSizeInBits());
15198       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15199 
15200       // DAG.getTruncStore() can't be used here because it doesn't accept
15201       // the general (base + offset) addressing mode.
15202       // So we use UpdateNodeOperands and setTruncatingStore instead.
15203       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15204                              N->getOperand(3));
15205       cast<StoreSDNode>(N)->setTruncatingStore(true);
15206       return SDValue(N, 0);
15207     }
15208 
15209     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15210     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15211     if (Op1VT.isSimple()) {
15212       MVT StoreVT = Op1VT.getSimpleVT();
15213       if (Subtarget.needsSwapsForVSXMemOps() &&
15214           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15215            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15216         return expandVSXStoreForLE(N, DCI);
15217     }
15218     break;
15219   }
15220   case ISD::LOAD: {
15221     LoadSDNode *LD = cast<LoadSDNode>(N);
15222     EVT VT = LD->getValueType(0);
15223 
15224     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15225     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15226     if (VT.isSimple()) {
15227       MVT LoadVT = VT.getSimpleVT();
15228       if (Subtarget.needsSwapsForVSXMemOps() &&
15229           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15230            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15231         return expandVSXLoadForLE(N, DCI);
15232     }
15233 
15234     // We sometimes end up with a 64-bit integer load, from which we extract
15235     // two single-precision floating-point numbers. This happens with
15236     // std::complex<float>, and other similar structures, because of the way we
15237     // canonicalize structure copies. However, if we lack direct moves,
15238     // then the final bitcasts from the extracted integer values to the
15239     // floating-point numbers turn into store/load pairs. Even with direct moves,
15240     // just loading the two floating-point numbers is likely better.
15241     auto ReplaceTwoFloatLoad = [&]() {
15242       if (VT != MVT::i64)
15243         return false;
15244 
15245       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15246           LD->isVolatile())
15247         return false;
15248 
15249       //  We're looking for a sequence like this:
15250       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15251       //      t16: i64 = srl t13, Constant:i32<32>
15252       //    t17: i32 = truncate t16
15253       //  t18: f32 = bitcast t17
15254       //    t19: i32 = truncate t13
15255       //  t20: f32 = bitcast t19
15256 
15257       if (!LD->hasNUsesOfValue(2, 0))
15258         return false;
15259 
15260       auto UI = LD->use_begin();
15261       while (UI.getUse().getResNo() != 0) ++UI;
15262       SDNode *Trunc = *UI++;
15263       while (UI.getUse().getResNo() != 0) ++UI;
15264       SDNode *RightShift = *UI;
15265       if (Trunc->getOpcode() != ISD::TRUNCATE)
15266         std::swap(Trunc, RightShift);
15267 
15268       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15269           Trunc->getValueType(0) != MVT::i32 ||
15270           !Trunc->hasOneUse())
15271         return false;
15272       if (RightShift->getOpcode() != ISD::SRL ||
15273           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15274           RightShift->getConstantOperandVal(1) != 32 ||
15275           !RightShift->hasOneUse())
15276         return false;
15277 
15278       SDNode *Trunc2 = *RightShift->use_begin();
15279       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15280           Trunc2->getValueType(0) != MVT::i32 ||
15281           !Trunc2->hasOneUse())
15282         return false;
15283 
15284       SDNode *Bitcast = *Trunc->use_begin();
15285       SDNode *Bitcast2 = *Trunc2->use_begin();
15286 
15287       if (Bitcast->getOpcode() != ISD::BITCAST ||
15288           Bitcast->getValueType(0) != MVT::f32)
15289         return false;
15290       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15291           Bitcast2->getValueType(0) != MVT::f32)
15292         return false;
15293 
15294       if (Subtarget.isLittleEndian())
15295         std::swap(Bitcast, Bitcast2);
15296 
15297       // Bitcast has the second float (in memory-layout order) and Bitcast2
15298       // has the first one.
15299 
15300       SDValue BasePtr = LD->getBasePtr();
15301       if (LD->isIndexed()) {
15302         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15303                "Non-pre-inc AM on PPC?");
15304         BasePtr =
15305           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15306                       LD->getOffset());
15307       }
15308 
15309       auto MMOFlags =
15310           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15311       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15312                                       LD->getPointerInfo(), LD->getAlignment(),
15313                                       MMOFlags, LD->getAAInfo());
15314       SDValue AddPtr =
15315         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15316                     BasePtr, DAG.getIntPtrConstant(4, dl));
15317       SDValue FloatLoad2 = DAG.getLoad(
15318           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15319           LD->getPointerInfo().getWithOffset(4),
15320           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15321 
15322       if (LD->isIndexed()) {
15323         // Note that DAGCombine should re-form any pre-increment load(s) from
15324         // what is produced here if that makes sense.
15325         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15326       }
15327 
15328       DCI.CombineTo(Bitcast2, FloatLoad);
15329       DCI.CombineTo(Bitcast, FloatLoad2);
15330 
15331       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15332                                     SDValue(FloatLoad2.getNode(), 1));
15333       return true;
15334     };
15335 
15336     if (ReplaceTwoFloatLoad())
15337       return SDValue(N, 0);
15338 
15339     EVT MemVT = LD->getMemoryVT();
15340     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15341     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15342     if (LD->isUnindexed() && VT.isVector() &&
15343         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15344           // P8 and later hardware should just use LOAD.
15345           !Subtarget.hasP8Vector() &&
15346           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15347            VT == MVT::v4f32))) &&
15348         LD->getAlign() < ABIAlignment) {
15349       // This is a type-legal unaligned Altivec load.
15350       SDValue Chain = LD->getChain();
15351       SDValue Ptr = LD->getBasePtr();
15352       bool isLittleEndian = Subtarget.isLittleEndian();
15353 
15354       // This implements the loading of unaligned vectors as described in
15355       // the venerable Apple Velocity Engine overview. Specifically:
15356       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15357       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15358       //
15359       // The general idea is to expand a sequence of one or more unaligned
15360       // loads into an alignment-based permutation-control instruction (lvsl
15361       // or lvsr), a series of regular vector loads (which always truncate
15362       // their input address to an aligned address), and a series of
15363       // permutations.  The results of these permutations are the requested
15364       // loaded values.  The trick is that the last "extra" load is not taken
15365       // from the address you might suspect (sizeof(vector) bytes after the
15366       // last requested load), but rather sizeof(vector) - 1 bytes after the
15367       // last requested vector. The point of this is to avoid a page fault if
15368       // the base address happened to be aligned. This works because if the
15369       // base address is aligned, then adding less than a full vector length
15370       // will cause the last vector in the sequence to be (re)loaded.
15371       // Otherwise, the next vector will be fetched as you might suspect was
15372       // necessary.
15373 
15374       // We might be able to reuse the permutation generation from
15375       // a different base address offset from this one by an aligned amount.
15376       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15377       // optimization later.
15378       Intrinsic::ID Intr, IntrLD, IntrPerm;
15379       MVT PermCntlTy, PermTy, LDTy;
15380       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15381                             : Intrinsic::ppc_altivec_lvsl;
15382       IntrLD = Intrinsic::ppc_altivec_lvx;
15383       IntrPerm = Intrinsic::ppc_altivec_vperm;
15384       PermCntlTy = MVT::v16i8;
15385       PermTy = MVT::v4i32;
15386       LDTy = MVT::v4i32;
15387 
15388       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15389 
15390       // Create the new MMO for the new base load. It is like the original MMO,
15391       // but represents an area in memory almost twice the vector size centered
15392       // on the original address. If the address is unaligned, we might start
15393       // reading up to (sizeof(vector)-1) bytes below the address of the
15394       // original unaligned load.
15395       MachineFunction &MF = DAG.getMachineFunction();
15396       MachineMemOperand *BaseMMO =
15397         MF.getMachineMemOperand(LD->getMemOperand(),
15398                                 -(long)MemVT.getStoreSize()+1,
15399                                 2*MemVT.getStoreSize()-1);
15400 
15401       // Create the new base load.
15402       SDValue LDXIntID =
15403           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15404       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15405       SDValue BaseLoad =
15406         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15407                                 DAG.getVTList(PermTy, MVT::Other),
15408                                 BaseLoadOps, LDTy, BaseMMO);
15409 
15410       // Note that the value of IncOffset (which is provided to the next
15411       // load's pointer info offset value, and thus used to calculate the
15412       // alignment), and the value of IncValue (which is actually used to
15413       // increment the pointer value) are different! This is because we
15414       // require the next load to appear to be aligned, even though it
15415       // is actually offset from the base pointer by a lesser amount.
15416       int IncOffset = VT.getSizeInBits() / 8;
15417       int IncValue = IncOffset;
15418 
15419       // Walk (both up and down) the chain looking for another load at the real
15420       // (aligned) offset (the alignment of the other load does not matter in
15421       // this case). If found, then do not use the offset reduction trick, as
15422       // that will prevent the loads from being later combined (as they would
15423       // otherwise be duplicates).
15424       if (!findConsecutiveLoad(LD, DAG))
15425         --IncValue;
15426 
15427       SDValue Increment =
15428           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15429       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15430 
15431       MachineMemOperand *ExtraMMO =
15432         MF.getMachineMemOperand(LD->getMemOperand(),
15433                                 1, 2*MemVT.getStoreSize()-1);
15434       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15435       SDValue ExtraLoad =
15436         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15437                                 DAG.getVTList(PermTy, MVT::Other),
15438                                 ExtraLoadOps, LDTy, ExtraMMO);
15439 
15440       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15441         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15442 
15443       // Because vperm has a big-endian bias, we must reverse the order
15444       // of the input vectors and complement the permute control vector
15445       // when generating little endian code.  We have already handled the
15446       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15447       // and ExtraLoad here.
15448       SDValue Perm;
15449       if (isLittleEndian)
15450         Perm = BuildIntrinsicOp(IntrPerm,
15451                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15452       else
15453         Perm = BuildIntrinsicOp(IntrPerm,
15454                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15455 
15456       if (VT != PermTy)
15457         Perm = Subtarget.hasAltivec()
15458                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15459                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15460                                  DAG.getTargetConstant(1, dl, MVT::i64));
15461                                // second argument is 1 because this rounding
15462                                // is always exact.
15463 
15464       // The output of the permutation is our loaded result, the TokenFactor is
15465       // our new chain.
15466       DCI.CombineTo(N, Perm, TF);
15467       return SDValue(N, 0);
15468     }
15469     }
15470     break;
15471     case ISD::INTRINSIC_WO_CHAIN: {
15472       bool isLittleEndian = Subtarget.isLittleEndian();
15473       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15474       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15475                                            : Intrinsic::ppc_altivec_lvsl);
15476       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15477         SDValue Add = N->getOperand(1);
15478 
15479         int Bits = 4 /* 16 byte alignment */;
15480 
15481         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15482                                   APInt::getAllOnes(Bits /* alignment */)
15483                                       .zext(Add.getScalarValueSizeInBits()))) {
15484           SDNode *BasePtr = Add->getOperand(0).getNode();
15485           for (SDNode *U : BasePtr->uses()) {
15486             if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15487                 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15488               // We've found another LVSL/LVSR, and this address is an aligned
15489               // multiple of that one. The results will be the same, so use the
15490               // one we've just found instead.
15491 
15492               return SDValue(U, 0);
15493             }
15494           }
15495         }
15496 
15497         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15498           SDNode *BasePtr = Add->getOperand(0).getNode();
15499           for (SDNode *U : BasePtr->uses()) {
15500             if (U->getOpcode() == ISD::ADD &&
15501                 isa<ConstantSDNode>(U->getOperand(1)) &&
15502                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15503                  cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15504                         (1ULL << Bits) ==
15505                     0) {
15506               SDNode *OtherAdd = U;
15507               for (SDNode *V : OtherAdd->uses()) {
15508                 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15509                     cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15510                         IID) {
15511                   return SDValue(V, 0);
15512                 }
15513               }
15514             }
15515           }
15516         }
15517       }
15518 
15519       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15520       // Expose the vabsduw/h/b opportunity for down stream
15521       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15522           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15523            IID == Intrinsic::ppc_altivec_vmaxsh ||
15524            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15525         SDValue V1 = N->getOperand(1);
15526         SDValue V2 = N->getOperand(2);
15527         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15528              V1.getSimpleValueType() == MVT::v8i16 ||
15529              V1.getSimpleValueType() == MVT::v16i8) &&
15530             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15531           // (0-a, a)
15532           if (V1.getOpcode() == ISD::SUB &&
15533               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15534               V1.getOperand(1) == V2) {
15535             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15536           }
15537           // (a, 0-a)
15538           if (V2.getOpcode() == ISD::SUB &&
15539               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15540               V2.getOperand(1) == V1) {
15541             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15542           }
15543           // (x-y, y-x)
15544           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15545               V1.getOperand(0) == V2.getOperand(1) &&
15546               V1.getOperand(1) == V2.getOperand(0)) {
15547             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15548           }
15549         }
15550       }
15551     }
15552 
15553     break;
15554   case ISD::INTRINSIC_W_CHAIN:
15555     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15556     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15557     if (Subtarget.needsSwapsForVSXMemOps()) {
15558       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15559       default:
15560         break;
15561       case Intrinsic::ppc_vsx_lxvw4x:
15562       case Intrinsic::ppc_vsx_lxvd2x:
15563         return expandVSXLoadForLE(N, DCI);
15564       }
15565     }
15566     break;
15567   case ISD::INTRINSIC_VOID:
15568     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15569     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15570     if (Subtarget.needsSwapsForVSXMemOps()) {
15571       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15572       default:
15573         break;
15574       case Intrinsic::ppc_vsx_stxvw4x:
15575       case Intrinsic::ppc_vsx_stxvd2x:
15576         return expandVSXStoreForLE(N, DCI);
15577       }
15578     }
15579     break;
15580   case ISD::BSWAP: {
15581     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15582     // For subtargets without LDBRX, we can still do better than the default
15583     // expansion even for 64-bit BSWAP (LOAD).
15584     bool Is64BitBswapOn64BitTgt =
15585         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15586     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15587                                N->getOperand(0).hasOneUse();
15588     if (IsSingleUseNormalLd &&
15589         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15590          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15591       SDValue Load = N->getOperand(0);
15592       LoadSDNode *LD = cast<LoadSDNode>(Load);
15593       // Create the byte-swapping load.
15594       SDValue Ops[] = {
15595         LD->getChain(),    // Chain
15596         LD->getBasePtr(),  // Ptr
15597         DAG.getValueType(N->getValueType(0)) // VT
15598       };
15599       SDValue BSLoad =
15600         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15601                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15602                                               MVT::i64 : MVT::i32, MVT::Other),
15603                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15604 
15605       // If this is an i16 load, insert the truncate.
15606       SDValue ResVal = BSLoad;
15607       if (N->getValueType(0) == MVT::i16)
15608         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15609 
15610       // First, combine the bswap away.  This makes the value produced by the
15611       // load dead.
15612       DCI.CombineTo(N, ResVal);
15613 
15614       // Next, combine the load away, we give it a bogus result value but a real
15615       // chain result.  The result value is dead because the bswap is dead.
15616       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15617 
15618       // Return N so it doesn't get rechecked!
15619       return SDValue(N, 0);
15620     }
15621     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15622     // before legalization so that the BUILD_PAIR is handled correctly.
15623     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15624         !IsSingleUseNormalLd)
15625       return SDValue();
15626     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15627 
15628     // Can't split volatile or atomic loads.
15629     if (!LD->isSimple())
15630       return SDValue();
15631     SDValue BasePtr = LD->getBasePtr();
15632     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15633                              LD->getPointerInfo(), LD->getAlignment());
15634     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15635     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15636                           DAG.getIntPtrConstant(4, dl));
15637     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15638         LD->getMemOperand(), 4, 4);
15639     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15640     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15641     SDValue Res;
15642     if (Subtarget.isLittleEndian())
15643       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15644     else
15645       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15646     SDValue TF =
15647         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15648                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15649     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15650     return Res;
15651   }
15652   case PPCISD::VCMP:
15653     // If a VCMP_rec node already exists with exactly the same operands as this
15654     // node, use its result instead of this node (VCMP_rec computes both a CR6
15655     // and a normal output).
15656     //
15657     if (!N->getOperand(0).hasOneUse() &&
15658         !N->getOperand(1).hasOneUse() &&
15659         !N->getOperand(2).hasOneUse()) {
15660 
15661       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15662       SDNode *VCMPrecNode = nullptr;
15663 
15664       SDNode *LHSN = N->getOperand(0).getNode();
15665       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15666            UI != E; ++UI)
15667         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15668             UI->getOperand(1) == N->getOperand(1) &&
15669             UI->getOperand(2) == N->getOperand(2) &&
15670             UI->getOperand(0) == N->getOperand(0)) {
15671           VCMPrecNode = *UI;
15672           break;
15673         }
15674 
15675       // If there is no VCMP_rec node, or if the flag value has a single use,
15676       // don't transform this.
15677       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15678         break;
15679 
15680       // Look at the (necessarily single) use of the flag value.  If it has a
15681       // chain, this transformation is more complex.  Note that multiple things
15682       // could use the value result, which we should ignore.
15683       SDNode *FlagUser = nullptr;
15684       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15685            FlagUser == nullptr; ++UI) {
15686         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15687         SDNode *User = *UI;
15688         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15689           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15690             FlagUser = User;
15691             break;
15692           }
15693         }
15694       }
15695 
15696       // If the user is a MFOCRF instruction, we know this is safe.
15697       // Otherwise we give up for right now.
15698       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15699         return SDValue(VCMPrecNode, 0);
15700     }
15701     break;
15702   case ISD::BRCOND: {
15703     SDValue Cond = N->getOperand(1);
15704     SDValue Target = N->getOperand(2);
15705 
15706     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15707         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15708           Intrinsic::loop_decrement) {
15709 
15710       // We now need to make the intrinsic dead (it cannot be instruction
15711       // selected).
15712       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15713       assert(Cond.getNode()->hasOneUse() &&
15714              "Counter decrement has more than one use");
15715 
15716       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15717                          N->getOperand(0), Target);
15718     }
15719   }
15720   break;
15721   case ISD::BR_CC: {
15722     // If this is a branch on an altivec predicate comparison, lower this so
15723     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15724     // lowering is done pre-legalize, because the legalizer lowers the predicate
15725     // compare down to code that is difficult to reassemble.
15726     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15727     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15728 
15729     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15730     // value. If so, pass-through the AND to get to the intrinsic.
15731     if (LHS.getOpcode() == ISD::AND &&
15732         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15733         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15734           Intrinsic::loop_decrement &&
15735         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15736         !isNullConstant(LHS.getOperand(1)))
15737       LHS = LHS.getOperand(0);
15738 
15739     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15740         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15741           Intrinsic::loop_decrement &&
15742         isa<ConstantSDNode>(RHS)) {
15743       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15744              "Counter decrement comparison is not EQ or NE");
15745 
15746       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15747       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15748                     (CC == ISD::SETNE && !Val);
15749 
15750       // We now need to make the intrinsic dead (it cannot be instruction
15751       // selected).
15752       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15753       assert(LHS.getNode()->hasOneUse() &&
15754              "Counter decrement has more than one use");
15755 
15756       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15757                          N->getOperand(0), N->getOperand(4));
15758     }
15759 
15760     int CompareOpc;
15761     bool isDot;
15762 
15763     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15764         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15765         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15766       assert(isDot && "Can't compare against a vector result!");
15767 
15768       // If this is a comparison against something other than 0/1, then we know
15769       // that the condition is never/always true.
15770       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15771       if (Val != 0 && Val != 1) {
15772         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15773           return N->getOperand(0);
15774         // Always !=, turn it into an unconditional branch.
15775         return DAG.getNode(ISD::BR, dl, MVT::Other,
15776                            N->getOperand(0), N->getOperand(4));
15777       }
15778 
15779       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15780 
15781       // Create the PPCISD altivec 'dot' comparison node.
15782       SDValue Ops[] = {
15783         LHS.getOperand(2),  // LHS of compare
15784         LHS.getOperand(3),  // RHS of compare
15785         DAG.getConstant(CompareOpc, dl, MVT::i32)
15786       };
15787       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15788       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15789 
15790       // Unpack the result based on how the target uses it.
15791       PPC::Predicate CompOpc;
15792       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15793       default:  // Can't happen, don't crash on invalid number though.
15794       case 0:   // Branch on the value of the EQ bit of CR6.
15795         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15796         break;
15797       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15798         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15799         break;
15800       case 2:   // Branch on the value of the LT bit of CR6.
15801         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15802         break;
15803       case 3:   // Branch on the inverted value of the LT bit of CR6.
15804         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15805         break;
15806       }
15807 
15808       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15809                          DAG.getConstant(CompOpc, dl, MVT::i32),
15810                          DAG.getRegister(PPC::CR6, MVT::i32),
15811                          N->getOperand(4), CompNode.getValue(1));
15812     }
15813     break;
15814   }
15815   case ISD::BUILD_VECTOR:
15816     return DAGCombineBuildVector(N, DCI);
15817   case ISD::ABS:
15818     return combineABS(N, DCI);
15819   case ISD::VSELECT:
15820     return combineVSelect(N, DCI);
15821   }
15822 
15823   return SDValue();
15824 }
15825 
15826 SDValue
15827 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15828                                  SelectionDAG &DAG,
15829                                  SmallVectorImpl<SDNode *> &Created) const {
15830   // fold (sdiv X, pow2)
15831   EVT VT = N->getValueType(0);
15832   if (VT == MVT::i64 && !Subtarget.isPPC64())
15833     return SDValue();
15834   if ((VT != MVT::i32 && VT != MVT::i64) ||
15835       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15836     return SDValue();
15837 
15838   SDLoc DL(N);
15839   SDValue N0 = N->getOperand(0);
15840 
15841   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15842   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15843   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15844 
15845   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15846   Created.push_back(Op.getNode());
15847 
15848   if (IsNegPow2) {
15849     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15850     Created.push_back(Op.getNode());
15851   }
15852 
15853   return Op;
15854 }
15855 
15856 //===----------------------------------------------------------------------===//
15857 // Inline Assembly Support
15858 //===----------------------------------------------------------------------===//
15859 
15860 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15861                                                       KnownBits &Known,
15862                                                       const APInt &DemandedElts,
15863                                                       const SelectionDAG &DAG,
15864                                                       unsigned Depth) const {
15865   Known.resetAll();
15866   switch (Op.getOpcode()) {
15867   default: break;
15868   case PPCISD::LBRX: {
15869     // lhbrx is known to have the top bits cleared out.
15870     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15871       Known.Zero = 0xFFFF0000;
15872     break;
15873   }
15874   case ISD::INTRINSIC_WO_CHAIN: {
15875     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15876     default: break;
15877     case Intrinsic::ppc_altivec_vcmpbfp_p:
15878     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15879     case Intrinsic::ppc_altivec_vcmpequb_p:
15880     case Intrinsic::ppc_altivec_vcmpequh_p:
15881     case Intrinsic::ppc_altivec_vcmpequw_p:
15882     case Intrinsic::ppc_altivec_vcmpequd_p:
15883     case Intrinsic::ppc_altivec_vcmpequq_p:
15884     case Intrinsic::ppc_altivec_vcmpgefp_p:
15885     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15886     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15887     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15888     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15889     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15890     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15891     case Intrinsic::ppc_altivec_vcmpgtub_p:
15892     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15893     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15894     case Intrinsic::ppc_altivec_vcmpgtud_p:
15895     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15896       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15897       break;
15898     }
15899     break;
15900   }
15901   case ISD::INTRINSIC_W_CHAIN: {
15902     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15903     default:
15904       break;
15905     case Intrinsic::ppc_load2r:
15906       // Top bits are cleared for load2r (which is the same as lhbrx).
15907       Known.Zero = 0xFFFF0000;
15908       break;
15909     }
15910     break;
15911   }
15912   }
15913 }
15914 
15915 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15916   switch (Subtarget.getCPUDirective()) {
15917   default: break;
15918   case PPC::DIR_970:
15919   case PPC::DIR_PWR4:
15920   case PPC::DIR_PWR5:
15921   case PPC::DIR_PWR5X:
15922   case PPC::DIR_PWR6:
15923   case PPC::DIR_PWR6X:
15924   case PPC::DIR_PWR7:
15925   case PPC::DIR_PWR8:
15926   case PPC::DIR_PWR9:
15927   case PPC::DIR_PWR10:
15928   case PPC::DIR_PWR_FUTURE: {
15929     if (!ML)
15930       break;
15931 
15932     if (!DisableInnermostLoopAlign32) {
15933       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15934       // so that we can decrease cache misses and branch-prediction misses.
15935       // Actual alignment of the loop will depend on the hotness check and other
15936       // logic in alignBlocks.
15937       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15938         return Align(32);
15939     }
15940 
15941     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15942 
15943     // For small loops (between 5 and 8 instructions), align to a 32-byte
15944     // boundary so that the entire loop fits in one instruction-cache line.
15945     uint64_t LoopSize = 0;
15946     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15947       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15948         LoopSize += TII->getInstSizeInBytes(*J);
15949         if (LoopSize > 32)
15950           break;
15951       }
15952 
15953     if (LoopSize > 16 && LoopSize <= 32)
15954       return Align(32);
15955 
15956     break;
15957   }
15958   }
15959 
15960   return TargetLowering::getPrefLoopAlignment(ML);
15961 }
15962 
15963 /// getConstraintType - Given a constraint, return the type of
15964 /// constraint it is for this target.
15965 PPCTargetLowering::ConstraintType
15966 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15967   if (Constraint.size() == 1) {
15968     switch (Constraint[0]) {
15969     default: break;
15970     case 'b':
15971     case 'r':
15972     case 'f':
15973     case 'd':
15974     case 'v':
15975     case 'y':
15976       return C_RegisterClass;
15977     case 'Z':
15978       // FIXME: While Z does indicate a memory constraint, it specifically
15979       // indicates an r+r address (used in conjunction with the 'y' modifier
15980       // in the replacement string). Currently, we're forcing the base
15981       // register to be r0 in the asm printer (which is interpreted as zero)
15982       // and forming the complete address in the second register. This is
15983       // suboptimal.
15984       return C_Memory;
15985     }
15986   } else if (Constraint == "wc") { // individual CR bits.
15987     return C_RegisterClass;
15988   } else if (Constraint == "wa" || Constraint == "wd" ||
15989              Constraint == "wf" || Constraint == "ws" ||
15990              Constraint == "wi" || Constraint == "ww") {
15991     return C_RegisterClass; // VSX registers.
15992   }
15993   return TargetLowering::getConstraintType(Constraint);
15994 }
15995 
15996 /// Examine constraint type and operand type and determine a weight value.
15997 /// This object must already have been set up with the operand type
15998 /// and the current alternative constraint selected.
15999 TargetLowering::ConstraintWeight
16000 PPCTargetLowering::getSingleConstraintMatchWeight(
16001     AsmOperandInfo &info, const char *constraint) const {
16002   ConstraintWeight weight = CW_Invalid;
16003   Value *CallOperandVal = info.CallOperandVal;
16004     // If we don't have a value, we can't do a match,
16005     // but allow it at the lowest weight.
16006   if (!CallOperandVal)
16007     return CW_Default;
16008   Type *type = CallOperandVal->getType();
16009 
16010   // Look at the constraint type.
16011   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
16012     return CW_Register; // an individual CR bit.
16013   else if ((StringRef(constraint) == "wa" ||
16014             StringRef(constraint) == "wd" ||
16015             StringRef(constraint) == "wf") &&
16016            type->isVectorTy())
16017     return CW_Register;
16018   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
16019     return CW_Register; // just hold 64-bit integers data.
16020   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
16021     return CW_Register;
16022   else if (StringRef(constraint) == "ww" && type->isFloatTy())
16023     return CW_Register;
16024 
16025   switch (*constraint) {
16026   default:
16027     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16028     break;
16029   case 'b':
16030     if (type->isIntegerTy())
16031       weight = CW_Register;
16032     break;
16033   case 'f':
16034     if (type->isFloatTy())
16035       weight = CW_Register;
16036     break;
16037   case 'd':
16038     if (type->isDoubleTy())
16039       weight = CW_Register;
16040     break;
16041   case 'v':
16042     if (type->isVectorTy())
16043       weight = CW_Register;
16044     break;
16045   case 'y':
16046     weight = CW_Register;
16047     break;
16048   case 'Z':
16049     weight = CW_Memory;
16050     break;
16051   }
16052   return weight;
16053 }
16054 
16055 std::pair<unsigned, const TargetRegisterClass *>
16056 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
16057                                                 StringRef Constraint,
16058                                                 MVT VT) const {
16059   if (Constraint.size() == 1) {
16060     // GCC RS6000 Constraint Letters
16061     switch (Constraint[0]) {
16062     case 'b':   // R1-R31
16063       if (VT == MVT::i64 && Subtarget.isPPC64())
16064         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
16065       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
16066     case 'r':   // R0-R31
16067       if (VT == MVT::i64 && Subtarget.isPPC64())
16068         return std::make_pair(0U, &PPC::G8RCRegClass);
16069       return std::make_pair(0U, &PPC::GPRCRegClass);
16070     // 'd' and 'f' constraints are both defined to be "the floating point
16071     // registers", where one is for 32-bit and the other for 64-bit. We don't
16072     // really care overly much here so just give them all the same reg classes.
16073     case 'd':
16074     case 'f':
16075       if (Subtarget.hasSPE()) {
16076         if (VT == MVT::f32 || VT == MVT::i32)
16077           return std::make_pair(0U, &PPC::GPRCRegClass);
16078         if (VT == MVT::f64 || VT == MVT::i64)
16079           return std::make_pair(0U, &PPC::SPERCRegClass);
16080       } else {
16081         if (VT == MVT::f32 || VT == MVT::i32)
16082           return std::make_pair(0U, &PPC::F4RCRegClass);
16083         if (VT == MVT::f64 || VT == MVT::i64)
16084           return std::make_pair(0U, &PPC::F8RCRegClass);
16085       }
16086       break;
16087     case 'v':
16088       if (Subtarget.hasAltivec() && VT.isVector())
16089         return std::make_pair(0U, &PPC::VRRCRegClass);
16090       else if (Subtarget.hasVSX())
16091         // Scalars in Altivec registers only make sense with VSX.
16092         return std::make_pair(0U, &PPC::VFRCRegClass);
16093       break;
16094     case 'y':   // crrc
16095       return std::make_pair(0U, &PPC::CRRCRegClass);
16096     }
16097   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
16098     // An individual CR bit.
16099     return std::make_pair(0U, &PPC::CRBITRCRegClass);
16100   } else if ((Constraint == "wa" || Constraint == "wd" ||
16101              Constraint == "wf" || Constraint == "wi") &&
16102              Subtarget.hasVSX()) {
16103     // A VSX register for either a scalar (FP) or vector. There is no
16104     // support for single precision scalars on subtargets prior to Power8.
16105     if (VT.isVector())
16106       return std::make_pair(0U, &PPC::VSRCRegClass);
16107     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16108       return std::make_pair(0U, &PPC::VSSRCRegClass);
16109     return std::make_pair(0U, &PPC::VSFRCRegClass);
16110   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16111     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16112       return std::make_pair(0U, &PPC::VSSRCRegClass);
16113     else
16114       return std::make_pair(0U, &PPC::VSFRCRegClass);
16115   } else if (Constraint == "lr") {
16116     if (VT == MVT::i64)
16117       return std::make_pair(0U, &PPC::LR8RCRegClass);
16118     else
16119       return std::make_pair(0U, &PPC::LRRCRegClass);
16120   }
16121 
16122   // Handle special cases of physical registers that are not properly handled
16123   // by the base class.
16124   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16125     // If we name a VSX register, we can't defer to the base class because it
16126     // will not recognize the correct register (their names will be VSL{0-31}
16127     // and V{0-31} so they won't match). So we match them here.
16128     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16129       int VSNum = atoi(Constraint.data() + 3);
16130       assert(VSNum >= 0 && VSNum <= 63 &&
16131              "Attempted to access a vsr out of range");
16132       if (VSNum < 32)
16133         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16134       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16135     }
16136 
16137     // For float registers, we can't defer to the base class as it will match
16138     // the SPILLTOVSRRC class.
16139     if (Constraint.size() > 3 && Constraint[1] == 'f') {
16140       int RegNum = atoi(Constraint.data() + 2);
16141       if (RegNum > 31 || RegNum < 0)
16142         report_fatal_error("Invalid floating point register number");
16143       if (VT == MVT::f32 || VT == MVT::i32)
16144         return Subtarget.hasSPE()
16145                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16146                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16147       if (VT == MVT::f64 || VT == MVT::i64)
16148         return Subtarget.hasSPE()
16149                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16150                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16151     }
16152   }
16153 
16154   std::pair<unsigned, const TargetRegisterClass *> R =
16155       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16156 
16157   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16158   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16159   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16160   // register.
16161   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16162   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16163   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16164       PPC::GPRCRegClass.contains(R.first))
16165     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16166                             PPC::sub_32, &PPC::G8RCRegClass),
16167                           &PPC::G8RCRegClass);
16168 
16169   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16170   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16171     R.first = PPC::CR0;
16172     R.second = &PPC::CRRCRegClass;
16173   }
16174   // FIXME: This warning should ideally be emitted in the front end.
16175   const auto &TM = getTargetMachine();
16176   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16177     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16178          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16179         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16180       errs() << "warning: vector registers 20 to 32 are reserved in the "
16181                 "default AIX AltiVec ABI and cannot be used\n";
16182   }
16183 
16184   return R;
16185 }
16186 
16187 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16188 /// vector.  If it is invalid, don't add anything to Ops.
16189 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16190                                                      std::string &Constraint,
16191                                                      std::vector<SDValue>&Ops,
16192                                                      SelectionDAG &DAG) const {
16193   SDValue Result;
16194 
16195   // Only support length 1 constraints.
16196   if (Constraint.length() > 1) return;
16197 
16198   char Letter = Constraint[0];
16199   switch (Letter) {
16200   default: break;
16201   case 'I':
16202   case 'J':
16203   case 'K':
16204   case 'L':
16205   case 'M':
16206   case 'N':
16207   case 'O':
16208   case 'P': {
16209     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16210     if (!CST) return; // Must be an immediate to match.
16211     SDLoc dl(Op);
16212     int64_t Value = CST->getSExtValue();
16213     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16214                          // numbers are printed as such.
16215     switch (Letter) {
16216     default: llvm_unreachable("Unknown constraint letter!");
16217     case 'I':  // "I" is a signed 16-bit constant.
16218       if (isInt<16>(Value))
16219         Result = DAG.getTargetConstant(Value, dl, TCVT);
16220       break;
16221     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16222       if (isShiftedUInt<16, 16>(Value))
16223         Result = DAG.getTargetConstant(Value, dl, TCVT);
16224       break;
16225     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16226       if (isShiftedInt<16, 16>(Value))
16227         Result = DAG.getTargetConstant(Value, dl, TCVT);
16228       break;
16229     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16230       if (isUInt<16>(Value))
16231         Result = DAG.getTargetConstant(Value, dl, TCVT);
16232       break;
16233     case 'M':  // "M" is a constant that is greater than 31.
16234       if (Value > 31)
16235         Result = DAG.getTargetConstant(Value, dl, TCVT);
16236       break;
16237     case 'N':  // "N" is a positive constant that is an exact power of two.
16238       if (Value > 0 && isPowerOf2_64(Value))
16239         Result = DAG.getTargetConstant(Value, dl, TCVT);
16240       break;
16241     case 'O':  // "O" is the constant zero.
16242       if (Value == 0)
16243         Result = DAG.getTargetConstant(Value, dl, TCVT);
16244       break;
16245     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16246       if (isInt<16>(-Value))
16247         Result = DAG.getTargetConstant(Value, dl, TCVT);
16248       break;
16249     }
16250     break;
16251   }
16252   }
16253 
16254   if (Result.getNode()) {
16255     Ops.push_back(Result);
16256     return;
16257   }
16258 
16259   // Handle standard constraint letters.
16260   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16261 }
16262 
16263 // isLegalAddressingMode - Return true if the addressing mode represented
16264 // by AM is legal for this target, for a load/store of the specified type.
16265 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16266                                               const AddrMode &AM, Type *Ty,
16267                                               unsigned AS,
16268                                               Instruction *I) const {
16269   // Vector type r+i form is supported since power9 as DQ form. We don't check
16270   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16271   // imm form is preferred and the offset can be adjusted to use imm form later
16272   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16273   // max offset to check legal addressing mode, we should be a little aggressive
16274   // to contain other offsets for that LSRUse.
16275   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16276     return false;
16277 
16278   // PPC allows a sign-extended 16-bit immediate field.
16279   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16280     return false;
16281 
16282   // No global is ever allowed as a base.
16283   if (AM.BaseGV)
16284     return false;
16285 
16286   // PPC only support r+r,
16287   switch (AM.Scale) {
16288   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16289     break;
16290   case 1:
16291     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16292       return false;
16293     // Otherwise we have r+r or r+i.
16294     break;
16295   case 2:
16296     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16297       return false;
16298     // Allow 2*r as r+r.
16299     break;
16300   default:
16301     // No other scales are supported.
16302     return false;
16303   }
16304 
16305   return true;
16306 }
16307 
16308 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16309                                            SelectionDAG &DAG) const {
16310   MachineFunction &MF = DAG.getMachineFunction();
16311   MachineFrameInfo &MFI = MF.getFrameInfo();
16312   MFI.setReturnAddressIsTaken(true);
16313 
16314   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16315     return SDValue();
16316 
16317   SDLoc dl(Op);
16318   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16319 
16320   // Make sure the function does not optimize away the store of the RA to
16321   // the stack.
16322   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16323   FuncInfo->setLRStoreRequired();
16324   bool isPPC64 = Subtarget.isPPC64();
16325   auto PtrVT = getPointerTy(MF.getDataLayout());
16326 
16327   if (Depth > 0) {
16328     // The link register (return address) is saved in the caller's frame
16329     // not the callee's stack frame. So we must get the caller's frame
16330     // address and load the return address at the LR offset from there.
16331     SDValue FrameAddr =
16332         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16333                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16334     SDValue Offset =
16335         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16336                         isPPC64 ? MVT::i64 : MVT::i32);
16337     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16338                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16339                        MachinePointerInfo());
16340   }
16341 
16342   // Just load the return address off the stack.
16343   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16344   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16345                      MachinePointerInfo());
16346 }
16347 
16348 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16349                                           SelectionDAG &DAG) const {
16350   SDLoc dl(Op);
16351   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16352 
16353   MachineFunction &MF = DAG.getMachineFunction();
16354   MachineFrameInfo &MFI = MF.getFrameInfo();
16355   MFI.setFrameAddressIsTaken(true);
16356 
16357   EVT PtrVT = getPointerTy(MF.getDataLayout());
16358   bool isPPC64 = PtrVT == MVT::i64;
16359 
16360   // Naked functions never have a frame pointer, and so we use r1. For all
16361   // other functions, this decision must be delayed until during PEI.
16362   unsigned FrameReg;
16363   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16364     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16365   else
16366     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16367 
16368   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16369                                          PtrVT);
16370   while (Depth--)
16371     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16372                             FrameAddr, MachinePointerInfo());
16373   return FrameAddr;
16374 }
16375 
16376 // FIXME? Maybe this could be a TableGen attribute on some registers and
16377 // this table could be generated automatically from RegInfo.
16378 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16379                                               const MachineFunction &MF) const {
16380   bool isPPC64 = Subtarget.isPPC64();
16381 
16382   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16383   if (!is64Bit && VT != LLT::scalar(32))
16384     report_fatal_error("Invalid register global variable type");
16385 
16386   Register Reg = StringSwitch<Register>(RegName)
16387                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16388                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16389                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16390                      .Default(Register());
16391 
16392   if (Reg)
16393     return Reg;
16394   report_fatal_error("Invalid register name global variable");
16395 }
16396 
16397 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16398   // 32-bit SVR4 ABI access everything as got-indirect.
16399   if (Subtarget.is32BitELFABI())
16400     return true;
16401 
16402   // AIX accesses everything indirectly through the TOC, which is similar to
16403   // the GOT.
16404   if (Subtarget.isAIXABI())
16405     return true;
16406 
16407   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16408   // If it is small or large code model, module locals are accessed
16409   // indirectly by loading their address from .toc/.got.
16410   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16411     return true;
16412 
16413   // JumpTable and BlockAddress are accessed as got-indirect.
16414   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16415     return true;
16416 
16417   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16418     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16419 
16420   return false;
16421 }
16422 
16423 bool
16424 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16425   // The PowerPC target isn't yet aware of offsets.
16426   return false;
16427 }
16428 
16429 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16430                                            const CallInst &I,
16431                                            MachineFunction &MF,
16432                                            unsigned Intrinsic) const {
16433   switch (Intrinsic) {
16434   case Intrinsic::ppc_atomicrmw_xchg_i128:
16435   case Intrinsic::ppc_atomicrmw_add_i128:
16436   case Intrinsic::ppc_atomicrmw_sub_i128:
16437   case Intrinsic::ppc_atomicrmw_nand_i128:
16438   case Intrinsic::ppc_atomicrmw_and_i128:
16439   case Intrinsic::ppc_atomicrmw_or_i128:
16440   case Intrinsic::ppc_atomicrmw_xor_i128:
16441   case Intrinsic::ppc_cmpxchg_i128:
16442     Info.opc = ISD::INTRINSIC_W_CHAIN;
16443     Info.memVT = MVT::i128;
16444     Info.ptrVal = I.getArgOperand(0);
16445     Info.offset = 0;
16446     Info.align = Align(16);
16447     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16448                  MachineMemOperand::MOVolatile;
16449     return true;
16450   case Intrinsic::ppc_atomic_load_i128:
16451     Info.opc = ISD::INTRINSIC_W_CHAIN;
16452     Info.memVT = MVT::i128;
16453     Info.ptrVal = I.getArgOperand(0);
16454     Info.offset = 0;
16455     Info.align = Align(16);
16456     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16457     return true;
16458   case Intrinsic::ppc_atomic_store_i128:
16459     Info.opc = ISD::INTRINSIC_VOID;
16460     Info.memVT = MVT::i128;
16461     Info.ptrVal = I.getArgOperand(2);
16462     Info.offset = 0;
16463     Info.align = Align(16);
16464     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16465     return true;
16466   case Intrinsic::ppc_altivec_lvx:
16467   case Intrinsic::ppc_altivec_lvxl:
16468   case Intrinsic::ppc_altivec_lvebx:
16469   case Intrinsic::ppc_altivec_lvehx:
16470   case Intrinsic::ppc_altivec_lvewx:
16471   case Intrinsic::ppc_vsx_lxvd2x:
16472   case Intrinsic::ppc_vsx_lxvw4x:
16473   case Intrinsic::ppc_vsx_lxvd2x_be:
16474   case Intrinsic::ppc_vsx_lxvw4x_be:
16475   case Intrinsic::ppc_vsx_lxvl:
16476   case Intrinsic::ppc_vsx_lxvll: {
16477     EVT VT;
16478     switch (Intrinsic) {
16479     case Intrinsic::ppc_altivec_lvebx:
16480       VT = MVT::i8;
16481       break;
16482     case Intrinsic::ppc_altivec_lvehx:
16483       VT = MVT::i16;
16484       break;
16485     case Intrinsic::ppc_altivec_lvewx:
16486       VT = MVT::i32;
16487       break;
16488     case Intrinsic::ppc_vsx_lxvd2x:
16489     case Intrinsic::ppc_vsx_lxvd2x_be:
16490       VT = MVT::v2f64;
16491       break;
16492     default:
16493       VT = MVT::v4i32;
16494       break;
16495     }
16496 
16497     Info.opc = ISD::INTRINSIC_W_CHAIN;
16498     Info.memVT = VT;
16499     Info.ptrVal = I.getArgOperand(0);
16500     Info.offset = -VT.getStoreSize()+1;
16501     Info.size = 2*VT.getStoreSize()-1;
16502     Info.align = Align(1);
16503     Info.flags = MachineMemOperand::MOLoad;
16504     return true;
16505   }
16506   case Intrinsic::ppc_altivec_stvx:
16507   case Intrinsic::ppc_altivec_stvxl:
16508   case Intrinsic::ppc_altivec_stvebx:
16509   case Intrinsic::ppc_altivec_stvehx:
16510   case Intrinsic::ppc_altivec_stvewx:
16511   case Intrinsic::ppc_vsx_stxvd2x:
16512   case Intrinsic::ppc_vsx_stxvw4x:
16513   case Intrinsic::ppc_vsx_stxvd2x_be:
16514   case Intrinsic::ppc_vsx_stxvw4x_be:
16515   case Intrinsic::ppc_vsx_stxvl:
16516   case Intrinsic::ppc_vsx_stxvll: {
16517     EVT VT;
16518     switch (Intrinsic) {
16519     case Intrinsic::ppc_altivec_stvebx:
16520       VT = MVT::i8;
16521       break;
16522     case Intrinsic::ppc_altivec_stvehx:
16523       VT = MVT::i16;
16524       break;
16525     case Intrinsic::ppc_altivec_stvewx:
16526       VT = MVT::i32;
16527       break;
16528     case Intrinsic::ppc_vsx_stxvd2x:
16529     case Intrinsic::ppc_vsx_stxvd2x_be:
16530       VT = MVT::v2f64;
16531       break;
16532     default:
16533       VT = MVT::v4i32;
16534       break;
16535     }
16536 
16537     Info.opc = ISD::INTRINSIC_VOID;
16538     Info.memVT = VT;
16539     Info.ptrVal = I.getArgOperand(1);
16540     Info.offset = -VT.getStoreSize()+1;
16541     Info.size = 2*VT.getStoreSize()-1;
16542     Info.align = Align(1);
16543     Info.flags = MachineMemOperand::MOStore;
16544     return true;
16545   }
16546   default:
16547     break;
16548   }
16549 
16550   return false;
16551 }
16552 
16553 /// It returns EVT::Other if the type should be determined using generic
16554 /// target-independent logic.
16555 EVT PPCTargetLowering::getOptimalMemOpType(
16556     const MemOp &Op, const AttributeList &FuncAttributes) const {
16557   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16558     // We should use Altivec/VSX loads and stores when available. For unaligned
16559     // addresses, unaligned VSX loads are only fast starting with the P8.
16560     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16561         (Op.isAligned(Align(16)) ||
16562          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16563       return MVT::v4i32;
16564   }
16565 
16566   if (Subtarget.isPPC64()) {
16567     return MVT::i64;
16568   }
16569 
16570   return MVT::i32;
16571 }
16572 
16573 /// Returns true if it is beneficial to convert a load of a constant
16574 /// to just the constant itself.
16575 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16576                                                           Type *Ty) const {
16577   assert(Ty->isIntegerTy());
16578 
16579   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16580   return !(BitSize == 0 || BitSize > 64);
16581 }
16582 
16583 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16584   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16585     return false;
16586   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16587   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16588   return NumBits1 == 64 && NumBits2 == 32;
16589 }
16590 
16591 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16592   if (!VT1.isInteger() || !VT2.isInteger())
16593     return false;
16594   unsigned NumBits1 = VT1.getSizeInBits();
16595   unsigned NumBits2 = VT2.getSizeInBits();
16596   return NumBits1 == 64 && NumBits2 == 32;
16597 }
16598 
16599 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16600   // Generally speaking, zexts are not free, but they are free when they can be
16601   // folded with other operations.
16602   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16603     EVT MemVT = LD->getMemoryVT();
16604     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16605          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16606         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16607          LD->getExtensionType() == ISD::ZEXTLOAD))
16608       return true;
16609   }
16610 
16611   // FIXME: Add other cases...
16612   //  - 32-bit shifts with a zext to i64
16613   //  - zext after ctlz, bswap, etc.
16614   //  - zext after and by a constant mask
16615 
16616   return TargetLowering::isZExtFree(Val, VT2);
16617 }
16618 
16619 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16620   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16621          "invalid fpext types");
16622   // Extending to float128 is not free.
16623   if (DestVT == MVT::f128)
16624     return false;
16625   return true;
16626 }
16627 
16628 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16629   return isInt<16>(Imm) || isUInt<16>(Imm);
16630 }
16631 
16632 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16633   return isInt<16>(Imm) || isUInt<16>(Imm);
16634 }
16635 
16636 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16637                                                        MachineMemOperand::Flags,
16638                                                        bool *Fast) const {
16639   if (DisablePPCUnaligned)
16640     return false;
16641 
16642   // PowerPC supports unaligned memory access for simple non-vector types.
16643   // Although accessing unaligned addresses is not as efficient as accessing
16644   // aligned addresses, it is generally more efficient than manual expansion,
16645   // and generally only traps for software emulation when crossing page
16646   // boundaries.
16647 
16648   if (!VT.isSimple())
16649     return false;
16650 
16651   if (VT.isFloatingPoint() && !VT.isVector() &&
16652       !Subtarget.allowsUnalignedFPAccess())
16653     return false;
16654 
16655   if (VT.getSimpleVT().isVector()) {
16656     if (Subtarget.hasVSX()) {
16657       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16658           VT != MVT::v4f32 && VT != MVT::v4i32)
16659         return false;
16660     } else {
16661       return false;
16662     }
16663   }
16664 
16665   if (VT == MVT::ppcf128)
16666     return false;
16667 
16668   if (Fast)
16669     *Fast = true;
16670 
16671   return true;
16672 }
16673 
16674 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16675                                                SDValue C) const {
16676   // Check integral scalar types.
16677   if (!VT.isScalarInteger())
16678     return false;
16679   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16680     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16681       return false;
16682     // This transformation will generate >= 2 operations. But the following
16683     // cases will generate <= 2 instructions during ISEL. So exclude them.
16684     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16685     // HW instruction, ie. MULLI
16686     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16687     // instruction is needed than case 1, ie. MULLI and RLDICR
16688     int64_t Imm = ConstNode->getSExtValue();
16689     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16690     Imm >>= Shift;
16691     if (isInt<16>(Imm))
16692       return false;
16693     uint64_t UImm = static_cast<uint64_t>(Imm);
16694     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16695         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16696       return true;
16697   }
16698   return false;
16699 }
16700 
16701 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16702                                                    EVT VT) const {
16703   return isFMAFasterThanFMulAndFAdd(
16704       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16705 }
16706 
16707 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16708                                                    Type *Ty) const {
16709   switch (Ty->getScalarType()->getTypeID()) {
16710   case Type::FloatTyID:
16711   case Type::DoubleTyID:
16712     return true;
16713   case Type::FP128TyID:
16714     return Subtarget.hasP9Vector();
16715   default:
16716     return false;
16717   }
16718 }
16719 
16720 // FIXME: add more patterns which are not profitable to hoist.
16721 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16722   if (!I->hasOneUse())
16723     return true;
16724 
16725   Instruction *User = I->user_back();
16726   assert(User && "A single use instruction with no uses.");
16727 
16728   switch (I->getOpcode()) {
16729   case Instruction::FMul: {
16730     // Don't break FMA, PowerPC prefers FMA.
16731     if (User->getOpcode() != Instruction::FSub &&
16732         User->getOpcode() != Instruction::FAdd)
16733       return true;
16734 
16735     const TargetOptions &Options = getTargetMachine().Options;
16736     const Function *F = I->getFunction();
16737     const DataLayout &DL = F->getParent()->getDataLayout();
16738     Type *Ty = User->getOperand(0)->getType();
16739 
16740     return !(
16741         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16742         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16743         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16744   }
16745   case Instruction::Load: {
16746     // Don't break "store (load float*)" pattern, this pattern will be combined
16747     // to "store (load int32)" in later InstCombine pass. See function
16748     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16749     // cycles than loading a 32 bit integer.
16750     LoadInst *LI = cast<LoadInst>(I);
16751     // For the loads that combineLoadToOperationType does nothing, like
16752     // ordered load, it should be profitable to hoist them.
16753     // For swifterror load, it can only be used for pointer to pointer type, so
16754     // later type check should get rid of this case.
16755     if (!LI->isUnordered())
16756       return true;
16757 
16758     if (User->getOpcode() != Instruction::Store)
16759       return true;
16760 
16761     if (I->getType()->getTypeID() != Type::FloatTyID)
16762       return true;
16763 
16764     return false;
16765   }
16766   default:
16767     return true;
16768   }
16769   return true;
16770 }
16771 
16772 const MCPhysReg *
16773 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16774   // LR is a callee-save register, but we must treat it as clobbered by any call
16775   // site. Hence we include LR in the scratch registers, which are in turn added
16776   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16777   // to CTR, which is used by any indirect call.
16778   static const MCPhysReg ScratchRegs[] = {
16779     PPC::X12, PPC::LR8, PPC::CTR8, 0
16780   };
16781 
16782   return ScratchRegs;
16783 }
16784 
16785 Register PPCTargetLowering::getExceptionPointerRegister(
16786     const Constant *PersonalityFn) const {
16787   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16788 }
16789 
16790 Register PPCTargetLowering::getExceptionSelectorRegister(
16791     const Constant *PersonalityFn) const {
16792   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16793 }
16794 
16795 bool
16796 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16797                      EVT VT , unsigned DefinedValues) const {
16798   if (VT == MVT::v2i64)
16799     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16800 
16801   if (Subtarget.hasVSX())
16802     return true;
16803 
16804   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16805 }
16806 
16807 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16808   if (DisableILPPref || Subtarget.enableMachineScheduler())
16809     return TargetLowering::getSchedulingPreference(N);
16810 
16811   return Sched::ILP;
16812 }
16813 
16814 // Create a fast isel object.
16815 FastISel *
16816 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16817                                   const TargetLibraryInfo *LibInfo) const {
16818   return PPC::createFastISel(FuncInfo, LibInfo);
16819 }
16820 
16821 // 'Inverted' means the FMA opcode after negating one multiplicand.
16822 // For example, (fma -a b c) = (fnmsub a b c)
16823 static unsigned invertFMAOpcode(unsigned Opc) {
16824   switch (Opc) {
16825   default:
16826     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16827   case ISD::FMA:
16828     return PPCISD::FNMSUB;
16829   case PPCISD::FNMSUB:
16830     return ISD::FMA;
16831   }
16832 }
16833 
16834 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16835                                                 bool LegalOps, bool OptForSize,
16836                                                 NegatibleCost &Cost,
16837                                                 unsigned Depth) const {
16838   if (Depth > SelectionDAG::MaxRecursionDepth)
16839     return SDValue();
16840 
16841   unsigned Opc = Op.getOpcode();
16842   EVT VT = Op.getValueType();
16843   SDNodeFlags Flags = Op.getNode()->getFlags();
16844 
16845   switch (Opc) {
16846   case PPCISD::FNMSUB:
16847     if (!Op.hasOneUse() || !isTypeLegal(VT))
16848       break;
16849 
16850     const TargetOptions &Options = getTargetMachine().Options;
16851     SDValue N0 = Op.getOperand(0);
16852     SDValue N1 = Op.getOperand(1);
16853     SDValue N2 = Op.getOperand(2);
16854     SDLoc Loc(Op);
16855 
16856     NegatibleCost N2Cost = NegatibleCost::Expensive;
16857     SDValue NegN2 =
16858         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16859 
16860     if (!NegN2)
16861       return SDValue();
16862 
16863     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16864     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16865     // These transformations may change sign of zeroes. For example,
16866     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16867     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16868       // Try and choose the cheaper one to negate.
16869       NegatibleCost N0Cost = NegatibleCost::Expensive;
16870       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16871                                            N0Cost, Depth + 1);
16872 
16873       NegatibleCost N1Cost = NegatibleCost::Expensive;
16874       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16875                                            N1Cost, Depth + 1);
16876 
16877       if (NegN0 && N0Cost <= N1Cost) {
16878         Cost = std::min(N0Cost, N2Cost);
16879         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16880       } else if (NegN1) {
16881         Cost = std::min(N1Cost, N2Cost);
16882         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16883       }
16884     }
16885 
16886     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16887     if (isOperationLegal(ISD::FMA, VT)) {
16888       Cost = N2Cost;
16889       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16890     }
16891 
16892     break;
16893   }
16894 
16895   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16896                                               Cost, Depth);
16897 }
16898 
16899 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16900 bool PPCTargetLowering::useLoadStackGuardNode() const {
16901   if (!Subtarget.isTargetLinux())
16902     return TargetLowering::useLoadStackGuardNode();
16903   return true;
16904 }
16905 
16906 // Override to disable global variable loading on Linux and insert AIX canary
16907 // word declaration.
16908 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16909   if (Subtarget.isAIXABI()) {
16910     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16911                         Type::getInt8PtrTy(M.getContext()));
16912     return;
16913   }
16914   if (!Subtarget.isTargetLinux())
16915     return TargetLowering::insertSSPDeclarations(M);
16916 }
16917 
16918 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16919   if (Subtarget.isAIXABI())
16920     return M.getGlobalVariable(AIXSSPCanaryWordName);
16921   return TargetLowering::getSDagStackGuard(M);
16922 }
16923 
16924 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16925                                      bool ForCodeSize) const {
16926   if (!VT.isSimple() || !Subtarget.hasVSX())
16927     return false;
16928 
16929   switch(VT.getSimpleVT().SimpleTy) {
16930   default:
16931     // For FP types that are currently not supported by PPC backend, return
16932     // false. Examples: f16, f80.
16933     return false;
16934   case MVT::f32:
16935   case MVT::f64:
16936     if (Subtarget.hasPrefixInstrs()) {
16937       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16938       return true;
16939     }
16940     LLVM_FALLTHROUGH;
16941   case MVT::ppcf128:
16942     return Imm.isPosZero();
16943   }
16944 }
16945 
16946 // For vector shift operation op, fold
16947 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16948 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16949                                   SelectionDAG &DAG) {
16950   SDValue N0 = N->getOperand(0);
16951   SDValue N1 = N->getOperand(1);
16952   EVT VT = N0.getValueType();
16953   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16954   unsigned Opcode = N->getOpcode();
16955   unsigned TargetOpcode;
16956 
16957   switch (Opcode) {
16958   default:
16959     llvm_unreachable("Unexpected shift operation");
16960   case ISD::SHL:
16961     TargetOpcode = PPCISD::SHL;
16962     break;
16963   case ISD::SRL:
16964     TargetOpcode = PPCISD::SRL;
16965     break;
16966   case ISD::SRA:
16967     TargetOpcode = PPCISD::SRA;
16968     break;
16969   }
16970 
16971   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16972       N1->getOpcode() == ISD::AND)
16973     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16974       if (Mask->getZExtValue() == OpSizeInBits - 1)
16975         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16976 
16977   return SDValue();
16978 }
16979 
16980 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16981   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16982     return Value;
16983 
16984   SDValue N0 = N->getOperand(0);
16985   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16986   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16987       N0.getOpcode() != ISD::SIGN_EXTEND ||
16988       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16989       N->getValueType(0) != MVT::i64)
16990     return SDValue();
16991 
16992   // We can't save an operation here if the value is already extended, and
16993   // the existing shift is easier to combine.
16994   SDValue ExtsSrc = N0.getOperand(0);
16995   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16996       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16997     return SDValue();
16998 
16999   SDLoc DL(N0);
17000   SDValue ShiftBy = SDValue(CN1, 0);
17001   // We want the shift amount to be i32 on the extswli, but the shift could
17002   // have an i64.
17003   if (ShiftBy.getValueType() == MVT::i64)
17004     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
17005 
17006   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
17007                          ShiftBy);
17008 }
17009 
17010 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
17011   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
17012     return Value;
17013 
17014   return SDValue();
17015 }
17016 
17017 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
17018   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
17019     return Value;
17020 
17021   return SDValue();
17022 }
17023 
17024 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
17025 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
17026 // When C is zero, the equation (addi Z, -C) can be simplified to Z
17027 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
17028 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
17029                                  const PPCSubtarget &Subtarget) {
17030   if (!Subtarget.isPPC64())
17031     return SDValue();
17032 
17033   SDValue LHS = N->getOperand(0);
17034   SDValue RHS = N->getOperand(1);
17035 
17036   auto isZextOfCompareWithConstant = [](SDValue Op) {
17037     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
17038         Op.getValueType() != MVT::i64)
17039       return false;
17040 
17041     SDValue Cmp = Op.getOperand(0);
17042     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
17043         Cmp.getOperand(0).getValueType() != MVT::i64)
17044       return false;
17045 
17046     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
17047       int64_t NegConstant = 0 - Constant->getSExtValue();
17048       // Due to the limitations of the addi instruction,
17049       // -C is required to be [-32768, 32767].
17050       return isInt<16>(NegConstant);
17051     }
17052 
17053     return false;
17054   };
17055 
17056   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
17057   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
17058 
17059   // If there is a pattern, canonicalize a zext operand to the RHS.
17060   if (LHSHasPattern && !RHSHasPattern)
17061     std::swap(LHS, RHS);
17062   else if (!LHSHasPattern && !RHSHasPattern)
17063     return SDValue();
17064 
17065   SDLoc DL(N);
17066   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
17067   SDValue Cmp = RHS.getOperand(0);
17068   SDValue Z = Cmp.getOperand(0);
17069   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
17070   int64_t NegConstant = 0 - Constant->getSExtValue();
17071 
17072   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
17073   default: break;
17074   case ISD::SETNE: {
17075     //                                 when C == 0
17076     //                             --> addze X, (addic Z, -1).carry
17077     //                            /
17078     // add X, (zext(setne Z, C))--
17079     //                            \    when -32768 <= -C <= 32767 && C != 0
17080     //                             --> addze X, (addic (addi Z, -C), -1).carry
17081     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17082                               DAG.getConstant(NegConstant, DL, MVT::i64));
17083     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17084     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17085                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
17086     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17087                        SDValue(Addc.getNode(), 1));
17088     }
17089   case ISD::SETEQ: {
17090     //                                 when C == 0
17091     //                             --> addze X, (subfic Z, 0).carry
17092     //                            /
17093     // add X, (zext(sete  Z, C))--
17094     //                            \    when -32768 <= -C <= 32767 && C != 0
17095     //                             --> addze X, (subfic (addi Z, -C), 0).carry
17096     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17097                               DAG.getConstant(NegConstant, DL, MVT::i64));
17098     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17099     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17100                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
17101     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17102                        SDValue(Subc.getNode(), 1));
17103     }
17104   }
17105 
17106   return SDValue();
17107 }
17108 
17109 // Transform
17110 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17111 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17112 // In this case both C1 and C2 must be known constants.
17113 // C1+C2 must fit into a 34 bit signed integer.
17114 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17115                                           const PPCSubtarget &Subtarget) {
17116   if (!Subtarget.isUsingPCRelativeCalls())
17117     return SDValue();
17118 
17119   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17120   // If we find that node try to cast the Global Address and the Constant.
17121   SDValue LHS = N->getOperand(0);
17122   SDValue RHS = N->getOperand(1);
17123 
17124   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17125     std::swap(LHS, RHS);
17126 
17127   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17128     return SDValue();
17129 
17130   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17131   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17132   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17133 
17134   // Check that both casts succeeded.
17135   if (!GSDN || !ConstNode)
17136     return SDValue();
17137 
17138   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17139   SDLoc DL(GSDN);
17140 
17141   // The signed int offset needs to fit in 34 bits.
17142   if (!isInt<34>(NewOffset))
17143     return SDValue();
17144 
17145   // The new global address is a copy of the old global address except
17146   // that it has the updated Offset.
17147   SDValue GA =
17148       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17149                                  NewOffset, GSDN->getTargetFlags());
17150   SDValue MatPCRel =
17151       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17152   return MatPCRel;
17153 }
17154 
17155 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17156   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17157     return Value;
17158 
17159   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17160     return Value;
17161 
17162   return SDValue();
17163 }
17164 
17165 // Detect TRUNCATE operations on bitcasts of float128 values.
17166 // What we are looking for here is the situtation where we extract a subset
17167 // of bits from a 128 bit float.
17168 // This can be of two forms:
17169 // 1) BITCAST of f128 feeding TRUNCATE
17170 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17171 // The reason this is required is because we do not have a legal i128 type
17172 // and so we want to prevent having to store the f128 and then reload part
17173 // of it.
17174 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17175                                            DAGCombinerInfo &DCI) const {
17176   // If we are using CRBits then try that first.
17177   if (Subtarget.useCRBits()) {
17178     // Check if CRBits did anything and return that if it did.
17179     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17180       return CRTruncValue;
17181   }
17182 
17183   SDLoc dl(N);
17184   SDValue Op0 = N->getOperand(0);
17185 
17186   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17187   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17188     EVT VT = N->getValueType(0);
17189     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17190       return SDValue();
17191     SDValue Sub = Op0.getOperand(0);
17192     if (Sub.getOpcode() == ISD::SUB) {
17193       SDValue SubOp0 = Sub.getOperand(0);
17194       SDValue SubOp1 = Sub.getOperand(1);
17195       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17196           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17197         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17198                                SubOp1.getOperand(0),
17199                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17200       }
17201     }
17202   }
17203 
17204   // Looking for a truncate of i128 to i64.
17205   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17206     return SDValue();
17207 
17208   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17209 
17210   // SRL feeding TRUNCATE.
17211   if (Op0.getOpcode() == ISD::SRL) {
17212     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17213     // The right shift has to be by 64 bits.
17214     if (!ConstNode || ConstNode->getZExtValue() != 64)
17215       return SDValue();
17216 
17217     // Switch the element number to extract.
17218     EltToExtract = EltToExtract ? 0 : 1;
17219     // Update Op0 past the SRL.
17220     Op0 = Op0.getOperand(0);
17221   }
17222 
17223   // BITCAST feeding a TRUNCATE possibly via SRL.
17224   if (Op0.getOpcode() == ISD::BITCAST &&
17225       Op0.getValueType() == MVT::i128 &&
17226       Op0.getOperand(0).getValueType() == MVT::f128) {
17227     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17228     return DCI.DAG.getNode(
17229         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17230         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17231   }
17232   return SDValue();
17233 }
17234 
17235 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17236   SelectionDAG &DAG = DCI.DAG;
17237 
17238   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17239   if (!ConstOpOrElement)
17240     return SDValue();
17241 
17242   // An imul is usually smaller than the alternative sequence for legal type.
17243   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17244       isOperationLegal(ISD::MUL, N->getValueType(0)))
17245     return SDValue();
17246 
17247   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17248     switch (this->Subtarget.getCPUDirective()) {
17249     default:
17250       // TODO: enhance the condition for subtarget before pwr8
17251       return false;
17252     case PPC::DIR_PWR8:
17253       //  type        mul     add    shl
17254       // scalar        4       1      1
17255       // vector        7       2      2
17256       return true;
17257     case PPC::DIR_PWR9:
17258     case PPC::DIR_PWR10:
17259     case PPC::DIR_PWR_FUTURE:
17260       //  type        mul     add    shl
17261       // scalar        5       2      2
17262       // vector        7       2      2
17263 
17264       // The cycle RATIO of related operations are showed as a table above.
17265       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17266       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17267       // are 4, it is always profitable; but for 3 instrs patterns
17268       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17269       // So we should only do it for vector type.
17270       return IsAddOne && IsNeg ? VT.isVector() : true;
17271     }
17272   };
17273 
17274   EVT VT = N->getValueType(0);
17275   SDLoc DL(N);
17276 
17277   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17278   bool IsNeg = MulAmt.isNegative();
17279   APInt MulAmtAbs = MulAmt.abs();
17280 
17281   if ((MulAmtAbs - 1).isPowerOf2()) {
17282     // (mul x, 2^N + 1) => (add (shl x, N), x)
17283     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17284 
17285     if (!IsProfitable(IsNeg, true, VT))
17286       return SDValue();
17287 
17288     SDValue Op0 = N->getOperand(0);
17289     SDValue Op1 =
17290         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17291                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17292     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17293 
17294     if (!IsNeg)
17295       return Res;
17296 
17297     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17298   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17299     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17300     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17301 
17302     if (!IsProfitable(IsNeg, false, VT))
17303       return SDValue();
17304 
17305     SDValue Op0 = N->getOperand(0);
17306     SDValue Op1 =
17307         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17308                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17309 
17310     if (!IsNeg)
17311       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17312     else
17313       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17314 
17315   } else {
17316     return SDValue();
17317   }
17318 }
17319 
17320 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17321 // in combiner since we need to check SD flags and other subtarget features.
17322 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17323                                           DAGCombinerInfo &DCI) const {
17324   SDValue N0 = N->getOperand(0);
17325   SDValue N1 = N->getOperand(1);
17326   SDValue N2 = N->getOperand(2);
17327   SDNodeFlags Flags = N->getFlags();
17328   EVT VT = N->getValueType(0);
17329   SelectionDAG &DAG = DCI.DAG;
17330   const TargetOptions &Options = getTargetMachine().Options;
17331   unsigned Opc = N->getOpcode();
17332   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17333   bool LegalOps = !DCI.isBeforeLegalizeOps();
17334   SDLoc Loc(N);
17335 
17336   if (!isOperationLegal(ISD::FMA, VT))
17337     return SDValue();
17338 
17339   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17340   // since (fnmsub a b c)=-0 while c-ab=+0.
17341   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17342     return SDValue();
17343 
17344   // (fma (fneg a) b c) => (fnmsub a b c)
17345   // (fnmsub (fneg a) b c) => (fma a b c)
17346   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17347     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17348 
17349   // (fma a (fneg b) c) => (fnmsub a b c)
17350   // (fnmsub a (fneg b) c) => (fma a b c)
17351   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17352     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17353 
17354   return SDValue();
17355 }
17356 
17357 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17358   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17359   if (!Subtarget.is64BitELFABI())
17360     return false;
17361 
17362   // If not a tail call then no need to proceed.
17363   if (!CI->isTailCall())
17364     return false;
17365 
17366   // If sibling calls have been disabled and tail-calls aren't guaranteed
17367   // there is no reason to duplicate.
17368   auto &TM = getTargetMachine();
17369   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17370     return false;
17371 
17372   // Can't tail call a function called indirectly, or if it has variadic args.
17373   const Function *Callee = CI->getCalledFunction();
17374   if (!Callee || Callee->isVarArg())
17375     return false;
17376 
17377   // Make sure the callee and caller calling conventions are eligible for tco.
17378   const Function *Caller = CI->getParent()->getParent();
17379   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17380                                            CI->getCallingConv()))
17381       return false;
17382 
17383   // If the function is local then we have a good chance at tail-calling it
17384   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17385 }
17386 
17387 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17388   if (!Subtarget.hasVSX())
17389     return false;
17390   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17391     return true;
17392   return VT == MVT::f32 || VT == MVT::f64 ||
17393     VT == MVT::v4f32 || VT == MVT::v2f64;
17394 }
17395 
17396 bool PPCTargetLowering::
17397 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17398   const Value *Mask = AndI.getOperand(1);
17399   // If the mask is suitable for andi. or andis. we should sink the and.
17400   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17401     // Can't handle constants wider than 64-bits.
17402     if (CI->getBitWidth() > 64)
17403       return false;
17404     int64_t ConstVal = CI->getZExtValue();
17405     return isUInt<16>(ConstVal) ||
17406       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17407   }
17408 
17409   // For non-constant masks, we can always use the record-form and.
17410   return true;
17411 }
17412 
17413 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17414 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17415 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17416 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17417 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17418 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17419   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17420   assert(Subtarget.hasP9Altivec() &&
17421          "Only combine this when P9 altivec supported!");
17422   EVT VT = N->getValueType(0);
17423   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17424     return SDValue();
17425 
17426   SelectionDAG &DAG = DCI.DAG;
17427   SDLoc dl(N);
17428   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17429     // Even for signed integers, if it's known to be positive (as signed
17430     // integer) due to zero-extended inputs.
17431     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17432     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17433     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17434          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17435         (SubOpcd1 == ISD::ZERO_EXTEND ||
17436          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17437       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17438                          N->getOperand(0)->getOperand(0),
17439                          N->getOperand(0)->getOperand(1),
17440                          DAG.getTargetConstant(0, dl, MVT::i32));
17441     }
17442 
17443     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17444     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17445         N->getOperand(0).hasOneUse()) {
17446       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17447                          N->getOperand(0)->getOperand(0),
17448                          N->getOperand(0)->getOperand(1),
17449                          DAG.getTargetConstant(1, dl, MVT::i32));
17450     }
17451   }
17452 
17453   return SDValue();
17454 }
17455 
17456 // For type v4i32/v8ii16/v16i8, transform
17457 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17458 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17459 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17460 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17461 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17462                                           DAGCombinerInfo &DCI) const {
17463   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17464   assert(Subtarget.hasP9Altivec() &&
17465          "Only combine this when P9 altivec supported!");
17466 
17467   SelectionDAG &DAG = DCI.DAG;
17468   SDLoc dl(N);
17469   SDValue Cond = N->getOperand(0);
17470   SDValue TrueOpnd = N->getOperand(1);
17471   SDValue FalseOpnd = N->getOperand(2);
17472   EVT VT = N->getOperand(1).getValueType();
17473 
17474   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17475       FalseOpnd.getOpcode() != ISD::SUB)
17476     return SDValue();
17477 
17478   // ABSD only available for type v4i32/v8i16/v16i8
17479   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17480     return SDValue();
17481 
17482   // At least to save one more dependent computation
17483   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17484     return SDValue();
17485 
17486   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17487 
17488   // Can only handle unsigned comparison here
17489   switch (CC) {
17490   default:
17491     return SDValue();
17492   case ISD::SETUGT:
17493   case ISD::SETUGE:
17494     break;
17495   case ISD::SETULT:
17496   case ISD::SETULE:
17497     std::swap(TrueOpnd, FalseOpnd);
17498     break;
17499   }
17500 
17501   SDValue CmpOpnd1 = Cond.getOperand(0);
17502   SDValue CmpOpnd2 = Cond.getOperand(1);
17503 
17504   // SETCC CmpOpnd1 CmpOpnd2 cond
17505   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17506   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17507   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17508       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17509       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17510       FalseOpnd.getOperand(1) == CmpOpnd1) {
17511     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17512                        CmpOpnd1, CmpOpnd2,
17513                        DAG.getTargetConstant(0, dl, MVT::i32));
17514   }
17515 
17516   return SDValue();
17517 }
17518 
17519 /// getAddrModeForFlags - Based on the set of address flags, select the most
17520 /// optimal instruction format to match by.
17521 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17522   // This is not a node we should be handling here.
17523   if (Flags == PPC::MOF_None)
17524     return PPC::AM_None;
17525   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17526   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17527     if ((Flags & FlagSet) == FlagSet)
17528       return PPC::AM_DForm;
17529   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17530     if ((Flags & FlagSet) == FlagSet)
17531       return PPC::AM_DSForm;
17532   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17533     if ((Flags & FlagSet) == FlagSet)
17534       return PPC::AM_DQForm;
17535   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17536     if ((Flags & FlagSet) == FlagSet)
17537       return PPC::AM_PrefixDForm;
17538   // If no other forms are selected, return an X-Form as it is the most
17539   // general addressing mode.
17540   return PPC::AM_XForm;
17541 }
17542 
17543 /// Set alignment flags based on whether or not the Frame Index is aligned.
17544 /// Utilized when computing flags for address computation when selecting
17545 /// load and store instructions.
17546 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17547                                SelectionDAG &DAG) {
17548   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17549   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17550   if (!FI)
17551     return;
17552   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17553   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17554   // If this is (add $FI, $S16Imm), the alignment flags are already set
17555   // based on the immediate. We just need to clear the alignment flags
17556   // if the FI alignment is weaker.
17557   if ((FrameIndexAlign % 4) != 0)
17558     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17559   if ((FrameIndexAlign % 16) != 0)
17560     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17561   // If the address is a plain FrameIndex, set alignment flags based on
17562   // FI alignment.
17563   if (!IsAdd) {
17564     if ((FrameIndexAlign % 4) == 0)
17565       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17566     if ((FrameIndexAlign % 16) == 0)
17567       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17568   }
17569 }
17570 
17571 /// Given a node, compute flags that are used for address computation when
17572 /// selecting load and store instructions. The flags computed are stored in
17573 /// FlagSet. This function takes into account whether the node is a constant,
17574 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17575 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17576                                               SelectionDAG &DAG) {
17577   // Set the alignment flags for the node depending on if the node is
17578   // 4-byte or 16-byte aligned.
17579   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17580     if ((Imm & 0x3) == 0)
17581       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17582     if ((Imm & 0xf) == 0)
17583       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17584   };
17585 
17586   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17587     // All 32-bit constants can be computed as LIS + Disp.
17588     const APInt &ConstImm = CN->getAPIntValue();
17589     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17590       FlagSet |= PPC::MOF_AddrIsSImm32;
17591       SetAlignFlagsForImm(ConstImm.getZExtValue());
17592       setAlignFlagsForFI(N, FlagSet, DAG);
17593     }
17594     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17595       FlagSet |= PPC::MOF_RPlusSImm34;
17596     else // Let constant materialization handle large constants.
17597       FlagSet |= PPC::MOF_NotAddNorCst;
17598   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17599     // This address can be represented as an addition of:
17600     // - Register + Imm16 (possibly a multiple of 4/16)
17601     // - Register + Imm34
17602     // - Register + PPCISD::Lo
17603     // - Register + Register
17604     // In any case, we won't have to match this as Base + Zero.
17605     SDValue RHS = N.getOperand(1);
17606     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17607       const APInt &ConstImm = CN->getAPIntValue();
17608       if (ConstImm.isSignedIntN(16)) {
17609         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17610         SetAlignFlagsForImm(ConstImm.getZExtValue());
17611         setAlignFlagsForFI(N, FlagSet, DAG);
17612       }
17613       if (ConstImm.isSignedIntN(34))
17614         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17615       else
17616         FlagSet |= PPC::MOF_RPlusR; // Register.
17617     } else if (RHS.getOpcode() == PPCISD::Lo &&
17618                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17619       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17620     else
17621       FlagSet |= PPC::MOF_RPlusR;
17622   } else { // The address computation is not a constant or an addition.
17623     setAlignFlagsForFI(N, FlagSet, DAG);
17624     FlagSet |= PPC::MOF_NotAddNorCst;
17625   }
17626 }
17627 
17628 static bool isPCRelNode(SDValue N) {
17629   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17630       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17631       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17632       isValidPCRelNode<JumpTableSDNode>(N) ||
17633       isValidPCRelNode<BlockAddressSDNode>(N));
17634 }
17635 
17636 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17637 /// the address flags of the load/store instruction that is to be matched.
17638 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17639                                            SelectionDAG &DAG) const {
17640   unsigned FlagSet = PPC::MOF_None;
17641 
17642   // Compute subtarget flags.
17643   if (!Subtarget.hasP9Vector())
17644     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17645   else {
17646     FlagSet |= PPC::MOF_SubtargetP9;
17647     if (Subtarget.hasPrefixInstrs())
17648       FlagSet |= PPC::MOF_SubtargetP10;
17649   }
17650   if (Subtarget.hasSPE())
17651     FlagSet |= PPC::MOF_SubtargetSPE;
17652 
17653   // Check if we have a PCRel node and return early.
17654   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17655     return FlagSet;
17656 
17657   // If the node is the paired load/store intrinsics, compute flags for
17658   // address computation and return early.
17659   unsigned ParentOp = Parent->getOpcode();
17660   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17661                                (ParentOp == ISD::INTRINSIC_VOID))) {
17662     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17663     if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
17664       SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
17665                              ? Parent->getOperand(2)
17666                              : Parent->getOperand(3);
17667       computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17668       FlagSet |= PPC::MOF_Vector;
17669       return FlagSet;
17670     }
17671   }
17672 
17673   // Mark this as something we don't want to handle here if it is atomic
17674   // or pre-increment instruction.
17675   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17676     if (LSB->isIndexed())
17677       return PPC::MOF_None;
17678 
17679   // Compute in-memory type flags. This is based on if there are scalars,
17680   // floats or vectors.
17681   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17682   assert(MN && "Parent should be a MemSDNode!");
17683   EVT MemVT = MN->getMemoryVT();
17684   unsigned Size = MemVT.getSizeInBits();
17685   if (MemVT.isScalarInteger()) {
17686     assert(Size <= 128 &&
17687            "Not expecting scalar integers larger than 16 bytes!");
17688     if (Size < 32)
17689       FlagSet |= PPC::MOF_SubWordInt;
17690     else if (Size == 32)
17691       FlagSet |= PPC::MOF_WordInt;
17692     else
17693       FlagSet |= PPC::MOF_DoubleWordInt;
17694   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17695     if (Size == 128)
17696       FlagSet |= PPC::MOF_Vector;
17697     else if (Size == 256) {
17698       assert(Subtarget.pairedVectorMemops() &&
17699              "256-bit vectors are only available when paired vector memops is "
17700              "enabled!");
17701       FlagSet |= PPC::MOF_Vector;
17702     } else
17703       llvm_unreachable("Not expecting illegal vectors!");
17704   } else { // Floating point type: can be scalar, f128 or vector types.
17705     if (Size == 32 || Size == 64)
17706       FlagSet |= PPC::MOF_ScalarFloat;
17707     else if (MemVT == MVT::f128 || MemVT.isVector())
17708       FlagSet |= PPC::MOF_Vector;
17709     else
17710       llvm_unreachable("Not expecting illegal scalar floats!");
17711   }
17712 
17713   // Compute flags for address computation.
17714   computeFlagsForAddressComputation(N, FlagSet, DAG);
17715 
17716   // Compute type extension flags.
17717   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17718     switch (LN->getExtensionType()) {
17719     case ISD::SEXTLOAD:
17720       FlagSet |= PPC::MOF_SExt;
17721       break;
17722     case ISD::EXTLOAD:
17723     case ISD::ZEXTLOAD:
17724       FlagSet |= PPC::MOF_ZExt;
17725       break;
17726     case ISD::NON_EXTLOAD:
17727       FlagSet |= PPC::MOF_NoExt;
17728       break;
17729     }
17730   } else
17731     FlagSet |= PPC::MOF_NoExt;
17732 
17733   // For integers, no extension is the same as zero extension.
17734   // We set the extension mode to zero extension so we don't have
17735   // to add separate entries in AddrModesMap for loads and stores.
17736   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17737     FlagSet |= PPC::MOF_ZExt;
17738     FlagSet &= ~PPC::MOF_NoExt;
17739   }
17740 
17741   // If we don't have prefixed instructions, 34-bit constants should be
17742   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17743   bool IsNonP1034BitConst =
17744       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17745        FlagSet) == PPC::MOF_RPlusSImm34;
17746   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17747       IsNonP1034BitConst)
17748     FlagSet |= PPC::MOF_NotAddNorCst;
17749 
17750   return FlagSet;
17751 }
17752 
17753 /// SelectForceXFormMode - Given the specified address, force it to be
17754 /// represented as an indexed [r+r] operation (an XForm instruction).
17755 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17756                                                       SDValue &Base,
17757                                                       SelectionDAG &DAG) const {
17758 
17759   PPC::AddrMode Mode = PPC::AM_XForm;
17760   int16_t ForceXFormImm = 0;
17761   if (provablyDisjointOr(DAG, N) &&
17762       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17763     Disp = N.getOperand(0);
17764     Base = N.getOperand(1);
17765     return Mode;
17766   }
17767 
17768   // If the address is the result of an add, we will utilize the fact that the
17769   // address calculation includes an implicit add.  However, we can reduce
17770   // register pressure if we do not materialize a constant just for use as the
17771   // index register.  We only get rid of the add if it is not an add of a
17772   // value and a 16-bit signed constant and both have a single use.
17773   if (N.getOpcode() == ISD::ADD &&
17774       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17775        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17776     Disp = N.getOperand(0);
17777     Base = N.getOperand(1);
17778     return Mode;
17779   }
17780 
17781   // Otherwise, use R0 as the base register.
17782   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17783                          N.getValueType());
17784   Base = N;
17785 
17786   return Mode;
17787 }
17788 
17789 bool PPCTargetLowering::splitValueIntoRegisterParts(
17790     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
17791     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
17792   EVT ValVT = Val.getValueType();
17793   // If we are splitting a scalar integer into f64 parts (i.e. so they
17794   // can be placed into VFRC registers), we need to zero extend and
17795   // bitcast the values. This will ensure the value is placed into a
17796   // VSR using direct moves or stack operations as needed.
17797   if (PartVT == MVT::f64 &&
17798       (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
17799     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
17800     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
17801     Parts[0] = Val;
17802     return true;
17803   }
17804   return false;
17805 }
17806 
17807 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
17808                                           SelectionDAG &DAG) const {
17809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17810   TargetLowering::CallLoweringInfo CLI(DAG);
17811   EVT RetVT = Op.getValueType();
17812   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
17813   SDValue Callee =
17814       DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
17815   bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
17816   TargetLowering::ArgListTy Args;
17817   TargetLowering::ArgListEntry Entry;
17818   for (const SDValue &N : Op->op_values()) {
17819     EVT ArgVT = N.getValueType();
17820     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17821     Entry.Node = N;
17822     Entry.Ty = ArgTy;
17823     Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
17824     Entry.IsZExt = !Entry.IsSExt;
17825     Args.push_back(Entry);
17826   }
17827 
17828   SDValue InChain = DAG.getEntryNode();
17829   SDValue TCChain = InChain;
17830   const Function &F = DAG.getMachineFunction().getFunction();
17831   bool isTailCall =
17832       TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
17833       (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
17834   if (isTailCall)
17835     InChain = TCChain;
17836   CLI.setDebugLoc(SDLoc(Op))
17837       .setChain(InChain)
17838       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
17839       .setTailCall(isTailCall)
17840       .setSExtResult(SignExtend)
17841       .setZExtResult(!SignExtend)
17842       .setIsPostTypeLegalization(true);
17843   return TLI.LowerCallTo(CLI).first;
17844 }
17845 
17846 SDValue PPCTargetLowering::lowerLibCallBasedOnType(
17847     const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
17848     SelectionDAG &DAG) const {
17849   if (Op.getValueType() == MVT::f32)
17850     return lowerToLibCall(LibCallFloatName, Op, DAG);
17851 
17852   if (Op.getValueType() == MVT::f64)
17853     return lowerToLibCall(LibCallDoubleName, Op, DAG);
17854 
17855   return SDValue();
17856 }
17857 
17858 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
17859   SDNodeFlags Flags = Op.getNode()->getFlags();
17860   return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
17861          Flags.hasNoNaNs() && Flags.hasNoInfs();
17862 }
17863 
17864 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
17865   return Op.getNode()->getFlags().hasApproximateFuncs();
17866 }
17867 
17868 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
17869                                             const char *LibCallFloatName,
17870                                             const char *LibCallDoubleNameFinite,
17871                                             const char *LibCallFloatNameFinite,
17872                                             SDValue Op,
17873                                             SelectionDAG &DAG) const {
17874   if (!isLowringToMASSSafe(Op))
17875     return SDValue();
17876 
17877   if (!isLowringToMASSFiniteSafe(Op))
17878     return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
17879                                    DAG);
17880 
17881   return lowerLibCallBasedOnType(LibCallFloatNameFinite,
17882                                  LibCallDoubleNameFinite, Op, DAG);
17883 }
17884 
17885 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
17886   return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
17887                           "__xl_powf_finite", Op, DAG);
17888 }
17889 
17890 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
17891   return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
17892                           "__xl_sinf_finite", Op, DAG);
17893 }
17894 
17895 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
17896   return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
17897                           "__xl_cosf_finite", Op, DAG);
17898 }
17899 
17900 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
17901   return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
17902                           "__xl_logf_finite", Op, DAG);
17903 }
17904 
17905 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
17906   return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
17907                           "__xl_log10f_finite", Op, DAG);
17908 }
17909 
17910 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
17911   return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
17912                           "__xl_expf_finite", Op, DAG);
17913 }
17914 
17915 // If we happen to match to an aligned D-Form, check if the Frame Index is
17916 // adequately aligned. If it is not, reset the mode to match to X-Form.
17917 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17918                                    PPC::AddrMode &Mode) {
17919   if (!isa<FrameIndexSDNode>(N))
17920     return;
17921   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17922       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17923     Mode = PPC::AM_XForm;
17924 }
17925 
17926 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17927 /// compute the address flags of the node, get the optimal address mode based
17928 /// on the flags, and set the Base and Disp based on the address mode.
17929 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17930                                                        SDValue N, SDValue &Disp,
17931                                                        SDValue &Base,
17932                                                        SelectionDAG &DAG,
17933                                                        MaybeAlign Align) const {
17934   SDLoc DL(Parent);
17935 
17936   // Compute the address flags.
17937   unsigned Flags = computeMOFlags(Parent, N, DAG);
17938 
17939   // Get the optimal address mode based on the Flags.
17940   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17941 
17942   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17943   // Select an X-Form load if it is not.
17944   setXFormForUnalignedFI(N, Flags, Mode);
17945 
17946   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17947   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17948     assert(Subtarget.isUsingPCRelativeCalls() &&
17949            "Must be using PC-Relative calls when a valid PC-Relative node is "
17950            "present!");
17951     Mode = PPC::AM_PCRel;
17952   }
17953 
17954   // Set Base and Disp accordingly depending on the address mode.
17955   switch (Mode) {
17956   case PPC::AM_DForm:
17957   case PPC::AM_DSForm:
17958   case PPC::AM_DQForm: {
17959     // This is a register plus a 16-bit immediate. The base will be the
17960     // register and the displacement will be the immediate unless it
17961     // isn't sufficiently aligned.
17962     if (Flags & PPC::MOF_RPlusSImm16) {
17963       SDValue Op0 = N.getOperand(0);
17964       SDValue Op1 = N.getOperand(1);
17965       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17966       if (!Align || isAligned(*Align, Imm)) {
17967         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17968         Base = Op0;
17969         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17970           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17971           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17972         }
17973         break;
17974       }
17975     }
17976     // This is a register plus the @lo relocation. The base is the register
17977     // and the displacement is the global address.
17978     else if (Flags & PPC::MOF_RPlusLo) {
17979       Disp = N.getOperand(1).getOperand(0); // The global address.
17980       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17981              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17982              Disp.getOpcode() == ISD::TargetConstantPool ||
17983              Disp.getOpcode() == ISD::TargetJumpTable);
17984       Base = N.getOperand(0);
17985       break;
17986     }
17987     // This is a constant address at most 32 bits. The base will be
17988     // zero or load-immediate-shifted and the displacement will be
17989     // the low 16 bits of the address.
17990     else if (Flags & PPC::MOF_AddrIsSImm32) {
17991       auto *CN = cast<ConstantSDNode>(N);
17992       EVT CNType = CN->getValueType(0);
17993       uint64_t CNImm = CN->getZExtValue();
17994       // If this address fits entirely in a 16-bit sext immediate field, codegen
17995       // this as "d, 0".
17996       int16_t Imm;
17997       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17998         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17999         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18000                                CNType);
18001         break;
18002       }
18003       // Handle 32-bit sext immediate with LIS + Addr mode.
18004       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
18005           (!Align || isAligned(*Align, CNImm))) {
18006         int32_t Addr = (int32_t)CNImm;
18007         // Otherwise, break this down into LIS + Disp.
18008         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
18009         Base =
18010             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
18011         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
18012         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
18013         break;
18014       }
18015     }
18016     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
18017     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
18018     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
18019       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18020       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
18021     } else
18022       Base = N;
18023     break;
18024   }
18025   case PPC::AM_PrefixDForm: {
18026     int64_t Imm34 = 0;
18027     unsigned Opcode = N.getOpcode();
18028     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
18029         (isIntS34Immediate(N.getOperand(1), Imm34))) {
18030       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
18031       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18032       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
18033         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
18034       else
18035         Base = N.getOperand(0);
18036     } else if (isIntS34Immediate(N, Imm34)) {
18037       // The address is a 34-bit signed immediate.
18038       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18039       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
18040     }
18041     break;
18042   }
18043   case PPC::AM_PCRel: {
18044     // When selecting PC-Relative instructions, "Base" is not utilized as
18045     // we select the address as [PC+imm].
18046     Disp = N;
18047     break;
18048   }
18049   case PPC::AM_None:
18050     break;
18051   default: { // By default, X-Form is always available to be selected.
18052     // When a frame index is not aligned, we also match by XForm.
18053     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
18054     Base = FI ? N : N.getOperand(1);
18055     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18056                                 N.getValueType())
18057               : N.getOperand(0);
18058     break;
18059   }
18060   }
18061   return Mode;
18062 }
18063 
18064 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
18065                                                  bool Return,
18066                                                  bool IsVarArg) const {
18067   switch (CC) {
18068   case CallingConv::Cold:
18069     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
18070   default:
18071     return CC_PPC64_ELF_FIS;
18072   }
18073 }
18074 
18075 bool PPCTargetLowering::shouldInlineQuadwordAtomics() const {
18076   // TODO: 16-byte atomic type support for AIX is in progress; we should be able
18077   // to inline 16-byte atomic ops on AIX too in the future.
18078   return Subtarget.isPPC64() &&
18079          (EnableQuadwordAtomics || !Subtarget.getTargetTriple().isOSAIX()) &&
18080          Subtarget.hasQuadwordAtomics();
18081 }
18082 
18083 TargetLowering::AtomicExpansionKind
18084 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18085   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18086   if (shouldInlineQuadwordAtomics() && Size == 128)
18087     return AtomicExpansionKind::MaskedIntrinsic;
18088   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
18089 }
18090 
18091 TargetLowering::AtomicExpansionKind
18092 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18093   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
18094   if (shouldInlineQuadwordAtomics() && Size == 128)
18095     return AtomicExpansionKind::MaskedIntrinsic;
18096   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
18097 }
18098 
18099 static Intrinsic::ID
18100 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
18101   switch (BinOp) {
18102   default:
18103     llvm_unreachable("Unexpected AtomicRMW BinOp");
18104   case AtomicRMWInst::Xchg:
18105     return Intrinsic::ppc_atomicrmw_xchg_i128;
18106   case AtomicRMWInst::Add:
18107     return Intrinsic::ppc_atomicrmw_add_i128;
18108   case AtomicRMWInst::Sub:
18109     return Intrinsic::ppc_atomicrmw_sub_i128;
18110   case AtomicRMWInst::And:
18111     return Intrinsic::ppc_atomicrmw_and_i128;
18112   case AtomicRMWInst::Or:
18113     return Intrinsic::ppc_atomicrmw_or_i128;
18114   case AtomicRMWInst::Xor:
18115     return Intrinsic::ppc_atomicrmw_xor_i128;
18116   case AtomicRMWInst::Nand:
18117     return Intrinsic::ppc_atomicrmw_nand_i128;
18118   }
18119 }
18120 
18121 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
18122     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
18123     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
18124   assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
18125   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18126   Type *ValTy = Incr->getType();
18127   assert(ValTy->getPrimitiveSizeInBits() == 128);
18128   Function *RMW = Intrinsic::getDeclaration(
18129       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
18130   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18131   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
18132   Value *IncrHi =
18133       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
18134   Value *Addr =
18135       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18136   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
18137   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18138   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18139   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18140   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18141   return Builder.CreateOr(
18142       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18143 }
18144 
18145 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
18146     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
18147     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
18148   assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
18149   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18150   Type *ValTy = CmpVal->getType();
18151   assert(ValTy->getPrimitiveSizeInBits() == 128);
18152   Function *IntCmpXchg =
18153       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
18154   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18155   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
18156   Value *CmpHi =
18157       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
18158   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
18159   Value *NewHi =
18160       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
18161   Value *Addr =
18162       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18163   emitLeadingFence(Builder, CI, Ord);
18164   Value *LoHi =
18165       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
18166   emitTrailingFence(Builder, CI, Ord);
18167   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18168   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18169   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18170   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18171   return Builder.CreateOr(
18172       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18173 }
18174