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(false), 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 
631   // To handle counter-based loop conditions.
632   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
633 
634   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
635   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
636   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
637   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
638 
639   // Comparisons that require checking two conditions.
640   if (Subtarget.hasSPE()) {
641     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
642     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
643     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
644     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
645   }
646   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
647   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
648   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
649   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
650   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
651   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
652   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
653   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
654   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
655   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
656   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
657   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
658 
659   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
660   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
661 
662   if (Subtarget.has64BitSupport()) {
663     // They also have instructions for converting between i64 and fp.
664     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
665     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
666     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
667     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
668     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
669     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
670     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
671     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
672     // This is just the low 32 bits of a (signed) fp->i64 conversion.
673     // We cannot do this with Promote because i64 is not a legal type.
674     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
675     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
676 
677     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
678       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
679       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
680     }
681   } else {
682     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
683     if (Subtarget.hasSPE()) {
684       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
685       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
686     } else {
687       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
688       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
689     }
690   }
691 
692   // With the instructions enabled under FPCVT, we can do everything.
693   if (Subtarget.hasFPCVT()) {
694     if (Subtarget.has64BitSupport()) {
695       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
696       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
697       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
698       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
699       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
700       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
701       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
702       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
703     }
704 
705     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
706     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
707     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
708     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
709     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
710     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
711     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
712     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
713   }
714 
715   if (Subtarget.use64BitRegs()) {
716     // 64-bit PowerPC implementations can support i64 types directly
717     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
718     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
719     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
720     // 64-bit PowerPC wants to expand i128 shifts itself.
721     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
722     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
723     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
724   } else {
725     // 32-bit PowerPC wants to expand i64 shifts itself.
726     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
727     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
728     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
729   }
730 
731   // PowerPC has better expansions for funnel shifts than the generic
732   // TargetLowering::expandFunnelShift.
733   if (Subtarget.has64BitSupport()) {
734     setOperationAction(ISD::FSHL, MVT::i64, Custom);
735     setOperationAction(ISD::FSHR, MVT::i64, Custom);
736   }
737   setOperationAction(ISD::FSHL, MVT::i32, Custom);
738   setOperationAction(ISD::FSHR, MVT::i32, Custom);
739 
740   if (Subtarget.hasVSX()) {
741     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
742     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
743     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
744     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
745   }
746 
747   if (Subtarget.hasAltivec()) {
748     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
749       setOperationAction(ISD::SADDSAT, VT, Legal);
750       setOperationAction(ISD::SSUBSAT, VT, Legal);
751       setOperationAction(ISD::UADDSAT, VT, Legal);
752       setOperationAction(ISD::USUBSAT, VT, Legal);
753     }
754     // First set operation action for all vector types to expand. Then we
755     // will selectively turn on ones that can be effectively codegen'd.
756     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
757       // add/sub are legal for all supported vector VT's.
758       setOperationAction(ISD::ADD, VT, Legal);
759       setOperationAction(ISD::SUB, VT, Legal);
760 
761       // For v2i64, these are only valid with P8Vector. This is corrected after
762       // the loop.
763       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
764         setOperationAction(ISD::SMAX, VT, Legal);
765         setOperationAction(ISD::SMIN, VT, Legal);
766         setOperationAction(ISD::UMAX, VT, Legal);
767         setOperationAction(ISD::UMIN, VT, Legal);
768       }
769       else {
770         setOperationAction(ISD::SMAX, VT, Expand);
771         setOperationAction(ISD::SMIN, VT, Expand);
772         setOperationAction(ISD::UMAX, VT, Expand);
773         setOperationAction(ISD::UMIN, VT, Expand);
774       }
775 
776       if (Subtarget.hasVSX()) {
777         setOperationAction(ISD::FMAXNUM, VT, Legal);
778         setOperationAction(ISD::FMINNUM, VT, Legal);
779       }
780 
781       // Vector instructions introduced in P8
782       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
783         setOperationAction(ISD::CTPOP, VT, Legal);
784         setOperationAction(ISD::CTLZ, VT, Legal);
785       }
786       else {
787         setOperationAction(ISD::CTPOP, VT, Expand);
788         setOperationAction(ISD::CTLZ, VT, Expand);
789       }
790 
791       // Vector instructions introduced in P9
792       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
793         setOperationAction(ISD::CTTZ, VT, Legal);
794       else
795         setOperationAction(ISD::CTTZ, VT, Expand);
796 
797       // We promote all shuffles to v16i8.
798       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
799       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
800 
801       // We promote all non-typed operations to v4i32.
802       setOperationAction(ISD::AND   , VT, Promote);
803       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
804       setOperationAction(ISD::OR    , VT, Promote);
805       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
806       setOperationAction(ISD::XOR   , VT, Promote);
807       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
808       setOperationAction(ISD::LOAD  , VT, Promote);
809       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
810       setOperationAction(ISD::SELECT, VT, Promote);
811       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
812       setOperationAction(ISD::VSELECT, VT, Legal);
813       setOperationAction(ISD::SELECT_CC, VT, Promote);
814       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
815       setOperationAction(ISD::STORE, VT, Promote);
816       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
817 
818       // No other operations are legal.
819       setOperationAction(ISD::MUL , VT, Expand);
820       setOperationAction(ISD::SDIV, VT, Expand);
821       setOperationAction(ISD::SREM, VT, Expand);
822       setOperationAction(ISD::UDIV, VT, Expand);
823       setOperationAction(ISD::UREM, VT, Expand);
824       setOperationAction(ISD::FDIV, VT, Expand);
825       setOperationAction(ISD::FREM, VT, Expand);
826       setOperationAction(ISD::FNEG, VT, Expand);
827       setOperationAction(ISD::FSQRT, VT, Expand);
828       setOperationAction(ISD::FLOG, VT, Expand);
829       setOperationAction(ISD::FLOG10, VT, Expand);
830       setOperationAction(ISD::FLOG2, VT, Expand);
831       setOperationAction(ISD::FEXP, VT, Expand);
832       setOperationAction(ISD::FEXP2, VT, Expand);
833       setOperationAction(ISD::FSIN, VT, Expand);
834       setOperationAction(ISD::FCOS, VT, Expand);
835       setOperationAction(ISD::FABS, VT, Expand);
836       setOperationAction(ISD::FFLOOR, VT, Expand);
837       setOperationAction(ISD::FCEIL,  VT, Expand);
838       setOperationAction(ISD::FTRUNC, VT, Expand);
839       setOperationAction(ISD::FRINT,  VT, Expand);
840       setOperationAction(ISD::FNEARBYINT, VT, Expand);
841       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
842       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
843       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
844       setOperationAction(ISD::MULHU, VT, Expand);
845       setOperationAction(ISD::MULHS, VT, Expand);
846       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
847       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
848       setOperationAction(ISD::UDIVREM, VT, Expand);
849       setOperationAction(ISD::SDIVREM, VT, Expand);
850       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
851       setOperationAction(ISD::FPOW, VT, Expand);
852       setOperationAction(ISD::BSWAP, VT, Expand);
853       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
854       setOperationAction(ISD::ROTL, VT, Expand);
855       setOperationAction(ISD::ROTR, VT, Expand);
856 
857       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
858         setTruncStoreAction(VT, InnerVT, Expand);
859         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
860         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
861         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
862       }
863     }
864     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
865     if (!Subtarget.hasP8Vector()) {
866       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
867       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
868       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
869       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
870     }
871 
872     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
873     // with merges, splats, etc.
874     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
875 
876     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
877     // are cheap, so handle them before they get expanded to scalar.
878     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
879     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
880     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
881     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
882     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
883 
884     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
885     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
886     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
887     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
888     setOperationAction(ISD::SELECT, MVT::v4i32,
889                        Subtarget.useCRBits() ? Legal : Expand);
890     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
891     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
892     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
893     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
894     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
895     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
896     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
897     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
898     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
899     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
900     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
901     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
902     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
903 
904     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
905     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
906     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
907     if (Subtarget.hasAltivec())
908       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
909         setOperationAction(ISD::ROTL, VT, Legal);
910     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
911     if (Subtarget.hasP8Altivec())
912       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
913 
914     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
915     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
916     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
917     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
918 
919     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
920     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
921 
922     if (Subtarget.hasVSX()) {
923       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
924       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
925       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
926     }
927 
928     if (Subtarget.hasP8Altivec())
929       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
930     else
931       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
932 
933     if (Subtarget.isISA3_1()) {
934       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
935       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
936       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
937       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
938       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
939       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
940       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
941       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
942       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
943       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
944       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
945       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
946       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
947       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
948       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
949       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
950       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
951       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
952     }
953 
954     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
955     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
956 
957     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
958     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
959 
960     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
961     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
962     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
963     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
964 
965     // Altivec does not contain unordered floating-point compare instructions
966     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
967     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
968     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
969     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
970 
971     if (Subtarget.hasVSX()) {
972       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
973       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
974       if (Subtarget.hasP8Vector()) {
975         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
976         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
977       }
978       if (Subtarget.hasDirectMove() && isPPC64) {
979         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
980         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
981         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
982         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
983         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
984         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
985         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
986         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
987       }
988       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
989 
990       // The nearbyint variants are not allowed to raise the inexact exception
991       // so we can only code-gen them with unsafe math.
992       if (TM.Options.UnsafeFPMath) {
993         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
994         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
995       }
996 
997       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
998       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
999       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1000       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1001       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1002       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1003       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1004       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1005 
1006       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1007       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1008       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1009       setOperationAction(ISD::FROUND, MVT::f32, Legal);
1010       setOperationAction(ISD::FRINT, MVT::f32, Legal);
1011 
1012       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1013       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1014 
1015       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1016       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1017 
1018       // Share the Altivec comparison restrictions.
1019       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1020       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1021       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
1022       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1023 
1024       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1025       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1026 
1027       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1028 
1029       if (Subtarget.hasP8Vector())
1030         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1031 
1032       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1033 
1034       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1035       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1036       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1037 
1038       if (Subtarget.hasP8Altivec()) {
1039         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1040         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1041         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1042 
1043         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1044         // SRL, but not for SRA because of the instructions available:
1045         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1046         // doing
1047         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1048         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1049         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1050 
1051         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1052       }
1053       else {
1054         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1055         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1056         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1057 
1058         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1059 
1060         // VSX v2i64 only supports non-arithmetic operations.
1061         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1062         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1063       }
1064 
1065       if (Subtarget.isISA3_1())
1066         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1067       else
1068         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1069 
1070       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1071       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1072       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1073       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1074 
1075       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1076 
1077       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1078       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1079       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1080       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1081       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1082       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1083       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1084       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1085 
1086       // Custom handling for partial vectors of integers converted to
1087       // floating point. We already have optimal handling for v2i32 through
1088       // the DAG combine, so those aren't necessary.
1089       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1090       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1091       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1092       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1093       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1094       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1095       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1096       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1097       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1098       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1099       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1100       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1101       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1102       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1103       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1104       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1105 
1106       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1107       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1108       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1109       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1110       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1111       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1112 
1113       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1114       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1115 
1116       // Handle constrained floating-point operations of vector.
1117       // The predictor is `hasVSX` because altivec instruction has
1118       // no exception but VSX vector instruction has.
1119       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1120       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1121       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1122       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1123       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1124       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1125       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1126       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1127       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1128       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1129       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1130       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1131       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1132 
1133       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1134       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1135       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1136       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1137       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1138       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1139       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1140       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1141       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1142       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1143       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1144       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1145       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1146 
1147       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1148       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1149 
1150       for (MVT FPT : MVT::fp_valuetypes())
1151         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1152 
1153       // Expand the SELECT to SELECT_CC
1154       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1155 
1156       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1157       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1158 
1159       // No implementation for these ops for PowerPC.
1160       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1161       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1162       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1163       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1164       setOperationAction(ISD::FREM, MVT::f128, Expand);
1165     }
1166 
1167     if (Subtarget.hasP8Altivec()) {
1168       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1169       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1170     }
1171 
1172     if (Subtarget.hasP9Vector()) {
1173       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1174       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1175 
1176       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1177       // SRL, but not for SRA because of the instructions available:
1178       // VS{RL} and VS{RL}O.
1179       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1180       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1181       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1182 
1183       setOperationAction(ISD::FADD, MVT::f128, Legal);
1184       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1185       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1186       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1187       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1188 
1189       setOperationAction(ISD::FMA, MVT::f128, Legal);
1190       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1191       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1192       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1193       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1194       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1195       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1196 
1197       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1198       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1199       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1200       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1201       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1202       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1203 
1204       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1205       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1206       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1207 
1208       // Handle constrained floating-point operations of fp128
1209       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1210       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1211       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1212       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1213       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1214       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1215       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1216       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1217       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1218       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1219       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1220       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1221       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1222       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1223       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1224       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1225       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1226       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1227       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1228       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1229     } else if (Subtarget.hasVSX()) {
1230       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1231       setOperationAction(ISD::STORE, MVT::f128, Promote);
1232 
1233       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1234       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1235 
1236       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1237       // fp_to_uint and int_to_fp.
1238       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1239       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1240 
1241       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1242       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1243       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1244       setOperationAction(ISD::FABS, MVT::f128, Expand);
1245       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1246       setOperationAction(ISD::FMA, MVT::f128, Expand);
1247       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1248 
1249       // Expand the fp_extend if the target type is fp128.
1250       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1251       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1252 
1253       // Expand the fp_round if the source type is fp128.
1254       for (MVT VT : {MVT::f32, MVT::f64}) {
1255         setOperationAction(ISD::FP_ROUND, VT, Custom);
1256         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1257       }
1258 
1259       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1260       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1261       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1262       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1263 
1264       // Lower following f128 select_cc pattern:
1265       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1266       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1267 
1268       // We need to handle f128 SELECT_CC with integer result type.
1269       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1270       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1271     }
1272 
1273     if (Subtarget.hasP9Altivec()) {
1274       if (Subtarget.isISA3_1()) {
1275         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
1276         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
1277         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
1278         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
1279       } else {
1280         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1281         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1282       }
1283       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1284       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1285       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1286       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1287       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1288       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1289       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1290     }
1291 
1292     if (Subtarget.hasP10Vector()) {
1293       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1294     }
1295   }
1296 
1297   if (Subtarget.pairedVectorMemops()) {
1298     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1299     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1300     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1301   }
1302   if (Subtarget.hasMMA()) {
1303     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1304     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1305     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1306     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1307   }
1308 
1309   if (Subtarget.has64BitSupport())
1310     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1311 
1312   if (Subtarget.isISA3_1())
1313     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1314 
1315   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1316 
1317   if (!isPPC64) {
1318     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1319     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1320   }
1321 
1322   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1323     setMaxAtomicSizeInBitsSupported(128);
1324     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1325     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1326     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1327   }
1328 
1329   setBooleanContents(ZeroOrOneBooleanContent);
1330 
1331   if (Subtarget.hasAltivec()) {
1332     // Altivec instructions set fields to all zeros or all ones.
1333     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1334   }
1335 
1336   if (!isPPC64) {
1337     // These libcalls are not available in 32-bit.
1338     setLibcallName(RTLIB::SHL_I128, nullptr);
1339     setLibcallName(RTLIB::SRL_I128, nullptr);
1340     setLibcallName(RTLIB::SRA_I128, nullptr);
1341     setLibcallName(RTLIB::MULO_I64, nullptr);
1342   }
1343 
1344   if (!isPPC64)
1345     setMaxAtomicSizeInBitsSupported(32);
1346 
1347   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1348 
1349   // We have target-specific dag combine patterns for the following nodes:
1350   setTargetDAGCombine(ISD::ADD);
1351   setTargetDAGCombine(ISD::SHL);
1352   setTargetDAGCombine(ISD::SRA);
1353   setTargetDAGCombine(ISD::SRL);
1354   setTargetDAGCombine(ISD::MUL);
1355   setTargetDAGCombine(ISD::FMA);
1356   setTargetDAGCombine(ISD::SINT_TO_FP);
1357   setTargetDAGCombine(ISD::BUILD_VECTOR);
1358   if (Subtarget.hasFPCVT())
1359     setTargetDAGCombine(ISD::UINT_TO_FP);
1360   setTargetDAGCombine(ISD::LOAD);
1361   setTargetDAGCombine(ISD::STORE);
1362   setTargetDAGCombine(ISD::BR_CC);
1363   if (Subtarget.useCRBits())
1364     setTargetDAGCombine(ISD::BRCOND);
1365   setTargetDAGCombine(ISD::BSWAP);
1366   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1367   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1368   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1369 
1370   setTargetDAGCombine(ISD::SIGN_EXTEND);
1371   setTargetDAGCombine(ISD::ZERO_EXTEND);
1372   setTargetDAGCombine(ISD::ANY_EXTEND);
1373 
1374   setTargetDAGCombine(ISD::TRUNCATE);
1375   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1376 
1377 
1378   if (Subtarget.useCRBits()) {
1379     setTargetDAGCombine(ISD::TRUNCATE);
1380     setTargetDAGCombine(ISD::SETCC);
1381     setTargetDAGCombine(ISD::SELECT_CC);
1382   }
1383 
1384   if (Subtarget.hasP9Altivec()) {
1385     setTargetDAGCombine(ISD::ABS);
1386     setTargetDAGCombine(ISD::VSELECT);
1387   }
1388 
1389   setLibcallName(RTLIB::LOG_F128, "logf128");
1390   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1391   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1392   setLibcallName(RTLIB::EXP_F128, "expf128");
1393   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1394   setLibcallName(RTLIB::SIN_F128, "sinf128");
1395   setLibcallName(RTLIB::COS_F128, "cosf128");
1396   setLibcallName(RTLIB::POW_F128, "powf128");
1397   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1398   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1399   setLibcallName(RTLIB::REM_F128, "fmodf128");
1400   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1401   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1402   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1403   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1404   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1405   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1406   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1407   setLibcallName(RTLIB::RINT_F128, "rintf128");
1408   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1409   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1410   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1411   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1412 
1413   // With 32 condition bits, we don't need to sink (and duplicate) compares
1414   // aggressively in CodeGenPrep.
1415   if (Subtarget.useCRBits()) {
1416     setHasMultipleConditionRegisters();
1417     setJumpIsExpensive();
1418   }
1419 
1420   setMinFunctionAlignment(Align(4));
1421 
1422   switch (Subtarget.getCPUDirective()) {
1423   default: break;
1424   case PPC::DIR_970:
1425   case PPC::DIR_A2:
1426   case PPC::DIR_E500:
1427   case PPC::DIR_E500mc:
1428   case PPC::DIR_E5500:
1429   case PPC::DIR_PWR4:
1430   case PPC::DIR_PWR5:
1431   case PPC::DIR_PWR5X:
1432   case PPC::DIR_PWR6:
1433   case PPC::DIR_PWR6X:
1434   case PPC::DIR_PWR7:
1435   case PPC::DIR_PWR8:
1436   case PPC::DIR_PWR9:
1437   case PPC::DIR_PWR10:
1438   case PPC::DIR_PWR_FUTURE:
1439     setPrefLoopAlignment(Align(16));
1440     setPrefFunctionAlignment(Align(16));
1441     break;
1442   }
1443 
1444   if (Subtarget.enableMachineScheduler())
1445     setSchedulingPreference(Sched::Source);
1446   else
1447     setSchedulingPreference(Sched::Hybrid);
1448 
1449   computeRegisterProperties(STI.getRegisterInfo());
1450 
1451   // The Freescale cores do better with aggressive inlining of memcpy and
1452   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1453   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1454       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1455     MaxStoresPerMemset = 32;
1456     MaxStoresPerMemsetOptSize = 16;
1457     MaxStoresPerMemcpy = 32;
1458     MaxStoresPerMemcpyOptSize = 8;
1459     MaxStoresPerMemmove = 32;
1460     MaxStoresPerMemmoveOptSize = 8;
1461   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1462     // The A2 also benefits from (very) aggressive inlining of memcpy and
1463     // friends. The overhead of a the function call, even when warm, can be
1464     // over one hundred cycles.
1465     MaxStoresPerMemset = 128;
1466     MaxStoresPerMemcpy = 128;
1467     MaxStoresPerMemmove = 128;
1468     MaxLoadsPerMemcmp = 128;
1469   } else {
1470     MaxLoadsPerMemcmp = 8;
1471     MaxLoadsPerMemcmpOptSize = 4;
1472   }
1473 
1474   IsStrictFPEnabled = true;
1475 
1476   // Let the subtarget (CPU) decide if a predictable select is more expensive
1477   // than the corresponding branch. This information is used in CGP to decide
1478   // when to convert selects into branches.
1479   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1480 }
1481 
1482 // *********************************** NOTE ************************************
1483 // For selecting load and store instructions, the addressing modes are defined
1484 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1485 // patterns to match the load the store instructions.
1486 //
1487 // The TD definitions for the addressing modes correspond to their respective
1488 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1489 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1490 // address mode flags of a particular node. Afterwards, the computed address
1491 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1492 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1493 // accordingly, based on the preferred addressing mode.
1494 //
1495 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1496 // MemOpFlags contains all the possible flags that can be used to compute the
1497 // optimal addressing mode for load and store instructions.
1498 // AddrMode contains all the possible load and store addressing modes available
1499 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1500 //
1501 // When adding new load and store instructions, it is possible that new address
1502 // flags may need to be added into MemOpFlags, and a new addressing mode will
1503 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1504 // of the minimal and main distinguishing address flags for the new load/store
1505 // instructions) will need to be added into initializeAddrModeMap() below.
1506 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1507 // need to be updated to account for selecting the optimal addressing mode.
1508 // *****************************************************************************
1509 /// Initialize the map that relates the different addressing modes of the load
1510 /// and store instructions to a set of flags. This ensures the load/store
1511 /// instruction is correctly matched during instruction selection.
1512 void PPCTargetLowering::initializeAddrModeMap() {
1513   AddrModesMap[PPC::AM_DForm] = {
1514       // LWZ, STW
1515       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1516       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1517       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1518       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1519       // LBZ, LHZ, STB, STH
1520       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1521       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1522       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1523       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1524       // LHA
1525       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1526       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1527       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1528       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1529       // LFS, LFD, STFS, STFD
1530       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1531       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1532       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1533       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1534   };
1535   AddrModesMap[PPC::AM_DSForm] = {
1536       // LWA
1537       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1538       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1539       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1540       // LD, STD
1541       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1542       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1543       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1544       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1545       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1546       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1547       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1548   };
1549   AddrModesMap[PPC::AM_DQForm] = {
1550       // LXV, STXV
1551       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1552       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1553       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1554   };
1555   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1556                                        PPC::MOF_SubtargetP10};
1557   // TODO: Add mapping for quadword load/store.
1558 }
1559 
1560 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1561 /// the desired ByVal argument alignment.
1562 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1563   if (MaxAlign == MaxMaxAlign)
1564     return;
1565   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1566     if (MaxMaxAlign >= 32 &&
1567         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1568       MaxAlign = Align(32);
1569     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1570              MaxAlign < 16)
1571       MaxAlign = Align(16);
1572   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1573     Align EltAlign;
1574     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1575     if (EltAlign > MaxAlign)
1576       MaxAlign = EltAlign;
1577   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1578     for (auto *EltTy : STy->elements()) {
1579       Align EltAlign;
1580       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1581       if (EltAlign > MaxAlign)
1582         MaxAlign = EltAlign;
1583       if (MaxAlign == MaxMaxAlign)
1584         break;
1585     }
1586   }
1587 }
1588 
1589 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1590 /// function arguments in the caller parameter area.
1591 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1592                                                   const DataLayout &DL) const {
1593   // 16byte and wider vectors are passed on 16byte boundary.
1594   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1595   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1596   if (Subtarget.hasAltivec())
1597     getMaxByValAlign(Ty, Alignment, Align(16));
1598   return Alignment.value();
1599 }
1600 
1601 bool PPCTargetLowering::useSoftFloat() const {
1602   return Subtarget.useSoftFloat();
1603 }
1604 
1605 bool PPCTargetLowering::hasSPE() const {
1606   return Subtarget.hasSPE();
1607 }
1608 
1609 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1610   return VT.isScalarInteger();
1611 }
1612 
1613 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1614   switch ((PPCISD::NodeType)Opcode) {
1615   case PPCISD::FIRST_NUMBER:    break;
1616   case PPCISD::FSEL:            return "PPCISD::FSEL";
1617   case PPCISD::XSMAXC:          return "PPCISD::XSMAXC";
1618   case PPCISD::XSMINC:          return "PPCISD::XSMINC";
1619   case PPCISD::FCFID:           return "PPCISD::FCFID";
1620   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1621   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1622   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1623   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1624   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1625   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1626   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1627   case PPCISD::FP_TO_UINT_IN_VSR:
1628                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1629   case PPCISD::FP_TO_SINT_IN_VSR:
1630                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1631   case PPCISD::FRE:             return "PPCISD::FRE";
1632   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1633   case PPCISD::FTSQRT:
1634     return "PPCISD::FTSQRT";
1635   case PPCISD::FSQRT:
1636     return "PPCISD::FSQRT";
1637   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1638   case PPCISD::VPERM:           return "PPCISD::VPERM";
1639   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1640   case PPCISD::XXSPLTI_SP_TO_DP:
1641     return "PPCISD::XXSPLTI_SP_TO_DP";
1642   case PPCISD::XXSPLTI32DX:
1643     return "PPCISD::XXSPLTI32DX";
1644   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1645   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1646   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1647   case PPCISD::CMPB:            return "PPCISD::CMPB";
1648   case PPCISD::Hi:              return "PPCISD::Hi";
1649   case PPCISD::Lo:              return "PPCISD::Lo";
1650   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1651   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1652   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1653   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1654   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1655   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1656   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1657   case PPCISD::SRL:             return "PPCISD::SRL";
1658   case PPCISD::SRA:             return "PPCISD::SRA";
1659   case PPCISD::SHL:             return "PPCISD::SHL";
1660   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1661   case PPCISD::CALL:            return "PPCISD::CALL";
1662   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1663   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1664   case PPCISD::CALL_RM:
1665     return "PPCISD::CALL_RM";
1666   case PPCISD::CALL_NOP_RM:
1667     return "PPCISD::CALL_NOP_RM";
1668   case PPCISD::CALL_NOTOC_RM:
1669     return "PPCISD::CALL_NOTOC_RM";
1670   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1671   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1672   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1673   case PPCISD::BCTRL_RM:
1674     return "PPCISD::BCTRL_RM";
1675   case PPCISD::BCTRL_LOAD_TOC_RM:
1676     return "PPCISD::BCTRL_LOAD_TOC_RM";
1677   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1678   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1679   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1680   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1681   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1682   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1683   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1684   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1685   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1686   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1687   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1688     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1689   case PPCISD::ANDI_rec_1_EQ_BIT:
1690     return "PPCISD::ANDI_rec_1_EQ_BIT";
1691   case PPCISD::ANDI_rec_1_GT_BIT:
1692     return "PPCISD::ANDI_rec_1_GT_BIT";
1693   case PPCISD::VCMP:            return "PPCISD::VCMP";
1694   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1695   case PPCISD::LBRX:            return "PPCISD::LBRX";
1696   case PPCISD::STBRX:           return "PPCISD::STBRX";
1697   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1698   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1699   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1700   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1701   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1702   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1703   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1704   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1705   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1706   case PPCISD::ST_VSR_SCAL_INT:
1707                                 return "PPCISD::ST_VSR_SCAL_INT";
1708   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1709   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1710   case PPCISD::BDZ:             return "PPCISD::BDZ";
1711   case PPCISD::MFFS:            return "PPCISD::MFFS";
1712   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1713   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1714   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1715   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1716   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1717   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1718   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1719   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1720   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1721   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1722   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1723   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1724   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1725   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1726   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1727   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1728   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1729   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1730   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1731   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1732   case PPCISD::PADDI_DTPREL:
1733     return "PPCISD::PADDI_DTPREL";
1734   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1735   case PPCISD::SC:              return "PPCISD::SC";
1736   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1737   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1738   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1739   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1740   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1741   case PPCISD::VABSD:           return "PPCISD::VABSD";
1742   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1743   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1744   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1745   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1746   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1747   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1748   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1749   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1750     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1751   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1752     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1753   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1754   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1755   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1756   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1757   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1758   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1759   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1760   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1761   case PPCISD::STRICT_FADDRTZ:
1762     return "PPCISD::STRICT_FADDRTZ";
1763   case PPCISD::STRICT_FCTIDZ:
1764     return "PPCISD::STRICT_FCTIDZ";
1765   case PPCISD::STRICT_FCTIWZ:
1766     return "PPCISD::STRICT_FCTIWZ";
1767   case PPCISD::STRICT_FCTIDUZ:
1768     return "PPCISD::STRICT_FCTIDUZ";
1769   case PPCISD::STRICT_FCTIWUZ:
1770     return "PPCISD::STRICT_FCTIWUZ";
1771   case PPCISD::STRICT_FCFID:
1772     return "PPCISD::STRICT_FCFID";
1773   case PPCISD::STRICT_FCFIDU:
1774     return "PPCISD::STRICT_FCFIDU";
1775   case PPCISD::STRICT_FCFIDS:
1776     return "PPCISD::STRICT_FCFIDS";
1777   case PPCISD::STRICT_FCFIDUS:
1778     return "PPCISD::STRICT_FCFIDUS";
1779   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1780   }
1781   return nullptr;
1782 }
1783 
1784 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1785                                           EVT VT) const {
1786   if (!VT.isVector())
1787     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1788 
1789   return VT.changeVectorElementTypeToInteger();
1790 }
1791 
1792 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1793   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1794   return true;
1795 }
1796 
1797 //===----------------------------------------------------------------------===//
1798 // Node matching predicates, for use by the tblgen matching code.
1799 //===----------------------------------------------------------------------===//
1800 
1801 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1802 static bool isFloatingPointZero(SDValue Op) {
1803   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1804     return CFP->getValueAPF().isZero();
1805   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1806     // Maybe this has already been legalized into the constant pool?
1807     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1808       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1809         return CFP->getValueAPF().isZero();
1810   }
1811   return false;
1812 }
1813 
1814 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1815 /// true if Op is undef or if it matches the specified value.
1816 static bool isConstantOrUndef(int Op, int Val) {
1817   return Op < 0 || Op == Val;
1818 }
1819 
1820 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1821 /// VPKUHUM instruction.
1822 /// The ShuffleKind distinguishes between big-endian operations with
1823 /// two different inputs (0), either-endian operations with two identical
1824 /// inputs (1), and little-endian operations with two different inputs (2).
1825 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1826 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1827                                SelectionDAG &DAG) {
1828   bool IsLE = DAG.getDataLayout().isLittleEndian();
1829   if (ShuffleKind == 0) {
1830     if (IsLE)
1831       return false;
1832     for (unsigned i = 0; i != 16; ++i)
1833       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1834         return false;
1835   } else if (ShuffleKind == 2) {
1836     if (!IsLE)
1837       return false;
1838     for (unsigned i = 0; i != 16; ++i)
1839       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1840         return false;
1841   } else if (ShuffleKind == 1) {
1842     unsigned j = IsLE ? 0 : 1;
1843     for (unsigned i = 0; i != 8; ++i)
1844       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1845           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1846         return false;
1847   }
1848   return true;
1849 }
1850 
1851 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1852 /// VPKUWUM instruction.
1853 /// The ShuffleKind distinguishes between big-endian operations with
1854 /// two different inputs (0), either-endian operations with two identical
1855 /// inputs (1), and little-endian operations with two different inputs (2).
1856 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1857 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1858                                SelectionDAG &DAG) {
1859   bool IsLE = DAG.getDataLayout().isLittleEndian();
1860   if (ShuffleKind == 0) {
1861     if (IsLE)
1862       return false;
1863     for (unsigned i = 0; i != 16; i += 2)
1864       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1865           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1866         return false;
1867   } else if (ShuffleKind == 2) {
1868     if (!IsLE)
1869       return false;
1870     for (unsigned i = 0; i != 16; i += 2)
1871       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1872           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1873         return false;
1874   } else if (ShuffleKind == 1) {
1875     unsigned j = IsLE ? 0 : 2;
1876     for (unsigned i = 0; i != 8; i += 2)
1877       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1878           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1879           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1880           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1881         return false;
1882   }
1883   return true;
1884 }
1885 
1886 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1887 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1888 /// current subtarget.
1889 ///
1890 /// The ShuffleKind distinguishes between big-endian operations with
1891 /// two different inputs (0), either-endian operations with two identical
1892 /// inputs (1), and little-endian operations with two different inputs (2).
1893 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1894 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1895                                SelectionDAG &DAG) {
1896   const PPCSubtarget& Subtarget =
1897       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1898   if (!Subtarget.hasP8Vector())
1899     return false;
1900 
1901   bool IsLE = DAG.getDataLayout().isLittleEndian();
1902   if (ShuffleKind == 0) {
1903     if (IsLE)
1904       return false;
1905     for (unsigned i = 0; i != 16; i += 4)
1906       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1907           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1908           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1909           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1910         return false;
1911   } else if (ShuffleKind == 2) {
1912     if (!IsLE)
1913       return false;
1914     for (unsigned i = 0; i != 16; i += 4)
1915       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1916           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1917           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1918           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1919         return false;
1920   } else if (ShuffleKind == 1) {
1921     unsigned j = IsLE ? 0 : 4;
1922     for (unsigned i = 0; i != 8; i += 4)
1923       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1924           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1925           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1926           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1927           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1928           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1929           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1930           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1931         return false;
1932   }
1933   return true;
1934 }
1935 
1936 /// isVMerge - Common function, used to match vmrg* shuffles.
1937 ///
1938 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1939                      unsigned LHSStart, unsigned RHSStart) {
1940   if (N->getValueType(0) != MVT::v16i8)
1941     return false;
1942   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1943          "Unsupported merge size!");
1944 
1945   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1946     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1947       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1948                              LHSStart+j+i*UnitSize) ||
1949           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1950                              RHSStart+j+i*UnitSize))
1951         return false;
1952     }
1953   return true;
1954 }
1955 
1956 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1957 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1958 /// The ShuffleKind distinguishes between big-endian merges with two
1959 /// different inputs (0), either-endian merges with two identical inputs (1),
1960 /// and little-endian merges with two different inputs (2).  For the latter,
1961 /// the input operands are swapped (see PPCInstrAltivec.td).
1962 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1963                              unsigned ShuffleKind, SelectionDAG &DAG) {
1964   if (DAG.getDataLayout().isLittleEndian()) {
1965     if (ShuffleKind == 1) // unary
1966       return isVMerge(N, UnitSize, 0, 0);
1967     else if (ShuffleKind == 2) // swapped
1968       return isVMerge(N, UnitSize, 0, 16);
1969     else
1970       return false;
1971   } else {
1972     if (ShuffleKind == 1) // unary
1973       return isVMerge(N, UnitSize, 8, 8);
1974     else if (ShuffleKind == 0) // normal
1975       return isVMerge(N, UnitSize, 8, 24);
1976     else
1977       return false;
1978   }
1979 }
1980 
1981 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1982 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1983 /// The ShuffleKind distinguishes between big-endian merges with two
1984 /// different inputs (0), either-endian merges with two identical inputs (1),
1985 /// and little-endian merges with two different inputs (2).  For the latter,
1986 /// the input operands are swapped (see PPCInstrAltivec.td).
1987 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1988                              unsigned ShuffleKind, SelectionDAG &DAG) {
1989   if (DAG.getDataLayout().isLittleEndian()) {
1990     if (ShuffleKind == 1) // unary
1991       return isVMerge(N, UnitSize, 8, 8);
1992     else if (ShuffleKind == 2) // swapped
1993       return isVMerge(N, UnitSize, 8, 24);
1994     else
1995       return false;
1996   } else {
1997     if (ShuffleKind == 1) // unary
1998       return isVMerge(N, UnitSize, 0, 0);
1999     else if (ShuffleKind == 0) // normal
2000       return isVMerge(N, UnitSize, 0, 16);
2001     else
2002       return false;
2003   }
2004 }
2005 
2006 /**
2007  * Common function used to match vmrgew and vmrgow shuffles
2008  *
2009  * The indexOffset determines whether to look for even or odd words in
2010  * the shuffle mask. This is based on the of the endianness of the target
2011  * machine.
2012  *   - Little Endian:
2013  *     - Use offset of 0 to check for odd elements
2014  *     - Use offset of 4 to check for even elements
2015  *   - Big Endian:
2016  *     - Use offset of 0 to check for even elements
2017  *     - Use offset of 4 to check for odd elements
2018  * A detailed description of the vector element ordering for little endian and
2019  * big endian can be found at
2020  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2021  * Targeting your applications - what little endian and big endian IBM XL C/C++
2022  * compiler differences mean to you
2023  *
2024  * The mask to the shuffle vector instruction specifies the indices of the
2025  * elements from the two input vectors to place in the result. The elements are
2026  * numbered in array-access order, starting with the first vector. These vectors
2027  * are always of type v16i8, thus each vector will contain 16 elements of size
2028  * 8. More info on the shuffle vector can be found in the
2029  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2030  * Language Reference.
2031  *
2032  * The RHSStartValue indicates whether the same input vectors are used (unary)
2033  * or two different input vectors are used, based on the following:
2034  *   - If the instruction uses the same vector for both inputs, the range of the
2035  *     indices will be 0 to 15. In this case, the RHSStart value passed should
2036  *     be 0.
2037  *   - If the instruction has two different vectors then the range of the
2038  *     indices will be 0 to 31. In this case, the RHSStart value passed should
2039  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
2040  *     to 31 specify elements in the second vector).
2041  *
2042  * \param[in] N The shuffle vector SD Node to analyze
2043  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2044  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2045  * vector to the shuffle_vector instruction
2046  * \return true iff this shuffle vector represents an even or odd word merge
2047  */
2048 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2049                      unsigned RHSStartValue) {
2050   if (N->getValueType(0) != MVT::v16i8)
2051     return false;
2052 
2053   for (unsigned i = 0; i < 2; ++i)
2054     for (unsigned j = 0; j < 4; ++j)
2055       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2056                              i*RHSStartValue+j+IndexOffset) ||
2057           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2058                              i*RHSStartValue+j+IndexOffset+8))
2059         return false;
2060   return true;
2061 }
2062 
2063 /**
2064  * Determine if the specified shuffle mask is suitable for the vmrgew or
2065  * vmrgow instructions.
2066  *
2067  * \param[in] N The shuffle vector SD Node to analyze
2068  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2069  * \param[in] ShuffleKind Identify the type of merge:
2070  *   - 0 = big-endian merge with two different inputs;
2071  *   - 1 = either-endian merge with two identical inputs;
2072  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2073  *     little-endian merges).
2074  * \param[in] DAG The current SelectionDAG
2075  * \return true iff this shuffle mask
2076  */
2077 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2078                               unsigned ShuffleKind, SelectionDAG &DAG) {
2079   if (DAG.getDataLayout().isLittleEndian()) {
2080     unsigned indexOffset = CheckEven ? 4 : 0;
2081     if (ShuffleKind == 1) // Unary
2082       return isVMerge(N, indexOffset, 0);
2083     else if (ShuffleKind == 2) // swapped
2084       return isVMerge(N, indexOffset, 16);
2085     else
2086       return false;
2087   }
2088   else {
2089     unsigned indexOffset = CheckEven ? 0 : 4;
2090     if (ShuffleKind == 1) // Unary
2091       return isVMerge(N, indexOffset, 0);
2092     else if (ShuffleKind == 0) // Normal
2093       return isVMerge(N, indexOffset, 16);
2094     else
2095       return false;
2096   }
2097   return false;
2098 }
2099 
2100 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2101 /// amount, otherwise return -1.
2102 /// The ShuffleKind distinguishes between big-endian operations with two
2103 /// different inputs (0), either-endian operations with two identical inputs
2104 /// (1), and little-endian operations with two different inputs (2).  For the
2105 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2106 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2107                              SelectionDAG &DAG) {
2108   if (N->getValueType(0) != MVT::v16i8)
2109     return -1;
2110 
2111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2112 
2113   // Find the first non-undef value in the shuffle mask.
2114   unsigned i;
2115   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2116     /*search*/;
2117 
2118   if (i == 16) return -1;  // all undef.
2119 
2120   // Otherwise, check to see if the rest of the elements are consecutively
2121   // numbered from this value.
2122   unsigned ShiftAmt = SVOp->getMaskElt(i);
2123   if (ShiftAmt < i) return -1;
2124 
2125   ShiftAmt -= i;
2126   bool isLE = DAG.getDataLayout().isLittleEndian();
2127 
2128   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2129     // Check the rest of the elements to see if they are consecutive.
2130     for (++i; i != 16; ++i)
2131       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2132         return -1;
2133   } else if (ShuffleKind == 1) {
2134     // Check the rest of the elements to see if they are consecutive.
2135     for (++i; i != 16; ++i)
2136       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2137         return -1;
2138   } else
2139     return -1;
2140 
2141   if (isLE)
2142     ShiftAmt = 16 - ShiftAmt;
2143 
2144   return ShiftAmt;
2145 }
2146 
2147 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2148 /// specifies a splat of a single element that is suitable for input to
2149 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2150 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2151   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2152          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2153 
2154   // The consecutive indices need to specify an element, not part of two
2155   // different elements.  So abandon ship early if this isn't the case.
2156   if (N->getMaskElt(0) % EltSize != 0)
2157     return false;
2158 
2159   // This is a splat operation if each element of the permute is the same, and
2160   // if the value doesn't reference the second vector.
2161   unsigned ElementBase = N->getMaskElt(0);
2162 
2163   // FIXME: Handle UNDEF elements too!
2164   if (ElementBase >= 16)
2165     return false;
2166 
2167   // Check that the indices are consecutive, in the case of a multi-byte element
2168   // splatted with a v16i8 mask.
2169   for (unsigned i = 1; i != EltSize; ++i)
2170     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2171       return false;
2172 
2173   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2174     if (N->getMaskElt(i) < 0) continue;
2175     for (unsigned j = 0; j != EltSize; ++j)
2176       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2177         return false;
2178   }
2179   return true;
2180 }
2181 
2182 /// Check that the mask is shuffling N byte elements. Within each N byte
2183 /// element of the mask, the indices could be either in increasing or
2184 /// decreasing order as long as they are consecutive.
2185 /// \param[in] N the shuffle vector SD Node to analyze
2186 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2187 /// Word/DoubleWord/QuadWord).
2188 /// \param[in] StepLen the delta indices number among the N byte element, if
2189 /// the mask is in increasing/decreasing order then it is 1/-1.
2190 /// \return true iff the mask is shuffling N byte elements.
2191 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2192                                    int StepLen) {
2193   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2194          "Unexpected element width.");
2195   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2196 
2197   unsigned NumOfElem = 16 / Width;
2198   unsigned MaskVal[16]; //  Width is never greater than 16
2199   for (unsigned i = 0; i < NumOfElem; ++i) {
2200     MaskVal[0] = N->getMaskElt(i * Width);
2201     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2202       return false;
2203     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2204       return false;
2205     }
2206 
2207     for (unsigned int j = 1; j < Width; ++j) {
2208       MaskVal[j] = N->getMaskElt(i * Width + j);
2209       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2210         return false;
2211       }
2212     }
2213   }
2214 
2215   return true;
2216 }
2217 
2218 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2219                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2220   if (!isNByteElemShuffleMask(N, 4, 1))
2221     return false;
2222 
2223   // Now we look at mask elements 0,4,8,12
2224   unsigned M0 = N->getMaskElt(0) / 4;
2225   unsigned M1 = N->getMaskElt(4) / 4;
2226   unsigned M2 = N->getMaskElt(8) / 4;
2227   unsigned M3 = N->getMaskElt(12) / 4;
2228   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2229   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2230 
2231   // Below, let H and L be arbitrary elements of the shuffle mask
2232   // where H is in the range [4,7] and L is in the range [0,3].
2233   // H, 1, 2, 3 or L, 5, 6, 7
2234   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2235       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2236     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2237     InsertAtByte = IsLE ? 12 : 0;
2238     Swap = M0 < 4;
2239     return true;
2240   }
2241   // 0, H, 2, 3 or 4, L, 6, 7
2242   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2243       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2244     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2245     InsertAtByte = IsLE ? 8 : 4;
2246     Swap = M1 < 4;
2247     return true;
2248   }
2249   // 0, 1, H, 3 or 4, 5, L, 7
2250   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2251       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2252     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2253     InsertAtByte = IsLE ? 4 : 8;
2254     Swap = M2 < 4;
2255     return true;
2256   }
2257   // 0, 1, 2, H or 4, 5, 6, L
2258   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2259       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2260     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2261     InsertAtByte = IsLE ? 0 : 12;
2262     Swap = M3 < 4;
2263     return true;
2264   }
2265 
2266   // If both vector operands for the shuffle are the same vector, the mask will
2267   // contain only elements from the first one and the second one will be undef.
2268   if (N->getOperand(1).isUndef()) {
2269     ShiftElts = 0;
2270     Swap = true;
2271     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2272     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2273       InsertAtByte = IsLE ? 12 : 0;
2274       return true;
2275     }
2276     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2277       InsertAtByte = IsLE ? 8 : 4;
2278       return true;
2279     }
2280     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2281       InsertAtByte = IsLE ? 4 : 8;
2282       return true;
2283     }
2284     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2285       InsertAtByte = IsLE ? 0 : 12;
2286       return true;
2287     }
2288   }
2289 
2290   return false;
2291 }
2292 
2293 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2294                                bool &Swap, bool IsLE) {
2295   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2296   // Ensure each byte index of the word is consecutive.
2297   if (!isNByteElemShuffleMask(N, 4, 1))
2298     return false;
2299 
2300   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2301   unsigned M0 = N->getMaskElt(0) / 4;
2302   unsigned M1 = N->getMaskElt(4) / 4;
2303   unsigned M2 = N->getMaskElt(8) / 4;
2304   unsigned M3 = N->getMaskElt(12) / 4;
2305 
2306   // If both vector operands for the shuffle are the same vector, the mask will
2307   // contain only elements from the first one and the second one will be undef.
2308   if (N->getOperand(1).isUndef()) {
2309     assert(M0 < 4 && "Indexing into an undef vector?");
2310     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2311       return false;
2312 
2313     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2314     Swap = false;
2315     return true;
2316   }
2317 
2318   // Ensure each word index of the ShuffleVector Mask is consecutive.
2319   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2320     return false;
2321 
2322   if (IsLE) {
2323     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2324       // Input vectors don't need to be swapped if the leading element
2325       // of the result is one of the 3 left elements of the second vector
2326       // (or if there is no shift to be done at all).
2327       Swap = false;
2328       ShiftElts = (8 - M0) % 8;
2329     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2330       // Input vectors need to be swapped if the leading element
2331       // of the result is one of the 3 left elements of the first vector
2332       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2333       Swap = true;
2334       ShiftElts = (4 - M0) % 4;
2335     }
2336 
2337     return true;
2338   } else {                                          // BE
2339     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2340       // Input vectors don't need to be swapped if the leading element
2341       // of the result is one of the 4 elements of the first vector.
2342       Swap = false;
2343       ShiftElts = M0;
2344     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2345       // Input vectors need to be swapped if the leading element
2346       // of the result is one of the 4 elements of the right vector.
2347       Swap = true;
2348       ShiftElts = M0 - 4;
2349     }
2350 
2351     return true;
2352   }
2353 }
2354 
2355 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2356   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2357 
2358   if (!isNByteElemShuffleMask(N, Width, -1))
2359     return false;
2360 
2361   for (int i = 0; i < 16; i += Width)
2362     if (N->getMaskElt(i) != i + Width - 1)
2363       return false;
2364 
2365   return true;
2366 }
2367 
2368 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2369   return isXXBRShuffleMaskHelper(N, 2);
2370 }
2371 
2372 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2373   return isXXBRShuffleMaskHelper(N, 4);
2374 }
2375 
2376 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2377   return isXXBRShuffleMaskHelper(N, 8);
2378 }
2379 
2380 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2381   return isXXBRShuffleMaskHelper(N, 16);
2382 }
2383 
2384 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2385 /// if the inputs to the instruction should be swapped and set \p DM to the
2386 /// value for the immediate.
2387 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2388 /// AND element 0 of the result comes from the first input (LE) or second input
2389 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2390 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2391 /// mask.
2392 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2393                                bool &Swap, bool IsLE) {
2394   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2395 
2396   // Ensure each byte index of the double word is consecutive.
2397   if (!isNByteElemShuffleMask(N, 8, 1))
2398     return false;
2399 
2400   unsigned M0 = N->getMaskElt(0) / 8;
2401   unsigned M1 = N->getMaskElt(8) / 8;
2402   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2403 
2404   // If both vector operands for the shuffle are the same vector, the mask will
2405   // contain only elements from the first one and the second one will be undef.
2406   if (N->getOperand(1).isUndef()) {
2407     if ((M0 | M1) < 2) {
2408       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2409       Swap = false;
2410       return true;
2411     } else
2412       return false;
2413   }
2414 
2415   if (IsLE) {
2416     if (M0 > 1 && M1 < 2) {
2417       Swap = false;
2418     } else if (M0 < 2 && M1 > 1) {
2419       M0 = (M0 + 2) % 4;
2420       M1 = (M1 + 2) % 4;
2421       Swap = true;
2422     } else
2423       return false;
2424 
2425     // Note: if control flow comes here that means Swap is already set above
2426     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2427     return true;
2428   } else { // BE
2429     if (M0 < 2 && M1 > 1) {
2430       Swap = false;
2431     } else if (M0 > 1 && M1 < 2) {
2432       M0 = (M0 + 2) % 4;
2433       M1 = (M1 + 2) % 4;
2434       Swap = true;
2435     } else
2436       return false;
2437 
2438     // Note: if control flow comes here that means Swap is already set above
2439     DM = (M0 << 1) + (M1 & 1);
2440     return true;
2441   }
2442 }
2443 
2444 
2445 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2446 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2447 /// elements are counted from the left of the vector register).
2448 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2449                                          SelectionDAG &DAG) {
2450   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2451   assert(isSplatShuffleMask(SVOp, EltSize));
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         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4448                                      MachinePointerInfo(&*FuncArg, j));
4449         MemOps.push_back(Store);
4450         ++GPR_idx;
4451       }
4452       ArgOffset += ArgSize;
4453       continue;
4454     }
4455 
4456     switch (ObjectVT.getSimpleVT().SimpleTy) {
4457     default: llvm_unreachable("Unhandled argument type!");
4458     case MVT::i1:
4459     case MVT::i32:
4460     case MVT::i64:
4461       if (Flags.isNest()) {
4462         // The 'nest' parameter, if any, is passed in R11.
4463         Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4464         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4465 
4466         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4467           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4468 
4469         break;
4470       }
4471 
4472       // These can be scalar arguments or elements of an integer array type
4473       // passed directly.  Clang may use those instead of "byval" aggregate
4474       // types to avoid forcing arguments to memory unnecessarily.
4475       if (GPR_idx != Num_GPR_Regs) {
4476         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4477         FuncInfo->addLiveInAttr(VReg, Flags);
4478         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4479 
4480         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4481           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4482           // value to MVT::i64 and then truncate to the correct register size.
4483           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4484       } else {
4485         if (CallConv == CallingConv::Fast)
4486           ComputeArgOffset();
4487 
4488         needsLoad = true;
4489         ArgSize = PtrByteSize;
4490       }
4491       if (CallConv != CallingConv::Fast || needsLoad)
4492         ArgOffset += 8;
4493       break;
4494 
4495     case MVT::f32:
4496     case MVT::f64:
4497       // These can be scalar arguments or elements of a float array type
4498       // passed directly.  The latter are used to implement ELFv2 homogenous
4499       // float aggregates.
4500       if (FPR_idx != Num_FPR_Regs) {
4501         unsigned VReg;
4502 
4503         if (ObjectVT == MVT::f32)
4504           VReg = MF.addLiveIn(FPR[FPR_idx],
4505                               Subtarget.hasP8Vector()
4506                                   ? &PPC::VSSRCRegClass
4507                                   : &PPC::F4RCRegClass);
4508         else
4509           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4510                                                 ? &PPC::VSFRCRegClass
4511                                                 : &PPC::F8RCRegClass);
4512 
4513         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4514         ++FPR_idx;
4515       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4516         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4517         // once we support fp <-> gpr moves.
4518 
4519         // This can only ever happen in the presence of f32 array types,
4520         // since otherwise we never run out of FPRs before running out
4521         // of GPRs.
4522         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4523         FuncInfo->addLiveInAttr(VReg, Flags);
4524         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4525 
4526         if (ObjectVT == MVT::f32) {
4527           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4528             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4529                                  DAG.getConstant(32, dl, MVT::i32));
4530           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4531         }
4532 
4533         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4534       } else {
4535         if (CallConv == CallingConv::Fast)
4536           ComputeArgOffset();
4537 
4538         needsLoad = true;
4539       }
4540 
4541       // When passing an array of floats, the array occupies consecutive
4542       // space in the argument area; only round up to the next doubleword
4543       // at the end of the array.  Otherwise, each float takes 8 bytes.
4544       if (CallConv != CallingConv::Fast || needsLoad) {
4545         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4546         ArgOffset += ArgSize;
4547         if (Flags.isInConsecutiveRegsLast())
4548           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4549       }
4550       break;
4551     case MVT::v4f32:
4552     case MVT::v4i32:
4553     case MVT::v8i16:
4554     case MVT::v16i8:
4555     case MVT::v2f64:
4556     case MVT::v2i64:
4557     case MVT::v1i128:
4558     case MVT::f128:
4559       // These can be scalar arguments or elements of a vector array type
4560       // passed directly.  The latter are used to implement ELFv2 homogenous
4561       // vector aggregates.
4562       if (VR_idx != Num_VR_Regs) {
4563         Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4564         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4565         ++VR_idx;
4566       } else {
4567         if (CallConv == CallingConv::Fast)
4568           ComputeArgOffset();
4569         needsLoad = true;
4570       }
4571       if (CallConv != CallingConv::Fast || needsLoad)
4572         ArgOffset += 16;
4573       break;
4574     }
4575 
4576     // We need to load the argument to a virtual register if we determined
4577     // above that we ran out of physical registers of the appropriate type.
4578     if (needsLoad) {
4579       if (ObjSize < ArgSize && !isLittleEndian)
4580         CurArgOffset += ArgSize - ObjSize;
4581       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4582       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4583       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4584     }
4585 
4586     InVals.push_back(ArgVal);
4587   }
4588 
4589   // Area that is at least reserved in the caller of this function.
4590   unsigned MinReservedArea;
4591   if (HasParameterArea)
4592     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4593   else
4594     MinReservedArea = LinkageSize;
4595 
4596   // Set the size that is at least reserved in caller of this function.  Tail
4597   // call optimized functions' reserved stack space needs to be aligned so that
4598   // taking the difference between two stack areas will result in an aligned
4599   // stack.
4600   MinReservedArea =
4601       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4602   FuncInfo->setMinReservedArea(MinReservedArea);
4603 
4604   // If the function takes variable number of arguments, make a frame index for
4605   // the start of the first vararg value... for expansion of llvm.va_start.
4606   // On ELFv2ABI spec, it writes:
4607   // C programs that are intended to be *portable* across different compilers
4608   // and architectures must use the header file <stdarg.h> to deal with variable
4609   // argument lists.
4610   if (isVarArg && MFI.hasVAStart()) {
4611     int Depth = ArgOffset;
4612 
4613     FuncInfo->setVarArgsFrameIndex(
4614       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4615     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4616 
4617     // If this function is vararg, store any remaining integer argument regs
4618     // to their spots on the stack so that they may be loaded by dereferencing
4619     // the result of va_next.
4620     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4621          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4622       Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4623       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4624       SDValue Store =
4625           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4626       MemOps.push_back(Store);
4627       // Increment the address by four for the next argument to store
4628       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4629       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4630     }
4631   }
4632 
4633   if (!MemOps.empty())
4634     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4635 
4636   return Chain;
4637 }
4638 
4639 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4640 /// adjusted to accommodate the arguments for the tailcall.
4641 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4642                                    unsigned ParamSize) {
4643 
4644   if (!isTailCall) return 0;
4645 
4646   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4647   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4648   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4649   // Remember only if the new adjustment is bigger.
4650   if (SPDiff < FI->getTailCallSPDelta())
4651     FI->setTailCallSPDelta(SPDiff);
4652 
4653   return SPDiff;
4654 }
4655 
4656 static bool isFunctionGlobalAddress(SDValue Callee);
4657 
4658 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4659                               const TargetMachine &TM) {
4660   // It does not make sense to call callsShareTOCBase() with a caller that
4661   // is PC Relative since PC Relative callers do not have a TOC.
4662 #ifndef NDEBUG
4663   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4664   assert(!STICaller->isUsingPCRelativeCalls() &&
4665          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4666 #endif
4667 
4668   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4669   // don't have enough information to determine if the caller and callee share
4670   // the same  TOC base, so we have to pessimistically assume they don't for
4671   // correctness.
4672   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4673   if (!G)
4674     return false;
4675 
4676   const GlobalValue *GV = G->getGlobal();
4677 
4678   // If the callee is preemptable, then the static linker will use a plt-stub
4679   // which saves the toc to the stack, and needs a nop after the call
4680   // instruction to convert to a toc-restore.
4681   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4682     return false;
4683 
4684   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4685   // We may need a TOC restore in the situation where the caller requires a
4686   // valid TOC but the callee is PC Relative and does not.
4687   const Function *F = dyn_cast<Function>(GV);
4688   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4689 
4690   // If we have an Alias we can try to get the function from there.
4691   if (Alias) {
4692     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4693     F = dyn_cast<Function>(GlobalObj);
4694   }
4695 
4696   // If we still have no valid function pointer we do not have enough
4697   // information to determine if the callee uses PC Relative calls so we must
4698   // assume that it does.
4699   if (!F)
4700     return false;
4701 
4702   // If the callee uses PC Relative we cannot guarantee that the callee won't
4703   // clobber the TOC of the caller and so we must assume that the two
4704   // functions do not share a TOC base.
4705   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4706   if (STICallee->isUsingPCRelativeCalls())
4707     return false;
4708 
4709   // If the GV is not a strong definition then we need to assume it can be
4710   // replaced by another function at link time. The function that replaces
4711   // it may not share the same TOC as the caller since the callee may be
4712   // replaced by a PC Relative version of the same function.
4713   if (!GV->isStrongDefinitionForLinker())
4714     return false;
4715 
4716   // The medium and large code models are expected to provide a sufficiently
4717   // large TOC to provide all data addressing needs of a module with a
4718   // single TOC.
4719   if (CodeModel::Medium == TM.getCodeModel() ||
4720       CodeModel::Large == TM.getCodeModel())
4721     return true;
4722 
4723   // Any explicitly-specified sections and section prefixes must also match.
4724   // Also, if we're using -ffunction-sections, then each function is always in
4725   // a different section (the same is true for COMDAT functions).
4726   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4727       GV->getSection() != Caller->getSection())
4728     return false;
4729   if (const auto *F = dyn_cast<Function>(GV)) {
4730     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4731       return false;
4732   }
4733 
4734   return true;
4735 }
4736 
4737 static bool
4738 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4739                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4740   assert(Subtarget.is64BitELFABI());
4741 
4742   const unsigned PtrByteSize = 8;
4743   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4744 
4745   static const MCPhysReg GPR[] = {
4746     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4747     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4748   };
4749   static const MCPhysReg VR[] = {
4750     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4751     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4752   };
4753 
4754   const unsigned NumGPRs = array_lengthof(GPR);
4755   const unsigned NumFPRs = 13;
4756   const unsigned NumVRs = array_lengthof(VR);
4757   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4758 
4759   unsigned NumBytes = LinkageSize;
4760   unsigned AvailableFPRs = NumFPRs;
4761   unsigned AvailableVRs = NumVRs;
4762 
4763   for (const ISD::OutputArg& Param : Outs) {
4764     if (Param.Flags.isNest()) continue;
4765 
4766     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4767                                LinkageSize, ParamAreaSize, NumBytes,
4768                                AvailableFPRs, AvailableVRs))
4769       return true;
4770   }
4771   return false;
4772 }
4773 
4774 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4775   if (CB.arg_size() != CallerFn->arg_size())
4776     return false;
4777 
4778   auto CalleeArgIter = CB.arg_begin();
4779   auto CalleeArgEnd = CB.arg_end();
4780   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4781 
4782   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4783     const Value* CalleeArg = *CalleeArgIter;
4784     const Value* CallerArg = &(*CallerArgIter);
4785     if (CalleeArg == CallerArg)
4786       continue;
4787 
4788     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4789     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4790     //      }
4791     // 1st argument of callee is undef and has the same type as caller.
4792     if (CalleeArg->getType() == CallerArg->getType() &&
4793         isa<UndefValue>(CalleeArg))
4794       continue;
4795 
4796     return false;
4797   }
4798 
4799   return true;
4800 }
4801 
4802 // Returns true if TCO is possible between the callers and callees
4803 // calling conventions.
4804 static bool
4805 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4806                                     CallingConv::ID CalleeCC) {
4807   // Tail calls are possible with fastcc and ccc.
4808   auto isTailCallableCC  = [] (CallingConv::ID CC){
4809       return  CC == CallingConv::C || CC == CallingConv::Fast;
4810   };
4811   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4812     return false;
4813 
4814   // We can safely tail call both fastcc and ccc callees from a c calling
4815   // convention caller. If the caller is fastcc, we may have less stack space
4816   // than a non-fastcc caller with the same signature so disable tail-calls in
4817   // that case.
4818   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4819 }
4820 
4821 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4822     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4823     const SmallVectorImpl<ISD::OutputArg> &Outs,
4824     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4825   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4826 
4827   if (DisableSCO && !TailCallOpt) return false;
4828 
4829   // Variadic argument functions are not supported.
4830   if (isVarArg) return false;
4831 
4832   auto &Caller = DAG.getMachineFunction().getFunction();
4833   // Check that the calling conventions are compatible for tco.
4834   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4835     return false;
4836 
4837   // Caller contains any byval parameter is not supported.
4838   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4839     return false;
4840 
4841   // Callee contains any byval parameter is not supported, too.
4842   // Note: This is a quick work around, because in some cases, e.g.
4843   // caller's stack size > callee's stack size, we are still able to apply
4844   // sibling call optimization. For example, gcc is able to do SCO for caller1
4845   // in the following example, but not for caller2.
4846   //   struct test {
4847   //     long int a;
4848   //     char ary[56];
4849   //   } gTest;
4850   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4851   //     b->a = v.a;
4852   //     return 0;
4853   //   }
4854   //   void caller1(struct test a, struct test c, struct test *b) {
4855   //     callee(gTest, b); }
4856   //   void caller2(struct test *b) { callee(gTest, b); }
4857   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4858     return false;
4859 
4860   // If callee and caller use different calling conventions, we cannot pass
4861   // parameters on stack since offsets for the parameter area may be different.
4862   if (Caller.getCallingConv() != CalleeCC &&
4863       needStackSlotPassParameters(Subtarget, Outs))
4864     return false;
4865 
4866   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4867   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4868   // callee potentially have different TOC bases then we cannot tail call since
4869   // we need to restore the TOC pointer after the call.
4870   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4871   // We cannot guarantee this for indirect calls or calls to external functions.
4872   // When PC-Relative addressing is used, the concept of the TOC is no longer
4873   // applicable so this check is not required.
4874   // Check first for indirect calls.
4875   if (!Subtarget.isUsingPCRelativeCalls() &&
4876       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4877     return false;
4878 
4879   // Check if we share the TOC base.
4880   if (!Subtarget.isUsingPCRelativeCalls() &&
4881       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4882     return false;
4883 
4884   // TCO allows altering callee ABI, so we don't have to check further.
4885   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4886     return true;
4887 
4888   if (DisableSCO) return false;
4889 
4890   // If callee use the same argument list that caller is using, then we can
4891   // apply SCO on this case. If it is not, then we need to check if callee needs
4892   // stack for passing arguments.
4893   // PC Relative tail calls may not have a CallBase.
4894   // If there is no CallBase we cannot verify if we have the same argument
4895   // list so assume that we don't have the same argument list.
4896   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4897       needStackSlotPassParameters(Subtarget, Outs))
4898     return false;
4899   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4900     return false;
4901 
4902   return true;
4903 }
4904 
4905 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4906 /// for tail call optimization. Targets which want to do tail call
4907 /// optimization should implement this function.
4908 bool
4909 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4910                                                      CallingConv::ID CalleeCC,
4911                                                      bool isVarArg,
4912                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4913                                                      SelectionDAG& DAG) const {
4914   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4915     return false;
4916 
4917   // Variable argument functions are not supported.
4918   if (isVarArg)
4919     return false;
4920 
4921   MachineFunction &MF = DAG.getMachineFunction();
4922   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4923   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4924     // Functions containing by val parameters are not supported.
4925     for (unsigned i = 0; i != Ins.size(); i++) {
4926        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4927        if (Flags.isByVal()) return false;
4928     }
4929 
4930     // Non-PIC/GOT tail calls are supported.
4931     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4932       return true;
4933 
4934     // At the moment we can only do local tail calls (in same module, hidden
4935     // or protected) if we are generating PIC.
4936     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4937       return G->getGlobal()->hasHiddenVisibility()
4938           || G->getGlobal()->hasProtectedVisibility();
4939   }
4940 
4941   return false;
4942 }
4943 
4944 /// isCallCompatibleAddress - Return the immediate to use if the specified
4945 /// 32-bit value is representable in the immediate field of a BxA instruction.
4946 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4947   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4948   if (!C) return nullptr;
4949 
4950   int Addr = C->getZExtValue();
4951   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4952       SignExtend32<26>(Addr) != Addr)
4953     return nullptr;  // Top 6 bits have to be sext of immediate.
4954 
4955   return DAG
4956       .getConstant(
4957           (int)C->getZExtValue() >> 2, SDLoc(Op),
4958           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4959       .getNode();
4960 }
4961 
4962 namespace {
4963 
4964 struct TailCallArgumentInfo {
4965   SDValue Arg;
4966   SDValue FrameIdxOp;
4967   int FrameIdx = 0;
4968 
4969   TailCallArgumentInfo() = default;
4970 };
4971 
4972 } // end anonymous namespace
4973 
4974 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4975 static void StoreTailCallArgumentsToStackSlot(
4976     SelectionDAG &DAG, SDValue Chain,
4977     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4978     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4979   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4980     SDValue Arg = TailCallArgs[i].Arg;
4981     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4982     int FI = TailCallArgs[i].FrameIdx;
4983     // Store relative to framepointer.
4984     MemOpChains.push_back(DAG.getStore(
4985         Chain, dl, Arg, FIN,
4986         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4987   }
4988 }
4989 
4990 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4991 /// the appropriate stack slot for the tail call optimized function call.
4992 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4993                                              SDValue OldRetAddr, SDValue OldFP,
4994                                              int SPDiff, const SDLoc &dl) {
4995   if (SPDiff) {
4996     // Calculate the new stack slot for the return address.
4997     MachineFunction &MF = DAG.getMachineFunction();
4998     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4999     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5000     bool isPPC64 = Subtarget.isPPC64();
5001     int SlotSize = isPPC64 ? 8 : 4;
5002     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5003     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5004                                                          NewRetAddrLoc, true);
5005     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5006     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5007     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5008                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5009   }
5010   return Chain;
5011 }
5012 
5013 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5014 /// the position of the argument.
5015 static void
5016 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5017                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5018                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5019   int Offset = ArgOffset + SPDiff;
5020   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5021   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5022   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5023   SDValue FIN = DAG.getFrameIndex(FI, VT);
5024   TailCallArgumentInfo Info;
5025   Info.Arg = Arg;
5026   Info.FrameIdxOp = FIN;
5027   Info.FrameIdx = FI;
5028   TailCallArguments.push_back(Info);
5029 }
5030 
5031 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5032 /// stack slot. Returns the chain as result and the loaded frame pointers in
5033 /// LROpOut/FPOpout. Used when tail calling.
5034 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5035     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5036     SDValue &FPOpOut, const SDLoc &dl) const {
5037   if (SPDiff) {
5038     // Load the LR and FP stack slot for later adjusting.
5039     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5040     LROpOut = getReturnAddrFrameIndex(DAG);
5041     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5042     Chain = SDValue(LROpOut.getNode(), 1);
5043   }
5044   return Chain;
5045 }
5046 
5047 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5048 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5049 /// specified by the specific parameter attribute. The copy will be passed as
5050 /// a byval function parameter.
5051 /// Sometimes what we are copying is the end of a larger object, the part that
5052 /// does not fit in registers.
5053 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5054                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5055                                          SelectionDAG &DAG, const SDLoc &dl) {
5056   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5057   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5058                        Flags.getNonZeroByValAlign(), false, false, false,
5059                        MachinePointerInfo(), MachinePointerInfo());
5060 }
5061 
5062 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5063 /// tail calls.
5064 static void LowerMemOpCallTo(
5065     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5066     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5067     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5068     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5069   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5070   if (!isTailCall) {
5071     if (isVector) {
5072       SDValue StackPtr;
5073       if (isPPC64)
5074         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5075       else
5076         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5077       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5078                            DAG.getConstant(ArgOffset, dl, PtrVT));
5079     }
5080     MemOpChains.push_back(
5081         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5082     // Calculate and remember argument location.
5083   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5084                                   TailCallArguments);
5085 }
5086 
5087 static void
5088 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5089                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5090                 SDValue FPOp,
5091                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5092   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5093   // might overwrite each other in case of tail call optimization.
5094   SmallVector<SDValue, 8> MemOpChains2;
5095   // Do not flag preceding copytoreg stuff together with the following stuff.
5096   InFlag = SDValue();
5097   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5098                                     MemOpChains2, dl);
5099   if (!MemOpChains2.empty())
5100     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5101 
5102   // Store the return address to the appropriate stack slot.
5103   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5104 
5105   // Emit callseq_end just before tailcall node.
5106   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5107                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5108   InFlag = Chain.getValue(1);
5109 }
5110 
5111 // Is this global address that of a function that can be called by name? (as
5112 // opposed to something that must hold a descriptor for an indirect call).
5113 static bool isFunctionGlobalAddress(SDValue Callee) {
5114   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5115     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5116         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5117       return false;
5118 
5119     return G->getGlobal()->getValueType()->isFunctionTy();
5120   }
5121 
5122   return false;
5123 }
5124 
5125 SDValue PPCTargetLowering::LowerCallResult(
5126     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5127     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5128     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5129   SmallVector<CCValAssign, 16> RVLocs;
5130   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5131                     *DAG.getContext());
5132 
5133   CCRetInfo.AnalyzeCallResult(
5134       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5135                ? RetCC_PPC_Cold
5136                : RetCC_PPC);
5137 
5138   // Copy all of the result registers out of their specified physreg.
5139   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5140     CCValAssign &VA = RVLocs[i];
5141     assert(VA.isRegLoc() && "Can only return in registers!");
5142 
5143     SDValue Val;
5144 
5145     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5146       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5147                                       InFlag);
5148       Chain = Lo.getValue(1);
5149       InFlag = Lo.getValue(2);
5150       VA = RVLocs[++i]; // skip ahead to next loc
5151       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5152                                       InFlag);
5153       Chain = Hi.getValue(1);
5154       InFlag = Hi.getValue(2);
5155       if (!Subtarget.isLittleEndian())
5156         std::swap (Lo, Hi);
5157       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5158     } else {
5159       Val = DAG.getCopyFromReg(Chain, dl,
5160                                VA.getLocReg(), VA.getLocVT(), InFlag);
5161       Chain = Val.getValue(1);
5162       InFlag = Val.getValue(2);
5163     }
5164 
5165     switch (VA.getLocInfo()) {
5166     default: llvm_unreachable("Unknown loc info!");
5167     case CCValAssign::Full: break;
5168     case CCValAssign::AExt:
5169       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5170       break;
5171     case CCValAssign::ZExt:
5172       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5173                         DAG.getValueType(VA.getValVT()));
5174       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5175       break;
5176     case CCValAssign::SExt:
5177       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5178                         DAG.getValueType(VA.getValVT()));
5179       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5180       break;
5181     }
5182 
5183     InVals.push_back(Val);
5184   }
5185 
5186   return Chain;
5187 }
5188 
5189 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5190                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5191   // PatchPoint calls are not indirect.
5192   if (isPatchPoint)
5193     return false;
5194 
5195   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5196     return false;
5197 
5198   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5199   // becuase the immediate function pointer points to a descriptor instead of
5200   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5201   // pointer immediate points to the global entry point, while the BLA would
5202   // need to jump to the local entry point (see rL211174).
5203   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5204       isBLACompatibleAddress(Callee, DAG))
5205     return false;
5206 
5207   return true;
5208 }
5209 
5210 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5211 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5212   return Subtarget.isAIXABI() ||
5213          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5214 }
5215 
5216 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5217                               const Function &Caller, const SDValue &Callee,
5218                               const PPCSubtarget &Subtarget,
5219                               const TargetMachine &TM,
5220                               bool IsStrictFPCall = false) {
5221   if (CFlags.IsTailCall)
5222     return PPCISD::TC_RETURN;
5223 
5224   unsigned RetOpc = 0;
5225   // This is a call through a function pointer.
5226   if (CFlags.IsIndirect) {
5227     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5228     // indirect calls. The save of the caller's TOC pointer to the stack will be
5229     // inserted into the DAG as part of call lowering. The restore of the TOC
5230     // pointer is modeled by using a pseudo instruction for the call opcode that
5231     // represents the 2 instruction sequence of an indirect branch and link,
5232     // immediately followed by a load of the TOC pointer from the the stack save
5233     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5234     // as it is not saved or used.
5235     RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5236                                                  : PPCISD::BCTRL;
5237   } else if (Subtarget.isUsingPCRelativeCalls()) {
5238     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5239     RetOpc = PPCISD::CALL_NOTOC;
5240   } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5241     // The ABIs that maintain a TOC pointer accross calls need to have a nop
5242     // immediately following the call instruction if the caller and callee may
5243     // have different TOC bases. At link time if the linker determines the calls
5244     // may not share a TOC base, the call is redirected to a trampoline inserted
5245     // by the linker. The trampoline will (among other things) save the callers
5246     // TOC pointer at an ABI designated offset in the linkage area and the
5247     // linker will rewrite the nop to be a load of the TOC pointer from the
5248     // linkage area into gpr2.
5249     RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5250                                                     : PPCISD::CALL_NOP;
5251   else
5252     RetOpc = PPCISD::CALL;
5253   if (IsStrictFPCall) {
5254     switch (RetOpc) {
5255     default:
5256       llvm_unreachable("Unknown call opcode");
5257     case PPCISD::BCTRL_LOAD_TOC:
5258       RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5259       break;
5260     case PPCISD::BCTRL:
5261       RetOpc = PPCISD::BCTRL_RM;
5262       break;
5263     case PPCISD::CALL_NOTOC:
5264       RetOpc = PPCISD::CALL_NOTOC_RM;
5265       break;
5266     case PPCISD::CALL:
5267       RetOpc = PPCISD::CALL_RM;
5268       break;
5269     case PPCISD::CALL_NOP:
5270       RetOpc = PPCISD::CALL_NOP_RM;
5271       break;
5272     }
5273   }
5274   return RetOpc;
5275 }
5276 
5277 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5278                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5279   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5280     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5281       return SDValue(Dest, 0);
5282 
5283   // Returns true if the callee is local, and false otherwise.
5284   auto isLocalCallee = [&]() {
5285     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5286     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5287     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5288 
5289     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5290            !isa_and_nonnull<GlobalIFunc>(GV);
5291   };
5292 
5293   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5294   // a static relocation model causes some versions of GNU LD (2.17.50, at
5295   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5296   // built with secure-PLT.
5297   bool UsePlt =
5298       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5299       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5300 
5301   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5302     const TargetMachine &TM = Subtarget.getTargetMachine();
5303     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5304     MCSymbolXCOFF *S =
5305         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5306 
5307     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5308     return DAG.getMCSymbol(S, PtrVT);
5309   };
5310 
5311   if (isFunctionGlobalAddress(Callee)) {
5312     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5313 
5314     if (Subtarget.isAIXABI()) {
5315       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5316       return getAIXFuncEntryPointSymbolSDNode(GV);
5317     }
5318     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5319                                       UsePlt ? PPCII::MO_PLT : 0);
5320   }
5321 
5322   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5323     const char *SymName = S->getSymbol();
5324     if (Subtarget.isAIXABI()) {
5325       // If there exists a user-declared function whose name is the same as the
5326       // ExternalSymbol's, then we pick up the user-declared version.
5327       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5328       if (const Function *F =
5329               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5330         return getAIXFuncEntryPointSymbolSDNode(F);
5331 
5332       // On AIX, direct function calls reference the symbol for the function's
5333       // entry point, which is named by prepending a "." before the function's
5334       // C-linkage name. A Qualname is returned here because an external
5335       // function entry point is a csect with XTY_ER property.
5336       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5337         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5338         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5339             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5340             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5341         return Sec->getQualNameSymbol();
5342       };
5343 
5344       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5345     }
5346     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5347                                        UsePlt ? PPCII::MO_PLT : 0);
5348   }
5349 
5350   // No transformation needed.
5351   assert(Callee.getNode() && "What no callee?");
5352   return Callee;
5353 }
5354 
5355 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5356   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5357          "Expected a CALLSEQ_STARTSDNode.");
5358 
5359   // The last operand is the chain, except when the node has glue. If the node
5360   // has glue, then the last operand is the glue, and the chain is the second
5361   // last operand.
5362   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5363   if (LastValue.getValueType() != MVT::Glue)
5364     return LastValue;
5365 
5366   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5367 }
5368 
5369 // Creates the node that moves a functions address into the count register
5370 // to prepare for an indirect call instruction.
5371 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5372                                 SDValue &Glue, SDValue &Chain,
5373                                 const SDLoc &dl) {
5374   SDValue MTCTROps[] = {Chain, Callee, Glue};
5375   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5376   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5377                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5378   // The glue is the second value produced.
5379   Glue = Chain.getValue(1);
5380 }
5381 
5382 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5383                                           SDValue &Glue, SDValue &Chain,
5384                                           SDValue CallSeqStart,
5385                                           const CallBase *CB, const SDLoc &dl,
5386                                           bool hasNest,
5387                                           const PPCSubtarget &Subtarget) {
5388   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5389   // entry point, but to the function descriptor (the function entry point
5390   // address is part of the function descriptor though).
5391   // The function descriptor is a three doubleword structure with the
5392   // following fields: function entry point, TOC base address and
5393   // environment pointer.
5394   // Thus for a call through a function pointer, the following actions need
5395   // to be performed:
5396   //   1. Save the TOC of the caller in the TOC save area of its stack
5397   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5398   //   2. Load the address of the function entry point from the function
5399   //      descriptor.
5400   //   3. Load the TOC of the callee from the function descriptor into r2.
5401   //   4. Load the environment pointer from the function descriptor into
5402   //      r11.
5403   //   5. Branch to the function entry point address.
5404   //   6. On return of the callee, the TOC of the caller needs to be
5405   //      restored (this is done in FinishCall()).
5406   //
5407   // The loads are scheduled at the beginning of the call sequence, and the
5408   // register copies are flagged together to ensure that no other
5409   // operations can be scheduled in between. E.g. without flagging the
5410   // copies together, a TOC access in the caller could be scheduled between
5411   // the assignment of the callee TOC and the branch to the callee, which leads
5412   // to incorrect code.
5413 
5414   // Start by loading the function address from the descriptor.
5415   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5416   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5417                       ? (MachineMemOperand::MODereferenceable |
5418                          MachineMemOperand::MOInvariant)
5419                       : MachineMemOperand::MONone;
5420 
5421   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5422 
5423   // Registers used in building the DAG.
5424   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5425   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5426 
5427   // Offsets of descriptor members.
5428   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5429   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5430 
5431   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5432   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5433 
5434   // One load for the functions entry point address.
5435   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5436                                     Alignment, MMOFlags);
5437 
5438   // One for loading the TOC anchor for the module that contains the called
5439   // function.
5440   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5441   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5442   SDValue TOCPtr =
5443       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5444                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5445 
5446   // One for loading the environment pointer.
5447   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5448   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5449   SDValue LoadEnvPtr =
5450       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5451                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5452 
5453 
5454   // Then copy the newly loaded TOC anchor to the TOC pointer.
5455   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5456   Chain = TOCVal.getValue(0);
5457   Glue = TOCVal.getValue(1);
5458 
5459   // If the function call has an explicit 'nest' parameter, it takes the
5460   // place of the environment pointer.
5461   assert((!hasNest || !Subtarget.isAIXABI()) &&
5462          "Nest parameter is not supported on AIX.");
5463   if (!hasNest) {
5464     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5465     Chain = EnvVal.getValue(0);
5466     Glue = EnvVal.getValue(1);
5467   }
5468 
5469   // The rest of the indirect call sequence is the same as the non-descriptor
5470   // DAG.
5471   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5472 }
5473 
5474 static void
5475 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5476                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5477                   SelectionDAG &DAG,
5478                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5479                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5480                   const PPCSubtarget &Subtarget) {
5481   const bool IsPPC64 = Subtarget.isPPC64();
5482   // MVT for a general purpose register.
5483   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5484 
5485   // First operand is always the chain.
5486   Ops.push_back(Chain);
5487 
5488   // If it's a direct call pass the callee as the second operand.
5489   if (!CFlags.IsIndirect)
5490     Ops.push_back(Callee);
5491   else {
5492     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5493 
5494     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5495     // on the stack (this would have been done in `LowerCall_64SVR4` or
5496     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5497     // represents both the indirect branch and a load that restores the TOC
5498     // pointer from the linkage area. The operand for the TOC restore is an add
5499     // of the TOC save offset to the stack pointer. This must be the second
5500     // operand: after the chain input but before any other variadic arguments.
5501     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5502     // saved or used.
5503     if (isTOCSaveRestoreRequired(Subtarget)) {
5504       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5505 
5506       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5507       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5508       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5509       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5510       Ops.push_back(AddTOC);
5511     }
5512 
5513     // Add the register used for the environment pointer.
5514     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5515       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5516                                     RegVT));
5517 
5518 
5519     // Add CTR register as callee so a bctr can be emitted later.
5520     if (CFlags.IsTailCall)
5521       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5522   }
5523 
5524   // If this is a tail call add stack pointer delta.
5525   if (CFlags.IsTailCall)
5526     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5527 
5528   // Add argument registers to the end of the list so that they are known live
5529   // into the call.
5530   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5531     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5532                                   RegsToPass[i].second.getValueType()));
5533 
5534   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5535   // no way to mark dependencies as implicit here.
5536   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5537   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5538        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5539     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5540 
5541   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5542   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5543     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5544 
5545   // Add a register mask operand representing the call-preserved registers.
5546   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5547   const uint32_t *Mask =
5548       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5549   assert(Mask && "Missing call preserved mask for calling convention");
5550   Ops.push_back(DAG.getRegisterMask(Mask));
5551 
5552   // If the glue is valid, it is the last operand.
5553   if (Glue.getNode())
5554     Ops.push_back(Glue);
5555 }
5556 
5557 SDValue PPCTargetLowering::FinishCall(
5558     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5559     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5560     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5561     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5562     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5563 
5564   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5565       Subtarget.isAIXABI())
5566     setUsesTOCBasePtr(DAG);
5567 
5568   unsigned CallOpc =
5569       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5570                     Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5571 
5572   if (!CFlags.IsIndirect)
5573     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5574   else if (Subtarget.usesFunctionDescriptors())
5575     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5576                                   dl, CFlags.HasNest, Subtarget);
5577   else
5578     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5579 
5580   // Build the operand list for the call instruction.
5581   SmallVector<SDValue, 8> Ops;
5582   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5583                     SPDiff, Subtarget);
5584 
5585   // Emit tail call.
5586   if (CFlags.IsTailCall) {
5587     // Indirect tail call when using PC Relative calls do not have the same
5588     // constraints.
5589     assert(((Callee.getOpcode() == ISD::Register &&
5590              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5591             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5592             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5593             isa<ConstantSDNode>(Callee) ||
5594             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5595            "Expecting a global address, external symbol, absolute value, "
5596            "register or an indirect tail call when PC Relative calls are "
5597            "used.");
5598     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5599     assert(CallOpc == PPCISD::TC_RETURN &&
5600            "Unexpected call opcode for a tail call.");
5601     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5602     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5603   }
5604 
5605   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5606   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5607   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5608   Glue = Chain.getValue(1);
5609 
5610   // When performing tail call optimization the callee pops its arguments off
5611   // the stack. Account for this here so these bytes can be pushed back on in
5612   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5613   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5614                          getTargetMachine().Options.GuaranteedTailCallOpt)
5615                             ? NumBytes
5616                             : 0;
5617 
5618   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5619                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5620                              Glue, dl);
5621   Glue = Chain.getValue(1);
5622 
5623   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5624                          DAG, InVals);
5625 }
5626 
5627 SDValue
5628 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5629                              SmallVectorImpl<SDValue> &InVals) const {
5630   SelectionDAG &DAG                     = CLI.DAG;
5631   SDLoc &dl                             = CLI.DL;
5632   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5633   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5634   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5635   SDValue Chain                         = CLI.Chain;
5636   SDValue Callee                        = CLI.Callee;
5637   bool &isTailCall                      = CLI.IsTailCall;
5638   CallingConv::ID CallConv              = CLI.CallConv;
5639   bool isVarArg                         = CLI.IsVarArg;
5640   bool isPatchPoint                     = CLI.IsPatchPoint;
5641   const CallBase *CB                    = CLI.CB;
5642 
5643   if (isTailCall) {
5644     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5645       isTailCall = false;
5646     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5647       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5648           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5649     else
5650       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5651                                                      Ins, DAG);
5652     if (isTailCall) {
5653       ++NumTailCalls;
5654       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5655         ++NumSiblingCalls;
5656 
5657       // PC Relative calls no longer guarantee that the callee is a Global
5658       // Address Node. The callee could be an indirect tail call in which
5659       // case the SDValue for the callee could be a load (to load the address
5660       // of a function pointer) or it may be a register copy (to move the
5661       // address of the callee from a function parameter into a virtual
5662       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5663       assert((Subtarget.isUsingPCRelativeCalls() ||
5664               isa<GlobalAddressSDNode>(Callee)) &&
5665              "Callee should be an llvm::Function object.");
5666 
5667       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5668                         << "\nTCO callee: ");
5669       LLVM_DEBUG(Callee.dump());
5670     }
5671   }
5672 
5673   if (!isTailCall && CB && CB->isMustTailCall())
5674     report_fatal_error("failed to perform tail call elimination on a call "
5675                        "site marked musttail");
5676 
5677   // When long calls (i.e. indirect calls) are always used, calls are always
5678   // made via function pointer. If we have a function name, first translate it
5679   // into a pointer.
5680   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5681       !isTailCall)
5682     Callee = LowerGlobalAddress(Callee, DAG);
5683 
5684   CallFlags CFlags(
5685       CallConv, isTailCall, isVarArg, isPatchPoint,
5686       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5687       // hasNest
5688       Subtarget.is64BitELFABI() &&
5689           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5690       CLI.NoMerge);
5691 
5692   if (Subtarget.isAIXABI())
5693     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5694                          InVals, CB);
5695 
5696   assert(Subtarget.isSVR4ABI());
5697   if (Subtarget.isPPC64())
5698     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5699                             InVals, CB);
5700   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5701                           InVals, CB);
5702 }
5703 
5704 SDValue PPCTargetLowering::LowerCall_32SVR4(
5705     SDValue Chain, SDValue Callee, CallFlags CFlags,
5706     const SmallVectorImpl<ISD::OutputArg> &Outs,
5707     const SmallVectorImpl<SDValue> &OutVals,
5708     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5709     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5710     const CallBase *CB) const {
5711   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5712   // of the 32-bit SVR4 ABI stack frame layout.
5713 
5714   const CallingConv::ID CallConv = CFlags.CallConv;
5715   const bool IsVarArg = CFlags.IsVarArg;
5716   const bool IsTailCall = CFlags.IsTailCall;
5717 
5718   assert((CallConv == CallingConv::C ||
5719           CallConv == CallingConv::Cold ||
5720           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5721 
5722   const Align PtrAlign(4);
5723 
5724   MachineFunction &MF = DAG.getMachineFunction();
5725 
5726   // Mark this function as potentially containing a function that contains a
5727   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5728   // and restoring the callers stack pointer in this functions epilog. This is
5729   // done because by tail calling the called function might overwrite the value
5730   // in this function's (MF) stack pointer stack slot 0(SP).
5731   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5732       CallConv == CallingConv::Fast)
5733     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5734 
5735   // Count how many bytes are to be pushed on the stack, including the linkage
5736   // area, parameter list area and the part of the local variable space which
5737   // contains copies of aggregates which are passed by value.
5738 
5739   // Assign locations to all of the outgoing arguments.
5740   SmallVector<CCValAssign, 16> ArgLocs;
5741   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5742 
5743   // Reserve space for the linkage area on the stack.
5744   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5745                        PtrAlign);
5746   if (useSoftFloat())
5747     CCInfo.PreAnalyzeCallOperands(Outs);
5748 
5749   if (IsVarArg) {
5750     // Handle fixed and variable vector arguments differently.
5751     // Fixed vector arguments go into registers as long as registers are
5752     // available. Variable vector arguments always go into memory.
5753     unsigned NumArgs = Outs.size();
5754 
5755     for (unsigned i = 0; i != NumArgs; ++i) {
5756       MVT ArgVT = Outs[i].VT;
5757       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5758       bool Result;
5759 
5760       if (Outs[i].IsFixed) {
5761         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5762                                CCInfo);
5763       } else {
5764         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5765                                       ArgFlags, CCInfo);
5766       }
5767 
5768       if (Result) {
5769 #ifndef NDEBUG
5770         errs() << "Call operand #" << i << " has unhandled type "
5771              << EVT(ArgVT).getEVTString() << "\n";
5772 #endif
5773         llvm_unreachable(nullptr);
5774       }
5775     }
5776   } else {
5777     // All arguments are treated the same.
5778     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5779   }
5780   CCInfo.clearWasPPCF128();
5781 
5782   // Assign locations to all of the outgoing aggregate by value arguments.
5783   SmallVector<CCValAssign, 16> ByValArgLocs;
5784   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5785 
5786   // Reserve stack space for the allocations in CCInfo.
5787   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5788 
5789   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5790 
5791   // Size of the linkage area, parameter list area and the part of the local
5792   // space variable where copies of aggregates which are passed by value are
5793   // stored.
5794   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5795 
5796   // Calculate by how many bytes the stack has to be adjusted in case of tail
5797   // call optimization.
5798   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5799 
5800   // Adjust the stack pointer for the new arguments...
5801   // These operations are automatically eliminated by the prolog/epilog pass
5802   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5803   SDValue CallSeqStart = Chain;
5804 
5805   // Load the return address and frame pointer so it can be moved somewhere else
5806   // later.
5807   SDValue LROp, FPOp;
5808   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5809 
5810   // Set up a copy of the stack pointer for use loading and storing any
5811   // arguments that may not fit in the registers available for argument
5812   // passing.
5813   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5814 
5815   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5816   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5817   SmallVector<SDValue, 8> MemOpChains;
5818 
5819   bool seenFloatArg = false;
5820   // Walk the register/memloc assignments, inserting copies/loads.
5821   // i - Tracks the index into the list of registers allocated for the call
5822   // RealArgIdx - Tracks the index into the list of actual function arguments
5823   // j - Tracks the index into the list of byval arguments
5824   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5825        i != e;
5826        ++i, ++RealArgIdx) {
5827     CCValAssign &VA = ArgLocs[i];
5828     SDValue Arg = OutVals[RealArgIdx];
5829     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5830 
5831     if (Flags.isByVal()) {
5832       // Argument is an aggregate which is passed by value, thus we need to
5833       // create a copy of it in the local variable space of the current stack
5834       // frame (which is the stack frame of the caller) and pass the address of
5835       // this copy to the callee.
5836       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5837       CCValAssign &ByValVA = ByValArgLocs[j++];
5838       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5839 
5840       // Memory reserved in the local variable space of the callers stack frame.
5841       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5842 
5843       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5844       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5845                            StackPtr, PtrOff);
5846 
5847       // Create a copy of the argument in the local area of the current
5848       // stack frame.
5849       SDValue MemcpyCall =
5850         CreateCopyOfByValArgument(Arg, PtrOff,
5851                                   CallSeqStart.getNode()->getOperand(0),
5852                                   Flags, DAG, dl);
5853 
5854       // This must go outside the CALLSEQ_START..END.
5855       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5856                                                      SDLoc(MemcpyCall));
5857       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5858                              NewCallSeqStart.getNode());
5859       Chain = CallSeqStart = NewCallSeqStart;
5860 
5861       // Pass the address of the aggregate copy on the stack either in a
5862       // physical register or in the parameter list area of the current stack
5863       // frame to the callee.
5864       Arg = PtrOff;
5865     }
5866 
5867     // When useCRBits() is true, there can be i1 arguments.
5868     // It is because getRegisterType(MVT::i1) => MVT::i1,
5869     // and for other integer types getRegisterType() => MVT::i32.
5870     // Extend i1 and ensure callee will get i32.
5871     if (Arg.getValueType() == MVT::i1)
5872       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5873                         dl, MVT::i32, Arg);
5874 
5875     if (VA.isRegLoc()) {
5876       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5877       // Put argument in a physical register.
5878       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5879         bool IsLE = Subtarget.isLittleEndian();
5880         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5881                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5882         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5883         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5884                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5885         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5886                              SVal.getValue(0)));
5887       } else
5888         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5889     } else {
5890       // Put argument in the parameter list area of the current stack frame.
5891       assert(VA.isMemLoc());
5892       unsigned LocMemOffset = VA.getLocMemOffset();
5893 
5894       if (!IsTailCall) {
5895         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5896         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5897                              StackPtr, PtrOff);
5898 
5899         MemOpChains.push_back(
5900             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5901       } else {
5902         // Calculate and remember argument location.
5903         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5904                                  TailCallArguments);
5905       }
5906     }
5907   }
5908 
5909   if (!MemOpChains.empty())
5910     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5911 
5912   // Build a sequence of copy-to-reg nodes chained together with token chain
5913   // and flag operands which copy the outgoing args into the appropriate regs.
5914   SDValue InFlag;
5915   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5916     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5917                              RegsToPass[i].second, InFlag);
5918     InFlag = Chain.getValue(1);
5919   }
5920 
5921   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5922   // registers.
5923   if (IsVarArg) {
5924     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5925     SDValue Ops[] = { Chain, InFlag };
5926 
5927     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5928                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5929 
5930     InFlag = Chain.getValue(1);
5931   }
5932 
5933   if (IsTailCall)
5934     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5935                     TailCallArguments);
5936 
5937   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5938                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5939 }
5940 
5941 // Copy an argument into memory, being careful to do this outside the
5942 // call sequence for the call to which the argument belongs.
5943 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5944     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5945     SelectionDAG &DAG, const SDLoc &dl) const {
5946   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5947                         CallSeqStart.getNode()->getOperand(0),
5948                         Flags, DAG, dl);
5949   // The MEMCPY must go outside the CALLSEQ_START..END.
5950   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5951   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5952                                                  SDLoc(MemcpyCall));
5953   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5954                          NewCallSeqStart.getNode());
5955   return NewCallSeqStart;
5956 }
5957 
5958 SDValue PPCTargetLowering::LowerCall_64SVR4(
5959     SDValue Chain, SDValue Callee, CallFlags CFlags,
5960     const SmallVectorImpl<ISD::OutputArg> &Outs,
5961     const SmallVectorImpl<SDValue> &OutVals,
5962     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5963     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5964     const CallBase *CB) const {
5965   bool isELFv2ABI = Subtarget.isELFv2ABI();
5966   bool isLittleEndian = Subtarget.isLittleEndian();
5967   unsigned NumOps = Outs.size();
5968   bool IsSibCall = false;
5969   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5970 
5971   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5972   unsigned PtrByteSize = 8;
5973 
5974   MachineFunction &MF = DAG.getMachineFunction();
5975 
5976   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5977     IsSibCall = true;
5978 
5979   // Mark this function as potentially containing a function that contains a
5980   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5981   // and restoring the callers stack pointer in this functions epilog. This is
5982   // done because by tail calling the called function might overwrite the value
5983   // in this function's (MF) stack pointer stack slot 0(SP).
5984   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5985     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5986 
5987   assert(!(IsFastCall && CFlags.IsVarArg) &&
5988          "fastcc not supported on varargs functions");
5989 
5990   // Count how many bytes are to be pushed on the stack, including the linkage
5991   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5992   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5993   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5994   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5995   unsigned NumBytes = LinkageSize;
5996   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5997 
5998   static const MCPhysReg GPR[] = {
5999     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6000     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6001   };
6002   static const MCPhysReg VR[] = {
6003     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6004     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6005   };
6006 
6007   const unsigned NumGPRs = array_lengthof(GPR);
6008   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6009   const unsigned NumVRs  = array_lengthof(VR);
6010 
6011   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6012   // can be passed to the callee in registers.
6013   // For the fast calling convention, there is another check below.
6014   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6015   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6016   if (!HasParameterArea) {
6017     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6018     unsigned AvailableFPRs = NumFPRs;
6019     unsigned AvailableVRs = NumVRs;
6020     unsigned NumBytesTmp = NumBytes;
6021     for (unsigned i = 0; i != NumOps; ++i) {
6022       if (Outs[i].Flags.isNest()) continue;
6023       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6024                                  PtrByteSize, LinkageSize, ParamAreaSize,
6025                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6026         HasParameterArea = true;
6027     }
6028   }
6029 
6030   // When using the fast calling convention, we don't provide backing for
6031   // arguments that will be in registers.
6032   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6033 
6034   // Avoid allocating parameter area for fastcc functions if all the arguments
6035   // can be passed in the registers.
6036   if (IsFastCall)
6037     HasParameterArea = false;
6038 
6039   // Add up all the space actually used.
6040   for (unsigned i = 0; i != NumOps; ++i) {
6041     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6042     EVT ArgVT = Outs[i].VT;
6043     EVT OrigVT = Outs[i].ArgVT;
6044 
6045     if (Flags.isNest())
6046       continue;
6047 
6048     if (IsFastCall) {
6049       if (Flags.isByVal()) {
6050         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6051         if (NumGPRsUsed > NumGPRs)
6052           HasParameterArea = true;
6053       } else {
6054         switch (ArgVT.getSimpleVT().SimpleTy) {
6055         default: llvm_unreachable("Unexpected ValueType for argument!");
6056         case MVT::i1:
6057         case MVT::i32:
6058         case MVT::i64:
6059           if (++NumGPRsUsed <= NumGPRs)
6060             continue;
6061           break;
6062         case MVT::v4i32:
6063         case MVT::v8i16:
6064         case MVT::v16i8:
6065         case MVT::v2f64:
6066         case MVT::v2i64:
6067         case MVT::v1i128:
6068         case MVT::f128:
6069           if (++NumVRsUsed <= NumVRs)
6070             continue;
6071           break;
6072         case MVT::v4f32:
6073           if (++NumVRsUsed <= NumVRs)
6074             continue;
6075           break;
6076         case MVT::f32:
6077         case MVT::f64:
6078           if (++NumFPRsUsed <= NumFPRs)
6079             continue;
6080           break;
6081         }
6082         HasParameterArea = true;
6083       }
6084     }
6085 
6086     /* Respect alignment of argument on the stack.  */
6087     auto Alignement =
6088         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6089     NumBytes = alignTo(NumBytes, Alignement);
6090 
6091     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6092     if (Flags.isInConsecutiveRegsLast())
6093       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6094   }
6095 
6096   unsigned NumBytesActuallyUsed = NumBytes;
6097 
6098   // In the old ELFv1 ABI,
6099   // the prolog code of the callee may store up to 8 GPR argument registers to
6100   // the stack, allowing va_start to index over them in memory if its varargs.
6101   // Because we cannot tell if this is needed on the caller side, we have to
6102   // conservatively assume that it is needed.  As such, make sure we have at
6103   // least enough stack space for the caller to store the 8 GPRs.
6104   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6105   // really requires memory operands, e.g. a vararg function.
6106   if (HasParameterArea)
6107     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6108   else
6109     NumBytes = LinkageSize;
6110 
6111   // Tail call needs the stack to be aligned.
6112   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6113     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6114 
6115   int SPDiff = 0;
6116 
6117   // Calculate by how many bytes the stack has to be adjusted in case of tail
6118   // call optimization.
6119   if (!IsSibCall)
6120     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6121 
6122   // To protect arguments on the stack from being clobbered in a tail call,
6123   // force all the loads to happen before doing any other lowering.
6124   if (CFlags.IsTailCall)
6125     Chain = DAG.getStackArgumentTokenFactor(Chain);
6126 
6127   // Adjust the stack pointer for the new arguments...
6128   // These operations are automatically eliminated by the prolog/epilog pass
6129   if (!IsSibCall)
6130     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6131   SDValue CallSeqStart = Chain;
6132 
6133   // Load the return address and frame pointer so it can be move somewhere else
6134   // later.
6135   SDValue LROp, FPOp;
6136   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6137 
6138   // Set up a copy of the stack pointer for use loading and storing any
6139   // arguments that may not fit in the registers available for argument
6140   // passing.
6141   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6142 
6143   // Figure out which arguments are going to go in registers, and which in
6144   // memory.  Also, if this is a vararg function, floating point operations
6145   // must be stored to our stack, and loaded into integer regs as well, if
6146   // any integer regs are available for argument passing.
6147   unsigned ArgOffset = LinkageSize;
6148 
6149   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6150   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6151 
6152   SmallVector<SDValue, 8> MemOpChains;
6153   for (unsigned i = 0; i != NumOps; ++i) {
6154     SDValue Arg = OutVals[i];
6155     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6156     EVT ArgVT = Outs[i].VT;
6157     EVT OrigVT = Outs[i].ArgVT;
6158 
6159     // PtrOff will be used to store the current argument to the stack if a
6160     // register cannot be found for it.
6161     SDValue PtrOff;
6162 
6163     // We re-align the argument offset for each argument, except when using the
6164     // fast calling convention, when we need to make sure we do that only when
6165     // we'll actually use a stack slot.
6166     auto ComputePtrOff = [&]() {
6167       /* Respect alignment of argument on the stack.  */
6168       auto Alignment =
6169           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6170       ArgOffset = alignTo(ArgOffset, Alignment);
6171 
6172       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6173 
6174       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6175     };
6176 
6177     if (!IsFastCall) {
6178       ComputePtrOff();
6179 
6180       /* Compute GPR index associated with argument offset.  */
6181       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6182       GPR_idx = std::min(GPR_idx, NumGPRs);
6183     }
6184 
6185     // Promote integers to 64-bit values.
6186     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6187       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6188       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6189       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6190     }
6191 
6192     // FIXME memcpy is used way more than necessary.  Correctness first.
6193     // Note: "by value" is code for passing a structure by value, not
6194     // basic types.
6195     if (Flags.isByVal()) {
6196       // Note: Size includes alignment padding, so
6197       //   struct x { short a; char b; }
6198       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6199       // These are the proper values we need for right-justifying the
6200       // aggregate in a parameter register.
6201       unsigned Size = Flags.getByValSize();
6202 
6203       // An empty aggregate parameter takes up no storage and no
6204       // registers.
6205       if (Size == 0)
6206         continue;
6207 
6208       if (IsFastCall)
6209         ComputePtrOff();
6210 
6211       // All aggregates smaller than 8 bytes must be passed right-justified.
6212       if (Size==1 || Size==2 || Size==4) {
6213         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6214         if (GPR_idx != NumGPRs) {
6215           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6216                                         MachinePointerInfo(), VT);
6217           MemOpChains.push_back(Load.getValue(1));
6218           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6219 
6220           ArgOffset += PtrByteSize;
6221           continue;
6222         }
6223       }
6224 
6225       if (GPR_idx == NumGPRs && Size < 8) {
6226         SDValue AddPtr = PtrOff;
6227         if (!isLittleEndian) {
6228           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6229                                           PtrOff.getValueType());
6230           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6231         }
6232         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6233                                                           CallSeqStart,
6234                                                           Flags, DAG, dl);
6235         ArgOffset += PtrByteSize;
6236         continue;
6237       }
6238       // Copy the object to parameter save area if it can not be entirely passed
6239       // by registers.
6240       // FIXME: we only need to copy the parts which need to be passed in
6241       // parameter save area. For the parts passed by registers, we don't need
6242       // to copy them to the stack although we need to allocate space for them
6243       // in parameter save area.
6244       if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6245         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6246                                                           CallSeqStart,
6247                                                           Flags, DAG, dl);
6248 
6249       // When a register is available, pass a small aggregate right-justified.
6250       if (Size < 8 && GPR_idx != NumGPRs) {
6251         // The easiest way to get this right-justified in a register
6252         // is to copy the structure into the rightmost portion of a
6253         // local variable slot, then load the whole slot into the
6254         // register.
6255         // FIXME: The memcpy seems to produce pretty awful code for
6256         // small aggregates, particularly for packed ones.
6257         // FIXME: It would be preferable to use the slot in the
6258         // parameter save area instead of a new local variable.
6259         SDValue AddPtr = PtrOff;
6260         if (!isLittleEndian) {
6261           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6262           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6263         }
6264         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6265                                                           CallSeqStart,
6266                                                           Flags, DAG, dl);
6267 
6268         // Load the slot into the register.
6269         SDValue Load =
6270             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6271         MemOpChains.push_back(Load.getValue(1));
6272         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6273 
6274         // Done with this argument.
6275         ArgOffset += PtrByteSize;
6276         continue;
6277       }
6278 
6279       // For aggregates larger than PtrByteSize, copy the pieces of the
6280       // object that fit into registers from the parameter save area.
6281       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6282         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6283         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6284         if (GPR_idx != NumGPRs) {
6285           SDValue Load =
6286               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6287           MemOpChains.push_back(Load.getValue(1));
6288           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6289           ArgOffset += PtrByteSize;
6290         } else {
6291           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6292           break;
6293         }
6294       }
6295       continue;
6296     }
6297 
6298     switch (Arg.getSimpleValueType().SimpleTy) {
6299     default: llvm_unreachable("Unexpected ValueType for argument!");
6300     case MVT::i1:
6301     case MVT::i32:
6302     case MVT::i64:
6303       if (Flags.isNest()) {
6304         // The 'nest' parameter, if any, is passed in R11.
6305         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6306         break;
6307       }
6308 
6309       // These can be scalar arguments or elements of an integer array type
6310       // passed directly.  Clang may use those instead of "byval" aggregate
6311       // types to avoid forcing arguments to memory unnecessarily.
6312       if (GPR_idx != NumGPRs) {
6313         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6314       } else {
6315         if (IsFastCall)
6316           ComputePtrOff();
6317 
6318         assert(HasParameterArea &&
6319                "Parameter area must exist to pass an argument in memory.");
6320         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6321                          true, CFlags.IsTailCall, false, MemOpChains,
6322                          TailCallArguments, dl);
6323         if (IsFastCall)
6324           ArgOffset += PtrByteSize;
6325       }
6326       if (!IsFastCall)
6327         ArgOffset += PtrByteSize;
6328       break;
6329     case MVT::f32:
6330     case MVT::f64: {
6331       // These can be scalar arguments or elements of a float array type
6332       // passed directly.  The latter are used to implement ELFv2 homogenous
6333       // float aggregates.
6334 
6335       // Named arguments go into FPRs first, and once they overflow, the
6336       // remaining arguments go into GPRs and then the parameter save area.
6337       // Unnamed arguments for vararg functions always go to GPRs and
6338       // then the parameter save area.  For now, put all arguments to vararg
6339       // routines always in both locations (FPR *and* GPR or stack slot).
6340       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6341       bool NeededLoad = false;
6342 
6343       // First load the argument into the next available FPR.
6344       if (FPR_idx != NumFPRs)
6345         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6346 
6347       // Next, load the argument into GPR or stack slot if needed.
6348       if (!NeedGPROrStack)
6349         ;
6350       else if (GPR_idx != NumGPRs && !IsFastCall) {
6351         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6352         // once we support fp <-> gpr moves.
6353 
6354         // In the non-vararg case, this can only ever happen in the
6355         // presence of f32 array types, since otherwise we never run
6356         // out of FPRs before running out of GPRs.
6357         SDValue ArgVal;
6358 
6359         // Double values are always passed in a single GPR.
6360         if (Arg.getValueType() != MVT::f32) {
6361           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6362 
6363         // Non-array float values are extended and passed in a GPR.
6364         } else if (!Flags.isInConsecutiveRegs()) {
6365           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6366           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6367 
6368         // If we have an array of floats, we collect every odd element
6369         // together with its predecessor into one GPR.
6370         } else if (ArgOffset % PtrByteSize != 0) {
6371           SDValue Lo, Hi;
6372           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6373           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6374           if (!isLittleEndian)
6375             std::swap(Lo, Hi);
6376           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6377 
6378         // The final element, if even, goes into the first half of a GPR.
6379         } else if (Flags.isInConsecutiveRegsLast()) {
6380           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6381           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6382           if (!isLittleEndian)
6383             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6384                                  DAG.getConstant(32, dl, MVT::i32));
6385 
6386         // Non-final even elements are skipped; they will be handled
6387         // together the with subsequent argument on the next go-around.
6388         } else
6389           ArgVal = SDValue();
6390 
6391         if (ArgVal.getNode())
6392           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6393       } else {
6394         if (IsFastCall)
6395           ComputePtrOff();
6396 
6397         // Single-precision floating-point values are mapped to the
6398         // second (rightmost) word of the stack doubleword.
6399         if (Arg.getValueType() == MVT::f32 &&
6400             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6401           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6402           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6403         }
6404 
6405         assert(HasParameterArea &&
6406                "Parameter area must exist to pass an argument in memory.");
6407         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6408                          true, CFlags.IsTailCall, false, MemOpChains,
6409                          TailCallArguments, dl);
6410 
6411         NeededLoad = true;
6412       }
6413       // When passing an array of floats, the array occupies consecutive
6414       // space in the argument area; only round up to the next doubleword
6415       // at the end of the array.  Otherwise, each float takes 8 bytes.
6416       if (!IsFastCall || NeededLoad) {
6417         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6418                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6419         if (Flags.isInConsecutiveRegsLast())
6420           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6421       }
6422       break;
6423     }
6424     case MVT::v4f32:
6425     case MVT::v4i32:
6426     case MVT::v8i16:
6427     case MVT::v16i8:
6428     case MVT::v2f64:
6429     case MVT::v2i64:
6430     case MVT::v1i128:
6431     case MVT::f128:
6432       // These can be scalar arguments or elements of a vector array type
6433       // passed directly.  The latter are used to implement ELFv2 homogenous
6434       // vector aggregates.
6435 
6436       // For a varargs call, named arguments go into VRs or on the stack as
6437       // usual; unnamed arguments always go to the stack or the corresponding
6438       // GPRs when within range.  For now, we always put the value in both
6439       // locations (or even all three).
6440       if (CFlags.IsVarArg) {
6441         assert(HasParameterArea &&
6442                "Parameter area must exist if we have a varargs call.");
6443         // We could elide this store in the case where the object fits
6444         // entirely in R registers.  Maybe later.
6445         SDValue Store =
6446             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6447         MemOpChains.push_back(Store);
6448         if (VR_idx != NumVRs) {
6449           SDValue Load =
6450               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6451           MemOpChains.push_back(Load.getValue(1));
6452           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6453         }
6454         ArgOffset += 16;
6455         for (unsigned i=0; i<16; i+=PtrByteSize) {
6456           if (GPR_idx == NumGPRs)
6457             break;
6458           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6459                                    DAG.getConstant(i, dl, PtrVT));
6460           SDValue Load =
6461               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6462           MemOpChains.push_back(Load.getValue(1));
6463           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6464         }
6465         break;
6466       }
6467 
6468       // Non-varargs Altivec params go into VRs or on the stack.
6469       if (VR_idx != NumVRs) {
6470         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6471       } else {
6472         if (IsFastCall)
6473           ComputePtrOff();
6474 
6475         assert(HasParameterArea &&
6476                "Parameter area must exist to pass an argument in memory.");
6477         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6478                          true, CFlags.IsTailCall, true, MemOpChains,
6479                          TailCallArguments, dl);
6480         if (IsFastCall)
6481           ArgOffset += 16;
6482       }
6483 
6484       if (!IsFastCall)
6485         ArgOffset += 16;
6486       break;
6487     }
6488   }
6489 
6490   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6491          "mismatch in size of parameter area");
6492   (void)NumBytesActuallyUsed;
6493 
6494   if (!MemOpChains.empty())
6495     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6496 
6497   // Check if this is an indirect call (MTCTR/BCTRL).
6498   // See prepareDescriptorIndirectCall and buildCallOperands for more
6499   // information about calls through function pointers in the 64-bit SVR4 ABI.
6500   if (CFlags.IsIndirect) {
6501     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6502     // caller in the TOC save area.
6503     if (isTOCSaveRestoreRequired(Subtarget)) {
6504       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6505       // Load r2 into a virtual register and store it to the TOC save area.
6506       setUsesTOCBasePtr(DAG);
6507       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6508       // TOC save area offset.
6509       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6510       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6511       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6512       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6513                            MachinePointerInfo::getStack(
6514                                DAG.getMachineFunction(), TOCSaveOffset));
6515     }
6516     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6517     // This does not mean the MTCTR instruction must use R12; it's easier
6518     // to model this as an extra parameter, so do that.
6519     if (isELFv2ABI && !CFlags.IsPatchPoint)
6520       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6521   }
6522 
6523   // Build a sequence of copy-to-reg nodes chained together with token chain
6524   // and flag operands which copy the outgoing args into the appropriate regs.
6525   SDValue InFlag;
6526   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6527     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6528                              RegsToPass[i].second, InFlag);
6529     InFlag = Chain.getValue(1);
6530   }
6531 
6532   if (CFlags.IsTailCall && !IsSibCall)
6533     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6534                     TailCallArguments);
6535 
6536   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6537                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6538 }
6539 
6540 // Returns true when the shadow of a general purpose argument register
6541 // in the parameter save area is aligned to at least 'RequiredAlign'.
6542 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6543   assert(RequiredAlign.value() <= 16 &&
6544          "Required alignment greater than stack alignment.");
6545   switch (Reg) {
6546   default:
6547     report_fatal_error("called on invalid register.");
6548   case PPC::R5:
6549   case PPC::R9:
6550   case PPC::X3:
6551   case PPC::X5:
6552   case PPC::X7:
6553   case PPC::X9:
6554     // These registers are 16 byte aligned which is the most strict aligment
6555     // we can support.
6556     return true;
6557   case PPC::R3:
6558   case PPC::R7:
6559   case PPC::X4:
6560   case PPC::X6:
6561   case PPC::X8:
6562   case PPC::X10:
6563     // The shadow of these registers in the PSA is 8 byte aligned.
6564     return RequiredAlign <= 8;
6565   case PPC::R4:
6566   case PPC::R6:
6567   case PPC::R8:
6568   case PPC::R10:
6569     return RequiredAlign <= 4;
6570   }
6571 }
6572 
6573 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6574                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6575                    CCState &S) {
6576   AIXCCState &State = static_cast<AIXCCState &>(S);
6577   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6578       State.getMachineFunction().getSubtarget());
6579   const bool IsPPC64 = Subtarget.isPPC64();
6580   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6581   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6582 
6583   if (ValVT == MVT::f128)
6584     report_fatal_error("f128 is unimplemented on AIX.");
6585 
6586   if (ArgFlags.isNest())
6587     report_fatal_error("Nest arguments are unimplemented.");
6588 
6589   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6590                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6591                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6592   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6593                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6594                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6595 
6596   static const MCPhysReg VR[] = {// Vector registers.
6597                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6598                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6599                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6600 
6601   if (ArgFlags.isByVal()) {
6602     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6603       report_fatal_error("Pass-by-value arguments with alignment greater than "
6604                          "register width are not supported.");
6605 
6606     const unsigned ByValSize = ArgFlags.getByValSize();
6607 
6608     // An empty aggregate parameter takes up no storage and no registers,
6609     // but needs a MemLoc for a stack slot for the formal arguments side.
6610     if (ByValSize == 0) {
6611       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6612                                        State.getNextStackOffset(), RegVT,
6613                                        LocInfo));
6614       return false;
6615     }
6616 
6617     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6618     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6619     for (const unsigned E = Offset + StackSize; Offset < E;
6620          Offset += PtrAlign.value()) {
6621       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6622         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6623       else {
6624         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6625                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6626                                          LocInfo));
6627         break;
6628       }
6629     }
6630     return false;
6631   }
6632 
6633   // Arguments always reserve parameter save area.
6634   switch (ValVT.SimpleTy) {
6635   default:
6636     report_fatal_error("Unhandled value type for argument.");
6637   case MVT::i64:
6638     // i64 arguments should have been split to i32 for PPC32.
6639     assert(IsPPC64 && "PPC32 should have split i64 values.");
6640     LLVM_FALLTHROUGH;
6641   case MVT::i1:
6642   case MVT::i32: {
6643     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6644     // AIX integer arguments are always passed in register width.
6645     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6646       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6647                                   : CCValAssign::LocInfo::ZExt;
6648     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6649       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6650     else
6651       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6652 
6653     return false;
6654   }
6655   case MVT::f32:
6656   case MVT::f64: {
6657     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6658     const unsigned StoreSize = LocVT.getStoreSize();
6659     // Floats are always 4-byte aligned in the PSA on AIX.
6660     // This includes f64 in 64-bit mode for ABI compatibility.
6661     const unsigned Offset =
6662         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6663     unsigned FReg = State.AllocateReg(FPR);
6664     if (FReg)
6665       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6666 
6667     // Reserve and initialize GPRs or initialize the PSA as required.
6668     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6669       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6670         assert(FReg && "An FPR should be available when a GPR is reserved.");
6671         if (State.isVarArg()) {
6672           // Successfully reserved GPRs are only initialized for vararg calls.
6673           // Custom handling is required for:
6674           //   f64 in PPC32 needs to be split into 2 GPRs.
6675           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6676           State.addLoc(
6677               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6678         }
6679       } else {
6680         // If there are insufficient GPRs, the PSA needs to be initialized.
6681         // Initialization occurs even if an FPR was initialized for
6682         // compatibility with the AIX XL compiler. The full memory for the
6683         // argument will be initialized even if a prior word is saved in GPR.
6684         // A custom memLoc is used when the argument also passes in FPR so
6685         // that the callee handling can skip over it easily.
6686         State.addLoc(
6687             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6688                                              LocInfo)
6689                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6690         break;
6691       }
6692     }
6693 
6694     return false;
6695   }
6696   case MVT::v4f32:
6697   case MVT::v4i32:
6698   case MVT::v8i16:
6699   case MVT::v16i8:
6700   case MVT::v2i64:
6701   case MVT::v2f64:
6702   case MVT::v1i128: {
6703     const unsigned VecSize = 16;
6704     const Align VecAlign(VecSize);
6705 
6706     if (!State.isVarArg()) {
6707       // If there are vector registers remaining we don't consume any stack
6708       // space.
6709       if (unsigned VReg = State.AllocateReg(VR)) {
6710         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6711         return false;
6712       }
6713       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6714       // might be allocated in the portion of the PSA that is shadowed by the
6715       // GPRs.
6716       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6717       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6718       return false;
6719     }
6720 
6721     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6722     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6723 
6724     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6725     // Burn any underaligned registers and their shadowed stack space until
6726     // we reach the required alignment.
6727     while (NextRegIndex != GPRs.size() &&
6728            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6729       // Shadow allocate register and its stack shadow.
6730       unsigned Reg = State.AllocateReg(GPRs);
6731       State.AllocateStack(PtrSize, PtrAlign);
6732       assert(Reg && "Allocating register unexpectedly failed.");
6733       (void)Reg;
6734       NextRegIndex = State.getFirstUnallocated(GPRs);
6735     }
6736 
6737     // Vectors that are passed as fixed arguments are handled differently.
6738     // They are passed in VRs if any are available (unlike arguments passed
6739     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6740     // functions)
6741     if (State.isFixed(ValNo)) {
6742       if (unsigned VReg = State.AllocateReg(VR)) {
6743         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6744         // Shadow allocate GPRs and stack space even though we pass in a VR.
6745         for (unsigned I = 0; I != VecSize; I += PtrSize)
6746           State.AllocateReg(GPRs);
6747         State.AllocateStack(VecSize, VecAlign);
6748         return false;
6749       }
6750       // No vector registers remain so pass on the stack.
6751       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6752       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6753       return false;
6754     }
6755 
6756     // If all GPRS are consumed then we pass the argument fully on the stack.
6757     if (NextRegIndex == GPRs.size()) {
6758       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6759       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6760       return false;
6761     }
6762 
6763     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6764     // half of the argument, and then need to pass the remaining half on the
6765     // stack.
6766     if (GPRs[NextRegIndex] == PPC::R9) {
6767       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6768       State.addLoc(
6769           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6770 
6771       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6772       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6773       assert(FirstReg && SecondReg &&
6774              "Allocating R9 or R10 unexpectedly failed.");
6775       State.addLoc(
6776           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6777       State.addLoc(
6778           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6779       return false;
6780     }
6781 
6782     // We have enough GPRs to fully pass the vector argument, and we have
6783     // already consumed any underaligned registers. Start with the custom
6784     // MemLoc and then the custom RegLocs.
6785     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6786     State.addLoc(
6787         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6788     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6789       const unsigned Reg = State.AllocateReg(GPRs);
6790       assert(Reg && "Failed to allocated register for vararg vector argument");
6791       State.addLoc(
6792           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6793     }
6794     return false;
6795   }
6796   }
6797   return true;
6798 }
6799 
6800 // So far, this function is only used by LowerFormalArguments_AIX()
6801 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6802                                                     bool IsPPC64,
6803                                                     bool HasP8Vector,
6804                                                     bool HasVSX) {
6805   assert((IsPPC64 || SVT != MVT::i64) &&
6806          "i64 should have been split for 32-bit codegen.");
6807 
6808   switch (SVT) {
6809   default:
6810     report_fatal_error("Unexpected value type for formal argument");
6811   case MVT::i1:
6812   case MVT::i32:
6813   case MVT::i64:
6814     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6815   case MVT::f32:
6816     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6817   case MVT::f64:
6818     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6819   case MVT::v4f32:
6820   case MVT::v4i32:
6821   case MVT::v8i16:
6822   case MVT::v16i8:
6823   case MVT::v2i64:
6824   case MVT::v2f64:
6825   case MVT::v1i128:
6826     return &PPC::VRRCRegClass;
6827   }
6828 }
6829 
6830 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6831                                         SelectionDAG &DAG, SDValue ArgValue,
6832                                         MVT LocVT, const SDLoc &dl) {
6833   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6834   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6835 
6836   if (Flags.isSExt())
6837     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6838                            DAG.getValueType(ValVT));
6839   else if (Flags.isZExt())
6840     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6841                            DAG.getValueType(ValVT));
6842 
6843   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6844 }
6845 
6846 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6847   const unsigned LASize = FL->getLinkageSize();
6848 
6849   if (PPC::GPRCRegClass.contains(Reg)) {
6850     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6851            "Reg must be a valid argument register!");
6852     return LASize + 4 * (Reg - PPC::R3);
6853   }
6854 
6855   if (PPC::G8RCRegClass.contains(Reg)) {
6856     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6857            "Reg must be a valid argument register!");
6858     return LASize + 8 * (Reg - PPC::X3);
6859   }
6860 
6861   llvm_unreachable("Only general purpose registers expected.");
6862 }
6863 
6864 //   AIX ABI Stack Frame Layout:
6865 //
6866 //   Low Memory +--------------------------------------------+
6867 //   SP   +---> | Back chain                                 | ---+
6868 //        |     +--------------------------------------------+    |
6869 //        |     | Saved Condition Register                   |    |
6870 //        |     +--------------------------------------------+    |
6871 //        |     | Saved Linkage Register                     |    |
6872 //        |     +--------------------------------------------+    | Linkage Area
6873 //        |     | Reserved for compilers                     |    |
6874 //        |     +--------------------------------------------+    |
6875 //        |     | Reserved for binders                       |    |
6876 //        |     +--------------------------------------------+    |
6877 //        |     | Saved TOC pointer                          | ---+
6878 //        |     +--------------------------------------------+
6879 //        |     | Parameter save area                        |
6880 //        |     +--------------------------------------------+
6881 //        |     | Alloca space                               |
6882 //        |     +--------------------------------------------+
6883 //        |     | Local variable space                       |
6884 //        |     +--------------------------------------------+
6885 //        |     | Float/int conversion temporary             |
6886 //        |     +--------------------------------------------+
6887 //        |     | Save area for AltiVec registers            |
6888 //        |     +--------------------------------------------+
6889 //        |     | AltiVec alignment padding                  |
6890 //        |     +--------------------------------------------+
6891 //        |     | Save area for VRSAVE register              |
6892 //        |     +--------------------------------------------+
6893 //        |     | Save area for General Purpose registers    |
6894 //        |     +--------------------------------------------+
6895 //        |     | Save area for Floating Point registers     |
6896 //        |     +--------------------------------------------+
6897 //        +---- | Back chain                                 |
6898 // High Memory  +--------------------------------------------+
6899 //
6900 //  Specifications:
6901 //  AIX 7.2 Assembler Language Reference
6902 //  Subroutine linkage convention
6903 
6904 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6905     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6906     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6907     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6908 
6909   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6910           CallConv == CallingConv::Fast) &&
6911          "Unexpected calling convention!");
6912 
6913   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6914     report_fatal_error("Tail call support is unimplemented on AIX.");
6915 
6916   if (useSoftFloat())
6917     report_fatal_error("Soft float support is unimplemented on AIX.");
6918 
6919   const PPCSubtarget &Subtarget =
6920       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6921 
6922   const bool IsPPC64 = Subtarget.isPPC64();
6923   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6924 
6925   // Assign locations to all of the incoming arguments.
6926   SmallVector<CCValAssign, 16> ArgLocs;
6927   MachineFunction &MF = DAG.getMachineFunction();
6928   MachineFrameInfo &MFI = MF.getFrameInfo();
6929   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6930   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6931 
6932   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6933   // Reserve space for the linkage area on the stack.
6934   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6935   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6936   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6937 
6938   SmallVector<SDValue, 8> MemOps;
6939 
6940   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6941     CCValAssign &VA = ArgLocs[I++];
6942     MVT LocVT = VA.getLocVT();
6943     MVT ValVT = VA.getValVT();
6944     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6945     // For compatibility with the AIX XL compiler, the float args in the
6946     // parameter save area are initialized even if the argument is available
6947     // in register.  The caller is required to initialize both the register
6948     // and memory, however, the callee can choose to expect it in either.
6949     // The memloc is dismissed here because the argument is retrieved from
6950     // the register.
6951     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6952       continue;
6953 
6954     auto HandleMemLoc = [&]() {
6955       const unsigned LocSize = LocVT.getStoreSize();
6956       const unsigned ValSize = ValVT.getStoreSize();
6957       assert((ValSize <= LocSize) &&
6958              "Object size is larger than size of MemLoc");
6959       int CurArgOffset = VA.getLocMemOffset();
6960       // Objects are right-justified because AIX is big-endian.
6961       if (LocSize > ValSize)
6962         CurArgOffset += LocSize - ValSize;
6963       // Potential tail calls could cause overwriting of argument stack slots.
6964       const bool IsImmutable =
6965           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6966             (CallConv == CallingConv::Fast));
6967       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6968       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6969       SDValue ArgValue =
6970           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6971       InVals.push_back(ArgValue);
6972     };
6973 
6974     // Vector arguments to VaArg functions are passed both on the stack, and
6975     // in any available GPRs. Load the value from the stack and add the GPRs
6976     // as live ins.
6977     if (VA.isMemLoc() && VA.needsCustom()) {
6978       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6979       assert(isVarArg && "Only use custom memloc for vararg.");
6980       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6981       // matching custom RegLocs.
6982       const unsigned OriginalValNo = VA.getValNo();
6983       (void)OriginalValNo;
6984 
6985       auto HandleCustomVecRegLoc = [&]() {
6986         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6987                "Missing custom RegLoc.");
6988         VA = ArgLocs[I++];
6989         assert(VA.getValVT().isVector() &&
6990                "Unexpected Val type for custom RegLoc.");
6991         assert(VA.getValNo() == OriginalValNo &&
6992                "ValNo mismatch between custom MemLoc and RegLoc.");
6993         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6994         MF.addLiveIn(VA.getLocReg(),
6995                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6996                                        Subtarget.hasVSX()));
6997       };
6998 
6999       HandleMemLoc();
7000       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7001       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7002       // R10.
7003       HandleCustomVecRegLoc();
7004       HandleCustomVecRegLoc();
7005 
7006       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7007       // we passed the vector in R5, R6, R7 and R8.
7008       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7009         assert(!IsPPC64 &&
7010                "Only 2 custom RegLocs expected for 64-bit codegen.");
7011         HandleCustomVecRegLoc();
7012         HandleCustomVecRegLoc();
7013       }
7014 
7015       continue;
7016     }
7017 
7018     if (VA.isRegLoc()) {
7019       if (VA.getValVT().isScalarInteger())
7020         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7021       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7022         switch (VA.getValVT().SimpleTy) {
7023         default:
7024           report_fatal_error("Unhandled value type for argument.");
7025         case MVT::f32:
7026           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7027           break;
7028         case MVT::f64:
7029           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7030           break;
7031         }
7032       } else if (VA.getValVT().isVector()) {
7033         switch (VA.getValVT().SimpleTy) {
7034         default:
7035           report_fatal_error("Unhandled value type for argument.");
7036         case MVT::v16i8:
7037           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7038           break;
7039         case MVT::v8i16:
7040           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7041           break;
7042         case MVT::v4i32:
7043         case MVT::v2i64:
7044         case MVT::v1i128:
7045           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7046           break;
7047         case MVT::v4f32:
7048         case MVT::v2f64:
7049           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7050           break;
7051         }
7052       }
7053     }
7054 
7055     if (Flags.isByVal() && VA.isMemLoc()) {
7056       const unsigned Size =
7057           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7058                   PtrByteSize);
7059       const int FI = MF.getFrameInfo().CreateFixedObject(
7060           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7061           /* IsAliased */ true);
7062       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7063       InVals.push_back(FIN);
7064 
7065       continue;
7066     }
7067 
7068     if (Flags.isByVal()) {
7069       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7070 
7071       const MCPhysReg ArgReg = VA.getLocReg();
7072       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7073 
7074       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7075         report_fatal_error("Over aligned byvals not supported yet.");
7076 
7077       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7078       const int FI = MF.getFrameInfo().CreateFixedObject(
7079           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7080           /* IsAliased */ true);
7081       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7082       InVals.push_back(FIN);
7083 
7084       // Add live ins for all the RegLocs for the same ByVal.
7085       const TargetRegisterClass *RegClass =
7086           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7087 
7088       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7089                                                unsigned Offset) {
7090         const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7091         // Since the callers side has left justified the aggregate in the
7092         // register, we can simply store the entire register into the stack
7093         // slot.
7094         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7095         // The store to the fixedstack object is needed becuase accessing a
7096         // field of the ByVal will use a gep and load. Ideally we will optimize
7097         // to extracting the value from the register directly, and elide the
7098         // stores when the arguments address is not taken, but that will need to
7099         // be future work.
7100         SDValue Store = DAG.getStore(
7101             CopyFrom.getValue(1), dl, CopyFrom,
7102             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7103             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7104 
7105         MemOps.push_back(Store);
7106       };
7107 
7108       unsigned Offset = 0;
7109       HandleRegLoc(VA.getLocReg(), Offset);
7110       Offset += PtrByteSize;
7111       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7112            Offset += PtrByteSize) {
7113         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7114                "RegLocs should be for ByVal argument.");
7115 
7116         const CCValAssign RL = ArgLocs[I++];
7117         HandleRegLoc(RL.getLocReg(), Offset);
7118         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7119       }
7120 
7121       if (Offset != StackSize) {
7122         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7123                "Expected MemLoc for remaining bytes.");
7124         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7125         // Consume the MemLoc.The InVal has already been emitted, so nothing
7126         // more needs to be done.
7127         ++I;
7128       }
7129 
7130       continue;
7131     }
7132 
7133     if (VA.isRegLoc() && !VA.needsCustom()) {
7134       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7135       Register VReg =
7136           MF.addLiveIn(VA.getLocReg(),
7137                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7138                                          Subtarget.hasVSX()));
7139       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7140       if (ValVT.isScalarInteger() &&
7141           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7142         ArgValue =
7143             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7144       }
7145       InVals.push_back(ArgValue);
7146       continue;
7147     }
7148     if (VA.isMemLoc()) {
7149       HandleMemLoc();
7150       continue;
7151     }
7152   }
7153 
7154   // On AIX a minimum of 8 words is saved to the parameter save area.
7155   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7156   // Area that is at least reserved in the caller of this function.
7157   unsigned CallerReservedArea =
7158       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7159 
7160   // Set the size that is at least reserved in caller of this function. Tail
7161   // call optimized function's reserved stack space needs to be aligned so
7162   // that taking the difference between two stack areas will result in an
7163   // aligned stack.
7164   CallerReservedArea =
7165       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7166   FuncInfo->setMinReservedArea(CallerReservedArea);
7167 
7168   if (isVarArg) {
7169     FuncInfo->setVarArgsFrameIndex(
7170         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7171     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7172 
7173     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7174                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7175 
7176     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7177                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7178     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7179 
7180     // The fixed integer arguments of a variadic function are stored to the
7181     // VarArgsFrameIndex on the stack so that they may be loaded by
7182     // dereferencing the result of va_next.
7183     for (unsigned GPRIndex =
7184              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7185          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7186 
7187       const Register VReg =
7188           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7189                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7190 
7191       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7192       SDValue Store =
7193           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7194       MemOps.push_back(Store);
7195       // Increment the address for the next argument to store.
7196       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7197       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7198     }
7199   }
7200 
7201   if (!MemOps.empty())
7202     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7203 
7204   return Chain;
7205 }
7206 
7207 SDValue PPCTargetLowering::LowerCall_AIX(
7208     SDValue Chain, SDValue Callee, CallFlags CFlags,
7209     const SmallVectorImpl<ISD::OutputArg> &Outs,
7210     const SmallVectorImpl<SDValue> &OutVals,
7211     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7212     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7213     const CallBase *CB) const {
7214   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7215   // AIX ABI stack frame layout.
7216 
7217   assert((CFlags.CallConv == CallingConv::C ||
7218           CFlags.CallConv == CallingConv::Cold ||
7219           CFlags.CallConv == CallingConv::Fast) &&
7220          "Unexpected calling convention!");
7221 
7222   if (CFlags.IsPatchPoint)
7223     report_fatal_error("This call type is unimplemented on AIX.");
7224 
7225   const PPCSubtarget& Subtarget =
7226       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7227 
7228   MachineFunction &MF = DAG.getMachineFunction();
7229   SmallVector<CCValAssign, 16> ArgLocs;
7230   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7231                     *DAG.getContext());
7232 
7233   // Reserve space for the linkage save area (LSA) on the stack.
7234   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7235   //   [SP][CR][LR][2 x reserved][TOC].
7236   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7237   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7238   const bool IsPPC64 = Subtarget.isPPC64();
7239   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7240   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7241   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7242   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7243 
7244   // The prolog code of the callee may store up to 8 GPR argument registers to
7245   // the stack, allowing va_start to index over them in memory if the callee
7246   // is variadic.
7247   // Because we cannot tell if this is needed on the caller side, we have to
7248   // conservatively assume that it is needed.  As such, make sure we have at
7249   // least enough stack space for the caller to store the 8 GPRs.
7250   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7251   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7252                                      CCInfo.getNextStackOffset());
7253 
7254   // Adjust the stack pointer for the new arguments...
7255   // These operations are automatically eliminated by the prolog/epilog pass.
7256   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7257   SDValue CallSeqStart = Chain;
7258 
7259   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7260   SmallVector<SDValue, 8> MemOpChains;
7261 
7262   // Set up a copy of the stack pointer for loading and storing any
7263   // arguments that may not fit in the registers available for argument
7264   // passing.
7265   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7266                                    : DAG.getRegister(PPC::R1, MVT::i32);
7267 
7268   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7269     const unsigned ValNo = ArgLocs[I].getValNo();
7270     SDValue Arg = OutVals[ValNo];
7271     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7272 
7273     if (Flags.isByVal()) {
7274       const unsigned ByValSize = Flags.getByValSize();
7275 
7276       // Nothing to do for zero-sized ByVals on the caller side.
7277       if (!ByValSize) {
7278         ++I;
7279         continue;
7280       }
7281 
7282       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7283         return DAG.getExtLoad(
7284             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7285             (LoadOffset != 0)
7286                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7287                 : Arg,
7288             MachinePointerInfo(), VT);
7289       };
7290 
7291       unsigned LoadOffset = 0;
7292 
7293       // Initialize registers, which are fully occupied by the by-val argument.
7294       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7295         SDValue Load = GetLoad(PtrVT, LoadOffset);
7296         MemOpChains.push_back(Load.getValue(1));
7297         LoadOffset += PtrByteSize;
7298         const CCValAssign &ByValVA = ArgLocs[I++];
7299         assert(ByValVA.getValNo() == ValNo &&
7300                "Unexpected location for pass-by-value argument.");
7301         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7302       }
7303 
7304       if (LoadOffset == ByValSize)
7305         continue;
7306 
7307       // There must be one more loc to handle the remainder.
7308       assert(ArgLocs[I].getValNo() == ValNo &&
7309              "Expected additional location for by-value argument.");
7310 
7311       if (ArgLocs[I].isMemLoc()) {
7312         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7313         const CCValAssign &ByValVA = ArgLocs[I++];
7314         ISD::ArgFlagsTy MemcpyFlags = Flags;
7315         // Only memcpy the bytes that don't pass in register.
7316         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7317         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7318             (LoadOffset != 0)
7319                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7320                 : Arg,
7321             DAG.getObjectPtrOffset(dl, StackPtr,
7322                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7323             CallSeqStart, MemcpyFlags, DAG, dl);
7324         continue;
7325       }
7326 
7327       // Initialize the final register residue.
7328       // Any residue that occupies the final by-val arg register must be
7329       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7330       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7331       // 2 and 1 byte loads.
7332       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7333       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7334              "Unexpected register residue for by-value argument.");
7335       SDValue ResidueVal;
7336       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7337         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7338         const MVT VT =
7339             N == 1 ? MVT::i8
7340                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7341         SDValue Load = GetLoad(VT, LoadOffset);
7342         MemOpChains.push_back(Load.getValue(1));
7343         LoadOffset += N;
7344         Bytes += N;
7345 
7346         // By-val arguments are passed left-justfied in register.
7347         // Every load here needs to be shifted, otherwise a full register load
7348         // should have been used.
7349         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7350                "Unexpected load emitted during handling of pass-by-value "
7351                "argument.");
7352         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7353         EVT ShiftAmountTy =
7354             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7355         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7356         SDValue ShiftedLoad =
7357             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7358         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7359                                               ShiftedLoad)
7360                                 : ShiftedLoad;
7361       }
7362 
7363       const CCValAssign &ByValVA = ArgLocs[I++];
7364       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7365       continue;
7366     }
7367 
7368     CCValAssign &VA = ArgLocs[I++];
7369     const MVT LocVT = VA.getLocVT();
7370     const MVT ValVT = VA.getValVT();
7371 
7372     switch (VA.getLocInfo()) {
7373     default:
7374       report_fatal_error("Unexpected argument extension type.");
7375     case CCValAssign::Full:
7376       break;
7377     case CCValAssign::ZExt:
7378       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7379       break;
7380     case CCValAssign::SExt:
7381       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7382       break;
7383     }
7384 
7385     if (VA.isRegLoc() && !VA.needsCustom()) {
7386       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7387       continue;
7388     }
7389 
7390     // Vector arguments passed to VarArg functions need custom handling when
7391     // they are passed (at least partially) in GPRs.
7392     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7393       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7394       // Store value to its stack slot.
7395       SDValue PtrOff =
7396           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7397       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7398       SDValue Store =
7399           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7400       MemOpChains.push_back(Store);
7401       const unsigned OriginalValNo = VA.getValNo();
7402       // Then load the GPRs from the stack
7403       unsigned LoadOffset = 0;
7404       auto HandleCustomVecRegLoc = [&]() {
7405         assert(I != E && "Unexpected end of CCvalAssigns.");
7406         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7407                "Expected custom RegLoc.");
7408         CCValAssign RegVA = ArgLocs[I++];
7409         assert(RegVA.getValNo() == OriginalValNo &&
7410                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7411         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7412                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7413         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7414         MemOpChains.push_back(Load.getValue(1));
7415         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7416         LoadOffset += PtrByteSize;
7417       };
7418 
7419       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7420       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7421       // R10.
7422       HandleCustomVecRegLoc();
7423       HandleCustomVecRegLoc();
7424 
7425       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7426           ArgLocs[I].getValNo() == OriginalValNo) {
7427         assert(!IsPPC64 &&
7428                "Only 2 custom RegLocs expected for 64-bit codegen.");
7429         HandleCustomVecRegLoc();
7430         HandleCustomVecRegLoc();
7431       }
7432 
7433       continue;
7434     }
7435 
7436     if (VA.isMemLoc()) {
7437       SDValue PtrOff =
7438           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7439       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7440       MemOpChains.push_back(
7441           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7442 
7443       continue;
7444     }
7445 
7446     if (!ValVT.isFloatingPoint())
7447       report_fatal_error(
7448           "Unexpected register handling for calling convention.");
7449 
7450     // Custom handling is used for GPR initializations for vararg float
7451     // arguments.
7452     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7453            LocVT.isInteger() &&
7454            "Custom register handling only expected for VarArg.");
7455 
7456     SDValue ArgAsInt =
7457         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7458 
7459     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7460       // f32 in 32-bit GPR
7461       // f64 in 64-bit GPR
7462       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7463     else if (Arg.getValueType().getFixedSizeInBits() <
7464              LocVT.getFixedSizeInBits())
7465       // f32 in 64-bit GPR.
7466       RegsToPass.push_back(std::make_pair(
7467           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7468     else {
7469       // f64 in two 32-bit GPRs
7470       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7471       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7472              "Unexpected custom register for argument!");
7473       CCValAssign &GPR1 = VA;
7474       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7475                                      DAG.getConstant(32, dl, MVT::i8));
7476       RegsToPass.push_back(std::make_pair(
7477           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7478 
7479       if (I != E) {
7480         // If only 1 GPR was available, there will only be one custom GPR and
7481         // the argument will also pass in memory.
7482         CCValAssign &PeekArg = ArgLocs[I];
7483         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7484           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7485           CCValAssign &GPR2 = ArgLocs[I++];
7486           RegsToPass.push_back(std::make_pair(
7487               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7488         }
7489       }
7490     }
7491   }
7492 
7493   if (!MemOpChains.empty())
7494     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7495 
7496   // For indirect calls, we need to save the TOC base to the stack for
7497   // restoration after the call.
7498   if (CFlags.IsIndirect) {
7499     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7500     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7501     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7502     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7503     const unsigned TOCSaveOffset =
7504         Subtarget.getFrameLowering()->getTOCSaveOffset();
7505 
7506     setUsesTOCBasePtr(DAG);
7507     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7508     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7509     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7510     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7511     Chain = DAG.getStore(
7512         Val.getValue(1), dl, Val, AddPtr,
7513         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7514   }
7515 
7516   // Build a sequence of copy-to-reg nodes chained together with token chain
7517   // and flag operands which copy the outgoing args into the appropriate regs.
7518   SDValue InFlag;
7519   for (auto Reg : RegsToPass) {
7520     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7521     InFlag = Chain.getValue(1);
7522   }
7523 
7524   const int SPDiff = 0;
7525   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7526                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7527 }
7528 
7529 bool
7530 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7531                                   MachineFunction &MF, bool isVarArg,
7532                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7533                                   LLVMContext &Context) const {
7534   SmallVector<CCValAssign, 16> RVLocs;
7535   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7536   return CCInfo.CheckReturn(
7537       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7538                 ? RetCC_PPC_Cold
7539                 : RetCC_PPC);
7540 }
7541 
7542 SDValue
7543 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7544                                bool isVarArg,
7545                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7546                                const SmallVectorImpl<SDValue> &OutVals,
7547                                const SDLoc &dl, SelectionDAG &DAG) const {
7548   SmallVector<CCValAssign, 16> RVLocs;
7549   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7550                  *DAG.getContext());
7551   CCInfo.AnalyzeReturn(Outs,
7552                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7553                            ? RetCC_PPC_Cold
7554                            : RetCC_PPC);
7555 
7556   SDValue Flag;
7557   SmallVector<SDValue, 4> RetOps(1, Chain);
7558 
7559   // Copy the result values into the output registers.
7560   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7561     CCValAssign &VA = RVLocs[i];
7562     assert(VA.isRegLoc() && "Can only return in registers!");
7563 
7564     SDValue Arg = OutVals[RealResIdx];
7565 
7566     switch (VA.getLocInfo()) {
7567     default: llvm_unreachable("Unknown loc info!");
7568     case CCValAssign::Full: break;
7569     case CCValAssign::AExt:
7570       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7571       break;
7572     case CCValAssign::ZExt:
7573       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7574       break;
7575     case CCValAssign::SExt:
7576       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7577       break;
7578     }
7579     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7580       bool isLittleEndian = Subtarget.isLittleEndian();
7581       // Legalize ret f64 -> ret 2 x i32.
7582       SDValue SVal =
7583           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7584                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7585       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7586       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7587       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7588                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7589       Flag = Chain.getValue(1);
7590       VA = RVLocs[++i]; // skip ahead to next loc
7591       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7592     } else
7593       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7594     Flag = Chain.getValue(1);
7595     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7596   }
7597 
7598   RetOps[0] = Chain;  // Update chain.
7599 
7600   // Add the flag if we have it.
7601   if (Flag.getNode())
7602     RetOps.push_back(Flag);
7603 
7604   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7605 }
7606 
7607 SDValue
7608 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7609                                                 SelectionDAG &DAG) const {
7610   SDLoc dl(Op);
7611 
7612   // Get the correct type for integers.
7613   EVT IntVT = Op.getValueType();
7614 
7615   // Get the inputs.
7616   SDValue Chain = Op.getOperand(0);
7617   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7618   // Build a DYNAREAOFFSET node.
7619   SDValue Ops[2] = {Chain, FPSIdx};
7620   SDVTList VTs = DAG.getVTList(IntVT);
7621   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7622 }
7623 
7624 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7625                                              SelectionDAG &DAG) const {
7626   // When we pop the dynamic allocation we need to restore the SP link.
7627   SDLoc dl(Op);
7628 
7629   // Get the correct type for pointers.
7630   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7631 
7632   // Construct the stack pointer operand.
7633   bool isPPC64 = Subtarget.isPPC64();
7634   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7635   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7636 
7637   // Get the operands for the STACKRESTORE.
7638   SDValue Chain = Op.getOperand(0);
7639   SDValue SaveSP = Op.getOperand(1);
7640 
7641   // Load the old link SP.
7642   SDValue LoadLinkSP =
7643       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7644 
7645   // Restore the stack pointer.
7646   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7647 
7648   // Store the old link SP.
7649   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7650 }
7651 
7652 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7653   MachineFunction &MF = DAG.getMachineFunction();
7654   bool isPPC64 = Subtarget.isPPC64();
7655   EVT PtrVT = getPointerTy(MF.getDataLayout());
7656 
7657   // Get current frame pointer save index.  The users of this index will be
7658   // primarily DYNALLOC instructions.
7659   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7660   int RASI = FI->getReturnAddrSaveIndex();
7661 
7662   // If the frame pointer save index hasn't been defined yet.
7663   if (!RASI) {
7664     // Find out what the fix offset of the frame pointer save area.
7665     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7666     // Allocate the frame index for frame pointer save area.
7667     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7668     // Save the result.
7669     FI->setReturnAddrSaveIndex(RASI);
7670   }
7671   return DAG.getFrameIndex(RASI, PtrVT);
7672 }
7673 
7674 SDValue
7675 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7676   MachineFunction &MF = DAG.getMachineFunction();
7677   bool isPPC64 = Subtarget.isPPC64();
7678   EVT PtrVT = getPointerTy(MF.getDataLayout());
7679 
7680   // Get current frame pointer save index.  The users of this index will be
7681   // primarily DYNALLOC instructions.
7682   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7683   int FPSI = FI->getFramePointerSaveIndex();
7684 
7685   // If the frame pointer save index hasn't been defined yet.
7686   if (!FPSI) {
7687     // Find out what the fix offset of the frame pointer save area.
7688     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7689     // Allocate the frame index for frame pointer save area.
7690     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7691     // Save the result.
7692     FI->setFramePointerSaveIndex(FPSI);
7693   }
7694   return DAG.getFrameIndex(FPSI, PtrVT);
7695 }
7696 
7697 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7698                                                    SelectionDAG &DAG) const {
7699   MachineFunction &MF = DAG.getMachineFunction();
7700   // Get the inputs.
7701   SDValue Chain = Op.getOperand(0);
7702   SDValue Size  = Op.getOperand(1);
7703   SDLoc dl(Op);
7704 
7705   // Get the correct type for pointers.
7706   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7707   // Negate the size.
7708   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7709                                 DAG.getConstant(0, dl, PtrVT), Size);
7710   // Construct a node for the frame pointer save index.
7711   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7712   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7713   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7714   if (hasInlineStackProbe(MF))
7715     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7716   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7717 }
7718 
7719 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7720                                                      SelectionDAG &DAG) const {
7721   MachineFunction &MF = DAG.getMachineFunction();
7722 
7723   bool isPPC64 = Subtarget.isPPC64();
7724   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7725 
7726   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7727   return DAG.getFrameIndex(FI, PtrVT);
7728 }
7729 
7730 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7731                                                SelectionDAG &DAG) const {
7732   SDLoc DL(Op);
7733   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7734                      DAG.getVTList(MVT::i32, MVT::Other),
7735                      Op.getOperand(0), Op.getOperand(1));
7736 }
7737 
7738 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7739                                                 SelectionDAG &DAG) const {
7740   SDLoc DL(Op);
7741   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7742                      Op.getOperand(0), Op.getOperand(1));
7743 }
7744 
7745 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7746   if (Op.getValueType().isVector())
7747     return LowerVectorLoad(Op, DAG);
7748 
7749   assert(Op.getValueType() == MVT::i1 &&
7750          "Custom lowering only for i1 loads");
7751 
7752   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7753 
7754   SDLoc dl(Op);
7755   LoadSDNode *LD = cast<LoadSDNode>(Op);
7756 
7757   SDValue Chain = LD->getChain();
7758   SDValue BasePtr = LD->getBasePtr();
7759   MachineMemOperand *MMO = LD->getMemOperand();
7760 
7761   SDValue NewLD =
7762       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7763                      BasePtr, MVT::i8, MMO);
7764   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7765 
7766   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7767   return DAG.getMergeValues(Ops, dl);
7768 }
7769 
7770 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7771   if (Op.getOperand(1).getValueType().isVector())
7772     return LowerVectorStore(Op, DAG);
7773 
7774   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7775          "Custom lowering only for i1 stores");
7776 
7777   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7778 
7779   SDLoc dl(Op);
7780   StoreSDNode *ST = cast<StoreSDNode>(Op);
7781 
7782   SDValue Chain = ST->getChain();
7783   SDValue BasePtr = ST->getBasePtr();
7784   SDValue Value = ST->getValue();
7785   MachineMemOperand *MMO = ST->getMemOperand();
7786 
7787   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7788                       Value);
7789   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7790 }
7791 
7792 // FIXME: Remove this once the ANDI glue bug is fixed:
7793 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7794   assert(Op.getValueType() == MVT::i1 &&
7795          "Custom lowering only for i1 results");
7796 
7797   SDLoc DL(Op);
7798   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7799 }
7800 
7801 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7802                                                SelectionDAG &DAG) const {
7803 
7804   // Implements a vector truncate that fits in a vector register as a shuffle.
7805   // We want to legalize vector truncates down to where the source fits in
7806   // a vector register (and target is therefore smaller than vector register
7807   // size).  At that point legalization will try to custom lower the sub-legal
7808   // result and get here - where we can contain the truncate as a single target
7809   // operation.
7810 
7811   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7812   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7813   //
7814   // We will implement it for big-endian ordering as this (where x denotes
7815   // undefined):
7816   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7817   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7818   //
7819   // The same operation in little-endian ordering will be:
7820   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7821   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7822 
7823   EVT TrgVT = Op.getValueType();
7824   assert(TrgVT.isVector() && "Vector type expected.");
7825   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7826   EVT EltVT = TrgVT.getVectorElementType();
7827   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7828       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7829       !isPowerOf2_32(EltVT.getSizeInBits()))
7830     return SDValue();
7831 
7832   SDValue N1 = Op.getOperand(0);
7833   EVT SrcVT = N1.getValueType();
7834   unsigned SrcSize = SrcVT.getSizeInBits();
7835   if (SrcSize > 256 ||
7836       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7837       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7838     return SDValue();
7839   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7840     return SDValue();
7841 
7842   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7843   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7844 
7845   SDLoc DL(Op);
7846   SDValue Op1, Op2;
7847   if (SrcSize == 256) {
7848     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7849     EVT SplitVT =
7850         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7851     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7852     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7853                       DAG.getConstant(0, DL, VecIdxTy));
7854     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7855                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7856   }
7857   else {
7858     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7859     Op2 = DAG.getUNDEF(WideVT);
7860   }
7861 
7862   // First list the elements we want to keep.
7863   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7864   SmallVector<int, 16> ShuffV;
7865   if (Subtarget.isLittleEndian())
7866     for (unsigned i = 0; i < TrgNumElts; ++i)
7867       ShuffV.push_back(i * SizeMult);
7868   else
7869     for (unsigned i = 1; i <= TrgNumElts; ++i)
7870       ShuffV.push_back(i * SizeMult - 1);
7871 
7872   // Populate the remaining elements with undefs.
7873   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7874     // ShuffV.push_back(i + WideNumElts);
7875     ShuffV.push_back(WideNumElts + 1);
7876 
7877   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7878   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7879   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7880 }
7881 
7882 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7883 /// possible.
7884 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7885   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7886   EVT ResVT = Op.getValueType();
7887   EVT CmpVT = Op.getOperand(0).getValueType();
7888   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7889   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7890   SDLoc dl(Op);
7891 
7892   // Without power9-vector, we don't have native instruction for f128 comparison.
7893   // Following transformation to libcall is needed for setcc:
7894   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7895   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7896     SDValue Z = DAG.getSetCC(
7897         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7898         LHS, RHS, CC);
7899     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7900     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7901   }
7902 
7903   // Not FP, or using SPE? Not a fsel.
7904   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7905       Subtarget.hasSPE())
7906     return Op;
7907 
7908   SDNodeFlags Flags = Op.getNode()->getFlags();
7909 
7910   // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
7911   // presence of infinities.
7912   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7913     switch (CC) {
7914     default:
7915       break;
7916     case ISD::SETOGT:
7917     case ISD::SETGT:
7918       return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
7919     case ISD::SETOLT:
7920     case ISD::SETLT:
7921       return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
7922     }
7923   }
7924 
7925   // We might be able to do better than this under some circumstances, but in
7926   // general, fsel-based lowering of select is a finite-math-only optimization.
7927   // For more information, see section F.3 of the 2.06 ISA specification.
7928   // With ISA 3.0
7929   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7930       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7931     return Op;
7932 
7933   // If the RHS of the comparison is a 0.0, we don't need to do the
7934   // subtraction at all.
7935   SDValue Sel1;
7936   if (isFloatingPointZero(RHS))
7937     switch (CC) {
7938     default: break;       // SETUO etc aren't handled by fsel.
7939     case ISD::SETNE:
7940       std::swap(TV, FV);
7941       LLVM_FALLTHROUGH;
7942     case ISD::SETEQ:
7943       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7944         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7945       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7946       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7947         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7948       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7949                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7950     case ISD::SETULT:
7951     case ISD::SETLT:
7952       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7953       LLVM_FALLTHROUGH;
7954     case ISD::SETOGE:
7955     case ISD::SETGE:
7956       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7957         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7958       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7959     case ISD::SETUGT:
7960     case ISD::SETGT:
7961       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7962       LLVM_FALLTHROUGH;
7963     case ISD::SETOLE:
7964     case ISD::SETLE:
7965       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7966         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7967       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7968                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7969     }
7970 
7971   SDValue Cmp;
7972   switch (CC) {
7973   default: break;       // SETUO etc aren't handled by fsel.
7974   case ISD::SETNE:
7975     std::swap(TV, FV);
7976     LLVM_FALLTHROUGH;
7977   case ISD::SETEQ:
7978     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7979     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7980       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7981     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7982     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7983       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7984     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7985                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7986   case ISD::SETULT:
7987   case ISD::SETLT:
7988     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7989     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7990       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7991     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7992   case ISD::SETOGE:
7993   case ISD::SETGE:
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, TV, FV);
7998   case ISD::SETUGT:
7999   case ISD::SETGT:
8000     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, 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, FV, TV);
8004   case ISD::SETOLE:
8005   case ISD::SETLE:
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, TV, FV);
8010   }
8011   return Op;
8012 }
8013 
8014 static unsigned getPPCStrictOpcode(unsigned Opc) {
8015   switch (Opc) {
8016   default:
8017     llvm_unreachable("No strict version of this opcode!");
8018   case PPCISD::FCTIDZ:
8019     return PPCISD::STRICT_FCTIDZ;
8020   case PPCISD::FCTIWZ:
8021     return PPCISD::STRICT_FCTIWZ;
8022   case PPCISD::FCTIDUZ:
8023     return PPCISD::STRICT_FCTIDUZ;
8024   case PPCISD::FCTIWUZ:
8025     return PPCISD::STRICT_FCTIWUZ;
8026   case PPCISD::FCFID:
8027     return PPCISD::STRICT_FCFID;
8028   case PPCISD::FCFIDU:
8029     return PPCISD::STRICT_FCFIDU;
8030   case PPCISD::FCFIDS:
8031     return PPCISD::STRICT_FCFIDS;
8032   case PPCISD::FCFIDUS:
8033     return PPCISD::STRICT_FCFIDUS;
8034   }
8035 }
8036 
8037 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8038                               const PPCSubtarget &Subtarget) {
8039   SDLoc dl(Op);
8040   bool IsStrict = Op->isStrictFPOpcode();
8041   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8042                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8043 
8044   // TODO: Any other flags to propagate?
8045   SDNodeFlags Flags;
8046   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8047 
8048   // For strict nodes, source is the second operand.
8049   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8050   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8051   assert(Src.getValueType().isFloatingPoint());
8052   if (Src.getValueType() == MVT::f32) {
8053     if (IsStrict) {
8054       Src =
8055           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8056                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8057       Chain = Src.getValue(1);
8058     } else
8059       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8060   }
8061   SDValue Conv;
8062   unsigned Opc = ISD::DELETED_NODE;
8063   switch (Op.getSimpleValueType().SimpleTy) {
8064   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8065   case MVT::i32:
8066     Opc = IsSigned ? PPCISD::FCTIWZ
8067                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8068     break;
8069   case MVT::i64:
8070     assert((IsSigned || Subtarget.hasFPCVT()) &&
8071            "i64 FP_TO_UINT is supported only with FPCVT");
8072     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8073   }
8074   if (IsStrict) {
8075     Opc = getPPCStrictOpcode(Opc);
8076     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8077                        {Chain, Src}, Flags);
8078   } else {
8079     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8080   }
8081   return Conv;
8082 }
8083 
8084 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8085                                                SelectionDAG &DAG,
8086                                                const SDLoc &dl) const {
8087   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8088   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8089                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8090   bool IsStrict = Op->isStrictFPOpcode();
8091 
8092   // Convert the FP value to an int value through memory.
8093   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8094                   (IsSigned || Subtarget.hasFPCVT());
8095   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8096   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8097   MachinePointerInfo MPI =
8098       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8099 
8100   // Emit a store to the stack slot.
8101   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8102   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8103   if (i32Stack) {
8104     MachineFunction &MF = DAG.getMachineFunction();
8105     Alignment = Align(4);
8106     MachineMemOperand *MMO =
8107         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8108     SDValue Ops[] = { Chain, Tmp, FIPtr };
8109     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8110               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8111   } else
8112     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8113 
8114   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8115   // add in a bias on big endian.
8116   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8117     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8118                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8119     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8120   }
8121 
8122   RLI.Chain = Chain;
8123   RLI.Ptr = FIPtr;
8124   RLI.MPI = MPI;
8125   RLI.Alignment = Alignment;
8126 }
8127 
8128 /// Custom lowers floating point to integer conversions to use
8129 /// the direct move instructions available in ISA 2.07 to avoid the
8130 /// need for load/store combinations.
8131 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8132                                                     SelectionDAG &DAG,
8133                                                     const SDLoc &dl) const {
8134   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8135   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8136   if (Op->isStrictFPOpcode())
8137     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8138   else
8139     return Mov;
8140 }
8141 
8142 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8143                                           const SDLoc &dl) const {
8144   bool IsStrict = Op->isStrictFPOpcode();
8145   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8146                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8147   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8148   EVT SrcVT = Src.getValueType();
8149   EVT DstVT = Op.getValueType();
8150 
8151   // FP to INT conversions are legal for f128.
8152   if (SrcVT == MVT::f128)
8153     return Subtarget.hasP9Vector() ? Op : SDValue();
8154 
8155   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8156   // PPC (the libcall is not available).
8157   if (SrcVT == MVT::ppcf128) {
8158     if (DstVT == MVT::i32) {
8159       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8160       // set other fast-math flags to FP operations in both strict and
8161       // non-strict cases. (FP_TO_SINT, FSUB)
8162       SDNodeFlags Flags;
8163       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8164 
8165       if (IsSigned) {
8166         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8167                                  DAG.getIntPtrConstant(0, dl));
8168         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8169                                  DAG.getIntPtrConstant(1, dl));
8170 
8171         // Add the two halves of the long double in round-to-zero mode, and use
8172         // a smaller FP_TO_SINT.
8173         if (IsStrict) {
8174           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8175                                     DAG.getVTList(MVT::f64, MVT::Other),
8176                                     {Op.getOperand(0), Lo, Hi}, Flags);
8177           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8178                              DAG.getVTList(MVT::i32, MVT::Other),
8179                              {Res.getValue(1), Res}, Flags);
8180         } else {
8181           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8182           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8183         }
8184       } else {
8185         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8186         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8187         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8188         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8189         if (IsStrict) {
8190           // Sel = Src < 0x80000000
8191           // FltOfs = select Sel, 0.0, 0x80000000
8192           // IntOfs = select Sel, 0, 0x80000000
8193           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8194           SDValue Chain = Op.getOperand(0);
8195           EVT SetCCVT =
8196               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8197           EVT DstSetCCVT =
8198               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8199           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8200                                      Chain, true);
8201           Chain = Sel.getValue(1);
8202 
8203           SDValue FltOfs = DAG.getSelect(
8204               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8205           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8206 
8207           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8208                                     DAG.getVTList(SrcVT, MVT::Other),
8209                                     {Chain, Src, FltOfs}, Flags);
8210           Chain = Val.getValue(1);
8211           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8212                                      DAG.getVTList(DstVT, MVT::Other),
8213                                      {Chain, Val}, Flags);
8214           Chain = SInt.getValue(1);
8215           SDValue IntOfs = DAG.getSelect(
8216               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8217           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8218           return DAG.getMergeValues({Result, Chain}, dl);
8219         } else {
8220           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8221           // FIXME: generated code sucks.
8222           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8223           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8224           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8225           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8226           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8227         }
8228       }
8229     }
8230 
8231     return SDValue();
8232   }
8233 
8234   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8235     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8236 
8237   ReuseLoadInfo RLI;
8238   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8239 
8240   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8241                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8242 }
8243 
8244 // We're trying to insert a regular store, S, and then a load, L. If the
8245 // incoming value, O, is a load, we might just be able to have our load use the
8246 // address used by O. However, we don't know if anything else will store to
8247 // that address before we can load from it. To prevent this situation, we need
8248 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8249 // the same chain operand as O, we create a token factor from the chain results
8250 // of O and L, and we replace all uses of O's chain result with that token
8251 // factor (see spliceIntoChain below for this last part).
8252 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8253                                             ReuseLoadInfo &RLI,
8254                                             SelectionDAG &DAG,
8255                                             ISD::LoadExtType ET) const {
8256   // Conservatively skip reusing for constrained FP nodes.
8257   if (Op->isStrictFPOpcode())
8258     return false;
8259 
8260   SDLoc dl(Op);
8261   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8262                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8263   if (ET == ISD::NON_EXTLOAD &&
8264       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8265       isOperationLegalOrCustom(Op.getOpcode(),
8266                                Op.getOperand(0).getValueType())) {
8267 
8268     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8269     return true;
8270   }
8271 
8272   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8273   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8274       LD->isNonTemporal())
8275     return false;
8276   if (LD->getMemoryVT() != MemVT)
8277     return false;
8278 
8279   // If the result of the load is an illegal type, then we can't build a
8280   // valid chain for reuse since the legalised loads and token factor node that
8281   // ties the legalised loads together uses a different output chain then the
8282   // illegal load.
8283   if (!isTypeLegal(LD->getValueType(0)))
8284     return false;
8285 
8286   RLI.Ptr = LD->getBasePtr();
8287   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8288     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8289            "Non-pre-inc AM on PPC?");
8290     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8291                           LD->getOffset());
8292   }
8293 
8294   RLI.Chain = LD->getChain();
8295   RLI.MPI = LD->getPointerInfo();
8296   RLI.IsDereferenceable = LD->isDereferenceable();
8297   RLI.IsInvariant = LD->isInvariant();
8298   RLI.Alignment = LD->getAlign();
8299   RLI.AAInfo = LD->getAAInfo();
8300   RLI.Ranges = LD->getRanges();
8301 
8302   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8303   return true;
8304 }
8305 
8306 // Given the head of the old chain, ResChain, insert a token factor containing
8307 // it and NewResChain, and make users of ResChain now be users of that token
8308 // factor.
8309 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8310 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8311                                         SDValue NewResChain,
8312                                         SelectionDAG &DAG) const {
8313   if (!ResChain)
8314     return;
8315 
8316   SDLoc dl(NewResChain);
8317 
8318   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8319                            NewResChain, DAG.getUNDEF(MVT::Other));
8320   assert(TF.getNode() != NewResChain.getNode() &&
8321          "A new TF really is required here");
8322 
8323   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8324   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8325 }
8326 
8327 /// Analyze profitability of direct move
8328 /// prefer float load to int load plus direct move
8329 /// when there is no integer use of int load
8330 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8331   SDNode *Origin = Op.getOperand(0).getNode();
8332   if (Origin->getOpcode() != ISD::LOAD)
8333     return true;
8334 
8335   // If there is no LXSIBZX/LXSIHZX, like Power8,
8336   // prefer direct move if the memory size is 1 or 2 bytes.
8337   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8338   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8339     return true;
8340 
8341   for (SDNode::use_iterator UI = Origin->use_begin(),
8342                             UE = Origin->use_end();
8343        UI != UE; ++UI) {
8344 
8345     // Only look at the users of the loaded value.
8346     if (UI.getUse().get().getResNo() != 0)
8347       continue;
8348 
8349     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8350         UI->getOpcode() != ISD::UINT_TO_FP &&
8351         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8352         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8353       return true;
8354   }
8355 
8356   return false;
8357 }
8358 
8359 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8360                               const PPCSubtarget &Subtarget,
8361                               SDValue Chain = SDValue()) {
8362   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8363                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8364   SDLoc dl(Op);
8365 
8366   // TODO: Any other flags to propagate?
8367   SDNodeFlags Flags;
8368   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8369 
8370   // If we have FCFIDS, then use it when converting to single-precision.
8371   // Otherwise, convert to double-precision and then round.
8372   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8373   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8374                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8375   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8376   if (Op->isStrictFPOpcode()) {
8377     if (!Chain)
8378       Chain = Op.getOperand(0);
8379     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8380                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8381   } else
8382     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8383 }
8384 
8385 /// Custom lowers integer to floating point conversions to use
8386 /// the direct move instructions available in ISA 2.07 to avoid the
8387 /// need for load/store combinations.
8388 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8389                                                     SelectionDAG &DAG,
8390                                                     const SDLoc &dl) const {
8391   assert((Op.getValueType() == MVT::f32 ||
8392           Op.getValueType() == MVT::f64) &&
8393          "Invalid floating point type as target of conversion");
8394   assert(Subtarget.hasFPCVT() &&
8395          "Int to FP conversions with direct moves require FPCVT");
8396   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8397   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8398   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8399                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8400   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8401   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8402   return convertIntToFP(Op, Mov, DAG, Subtarget);
8403 }
8404 
8405 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8406 
8407   EVT VecVT = Vec.getValueType();
8408   assert(VecVT.isVector() && "Expected a vector type.");
8409   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8410 
8411   EVT EltVT = VecVT.getVectorElementType();
8412   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8413   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8414 
8415   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8416   SmallVector<SDValue, 16> Ops(NumConcat);
8417   Ops[0] = Vec;
8418   SDValue UndefVec = DAG.getUNDEF(VecVT);
8419   for (unsigned i = 1; i < NumConcat; ++i)
8420     Ops[i] = UndefVec;
8421 
8422   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8423 }
8424 
8425 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8426                                                 const SDLoc &dl) const {
8427   bool IsStrict = Op->isStrictFPOpcode();
8428   unsigned Opc = Op.getOpcode();
8429   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8430   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8431           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8432          "Unexpected conversion type");
8433   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8434          "Supports conversions to v2f64/v4f32 only.");
8435 
8436   // TODO: Any other flags to propagate?
8437   SDNodeFlags Flags;
8438   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8439 
8440   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8441   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8442 
8443   SDValue Wide = widenVec(DAG, Src, dl);
8444   EVT WideVT = Wide.getValueType();
8445   unsigned WideNumElts = WideVT.getVectorNumElements();
8446   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8447 
8448   SmallVector<int, 16> ShuffV;
8449   for (unsigned i = 0; i < WideNumElts; ++i)
8450     ShuffV.push_back(i + WideNumElts);
8451 
8452   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8453   int SaveElts = FourEltRes ? 4 : 2;
8454   if (Subtarget.isLittleEndian())
8455     for (int i = 0; i < SaveElts; i++)
8456       ShuffV[i * Stride] = i;
8457   else
8458     for (int i = 1; i <= SaveElts; i++)
8459       ShuffV[i * Stride - 1] = i - 1;
8460 
8461   SDValue ShuffleSrc2 =
8462       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8463   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8464 
8465   SDValue Extend;
8466   if (SignedConv) {
8467     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8468     EVT ExtVT = Src.getValueType();
8469     if (Subtarget.hasP9Altivec())
8470       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8471                                IntermediateVT.getVectorNumElements());
8472 
8473     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8474                          DAG.getValueType(ExtVT));
8475   } else
8476     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8477 
8478   if (IsStrict)
8479     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8480                        {Op.getOperand(0), Extend}, Flags);
8481 
8482   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8483 }
8484 
8485 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8486                                           SelectionDAG &DAG) const {
8487   SDLoc dl(Op);
8488   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8489                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8490   bool IsStrict = Op->isStrictFPOpcode();
8491   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8492   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8493 
8494   // TODO: Any other flags to propagate?
8495   SDNodeFlags Flags;
8496   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8497 
8498   EVT InVT = Src.getValueType();
8499   EVT OutVT = Op.getValueType();
8500   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8501       isOperationCustom(Op.getOpcode(), InVT))
8502     return LowerINT_TO_FPVector(Op, DAG, dl);
8503 
8504   // Conversions to f128 are legal.
8505   if (Op.getValueType() == MVT::f128)
8506     return Subtarget.hasP9Vector() ? Op : SDValue();
8507 
8508   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8509   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8510     return SDValue();
8511 
8512   if (Src.getValueType() == MVT::i1) {
8513     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8514                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8515                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8516     if (IsStrict)
8517       return DAG.getMergeValues({Sel, Chain}, dl);
8518     else
8519       return Sel;
8520   }
8521 
8522   // If we have direct moves, we can do all the conversion, skip the store/load
8523   // however, without FPCVT we can't do most conversions.
8524   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8525       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8526     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8527 
8528   assert((IsSigned || Subtarget.hasFPCVT()) &&
8529          "UINT_TO_FP is supported only with FPCVT");
8530 
8531   if (Src.getValueType() == MVT::i64) {
8532     SDValue SINT = Src;
8533     // When converting to single-precision, we actually need to convert
8534     // to double-precision first and then round to single-precision.
8535     // To avoid double-rounding effects during that operation, we have
8536     // to prepare the input operand.  Bits that might be truncated when
8537     // converting to double-precision are replaced by a bit that won't
8538     // be lost at this stage, but is below the single-precision rounding
8539     // position.
8540     //
8541     // However, if -enable-unsafe-fp-math is in effect, accept double
8542     // rounding to avoid the extra overhead.
8543     if (Op.getValueType() == MVT::f32 &&
8544         !Subtarget.hasFPCVT() &&
8545         !DAG.getTarget().Options.UnsafeFPMath) {
8546 
8547       // Twiddle input to make sure the low 11 bits are zero.  (If this
8548       // is the case, we are guaranteed the value will fit into the 53 bit
8549       // mantissa of an IEEE double-precision value without rounding.)
8550       // If any of those low 11 bits were not zero originally, make sure
8551       // bit 12 (value 2048) is set instead, so that the final rounding
8552       // to single-precision gets the correct result.
8553       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8554                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8555       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8556                           Round, DAG.getConstant(2047, dl, MVT::i64));
8557       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8558       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8559                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8560 
8561       // However, we cannot use that value unconditionally: if the magnitude
8562       // of the input value is small, the bit-twiddling we did above might
8563       // end up visibly changing the output.  Fortunately, in that case, we
8564       // don't need to twiddle bits since the original input will convert
8565       // exactly to double-precision floating-point already.  Therefore,
8566       // construct a conditional to use the original value if the top 11
8567       // bits are all sign-bit copies, and use the rounded value computed
8568       // above otherwise.
8569       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8570                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8571       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8572                          Cond, DAG.getConstant(1, dl, MVT::i64));
8573       Cond = DAG.getSetCC(
8574           dl,
8575           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8576           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8577 
8578       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8579     }
8580 
8581     ReuseLoadInfo RLI;
8582     SDValue Bits;
8583 
8584     MachineFunction &MF = DAG.getMachineFunction();
8585     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8586       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8587                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8588       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8589     } else if (Subtarget.hasLFIWAX() &&
8590                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8591       MachineMemOperand *MMO =
8592         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8593                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8594       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8595       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8596                                      DAG.getVTList(MVT::f64, MVT::Other),
8597                                      Ops, MVT::i32, MMO);
8598       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8599     } else if (Subtarget.hasFPCVT() &&
8600                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8601       MachineMemOperand *MMO =
8602         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8603                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8604       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8605       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8606                                      DAG.getVTList(MVT::f64, MVT::Other),
8607                                      Ops, MVT::i32, MMO);
8608       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8609     } else if (((Subtarget.hasLFIWAX() &&
8610                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8611                 (Subtarget.hasFPCVT() &&
8612                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8613                SINT.getOperand(0).getValueType() == MVT::i32) {
8614       MachineFrameInfo &MFI = MF.getFrameInfo();
8615       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8616 
8617       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8618       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8619 
8620       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8621                                    MachinePointerInfo::getFixedStack(
8622                                        DAG.getMachineFunction(), FrameIdx));
8623       Chain = Store;
8624 
8625       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8626              "Expected an i32 store");
8627 
8628       RLI.Ptr = FIdx;
8629       RLI.Chain = Chain;
8630       RLI.MPI =
8631           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8632       RLI.Alignment = Align(4);
8633 
8634       MachineMemOperand *MMO =
8635         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8636                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8637       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8638       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8639                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8640                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8641                                      Ops, MVT::i32, MMO);
8642       Chain = Bits.getValue(1);
8643     } else
8644       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8645 
8646     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8647     if (IsStrict)
8648       Chain = FP.getValue(1);
8649 
8650     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8651       if (IsStrict)
8652         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8653                          DAG.getVTList(MVT::f32, MVT::Other),
8654                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8655       else
8656         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8657                          DAG.getIntPtrConstant(0, dl));
8658     }
8659     return FP;
8660   }
8661 
8662   assert(Src.getValueType() == MVT::i32 &&
8663          "Unhandled INT_TO_FP type in custom expander!");
8664   // Since we only generate this in 64-bit mode, we can take advantage of
8665   // 64-bit registers.  In particular, sign extend the input value into the
8666   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8667   // then lfd it and fcfid it.
8668   MachineFunction &MF = DAG.getMachineFunction();
8669   MachineFrameInfo &MFI = MF.getFrameInfo();
8670   EVT PtrVT = getPointerTy(MF.getDataLayout());
8671 
8672   SDValue Ld;
8673   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8674     ReuseLoadInfo RLI;
8675     bool ReusingLoad;
8676     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8677       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8678       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8679 
8680       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8681                                    MachinePointerInfo::getFixedStack(
8682                                        DAG.getMachineFunction(), FrameIdx));
8683       Chain = Store;
8684 
8685       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8686              "Expected an i32 store");
8687 
8688       RLI.Ptr = FIdx;
8689       RLI.Chain = Chain;
8690       RLI.MPI =
8691           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8692       RLI.Alignment = Align(4);
8693     }
8694 
8695     MachineMemOperand *MMO =
8696       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8697                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8698     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8699     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8700                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8701                                  MVT::i32, MMO);
8702     Chain = Ld.getValue(1);
8703     if (ReusingLoad)
8704       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8705   } else {
8706     assert(Subtarget.isPPC64() &&
8707            "i32->FP without LFIWAX supported only on PPC64");
8708 
8709     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8710     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8711 
8712     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8713 
8714     // STD the extended value into the stack slot.
8715     SDValue Store = DAG.getStore(
8716         Chain, dl, Ext64, FIdx,
8717         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8718     Chain = Store;
8719 
8720     // Load the value as a double.
8721     Ld = DAG.getLoad(
8722         MVT::f64, dl, Chain, FIdx,
8723         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8724     Chain = Ld.getValue(1);
8725   }
8726 
8727   // FCFID it and return it.
8728   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8729   if (IsStrict)
8730     Chain = FP.getValue(1);
8731   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8732     if (IsStrict)
8733       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8734                        DAG.getVTList(MVT::f32, MVT::Other),
8735                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8736     else
8737       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8738                        DAG.getIntPtrConstant(0, dl));
8739   }
8740   return FP;
8741 }
8742 
8743 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8744                                             SelectionDAG &DAG) const {
8745   SDLoc dl(Op);
8746   /*
8747    The rounding mode is in bits 30:31 of FPSR, and has the following
8748    settings:
8749      00 Round to nearest
8750      01 Round to 0
8751      10 Round to +inf
8752      11 Round to -inf
8753 
8754   FLT_ROUNDS, on the other hand, expects the following:
8755     -1 Undefined
8756      0 Round to 0
8757      1 Round to nearest
8758      2 Round to +inf
8759      3 Round to -inf
8760 
8761   To perform the conversion, we do:
8762     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8763   */
8764 
8765   MachineFunction &MF = DAG.getMachineFunction();
8766   EVT VT = Op.getValueType();
8767   EVT PtrVT = getPointerTy(MF.getDataLayout());
8768 
8769   // Save FP Control Word to register
8770   SDValue Chain = Op.getOperand(0);
8771   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8772   Chain = MFFS.getValue(1);
8773 
8774   SDValue CWD;
8775   if (isTypeLegal(MVT::i64)) {
8776     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8777                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8778   } else {
8779     // Save FP register to stack slot
8780     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8781     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8782     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8783 
8784     // Load FP Control Word from low 32 bits of stack slot.
8785     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8786            "Stack slot adjustment is valid only on big endian subtargets!");
8787     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8788     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8789     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8790     Chain = CWD.getValue(1);
8791   }
8792 
8793   // Transform as necessary
8794   SDValue CWD1 =
8795     DAG.getNode(ISD::AND, dl, MVT::i32,
8796                 CWD, DAG.getConstant(3, dl, MVT::i32));
8797   SDValue CWD2 =
8798     DAG.getNode(ISD::SRL, dl, MVT::i32,
8799                 DAG.getNode(ISD::AND, dl, MVT::i32,
8800                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8801                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8802                             DAG.getConstant(3, dl, MVT::i32)),
8803                 DAG.getConstant(1, dl, MVT::i32));
8804 
8805   SDValue RetVal =
8806     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8807 
8808   RetVal =
8809       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8810                   dl, VT, RetVal);
8811 
8812   return DAG.getMergeValues({RetVal, Chain}, dl);
8813 }
8814 
8815 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8816   EVT VT = Op.getValueType();
8817   unsigned BitWidth = VT.getSizeInBits();
8818   SDLoc dl(Op);
8819   assert(Op.getNumOperands() == 3 &&
8820          VT == Op.getOperand(1).getValueType() &&
8821          "Unexpected SHL!");
8822 
8823   // Expand into a bunch of logical ops.  Note that these ops
8824   // depend on the PPC behavior for oversized shift amounts.
8825   SDValue Lo = Op.getOperand(0);
8826   SDValue Hi = Op.getOperand(1);
8827   SDValue Amt = Op.getOperand(2);
8828   EVT AmtVT = Amt.getValueType();
8829 
8830   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8831                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8832   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8833   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8834   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8835   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8836                              DAG.getConstant(-BitWidth, dl, AmtVT));
8837   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8838   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8839   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8840   SDValue OutOps[] = { OutLo, OutHi };
8841   return DAG.getMergeValues(OutOps, dl);
8842 }
8843 
8844 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8845   EVT VT = Op.getValueType();
8846   SDLoc dl(Op);
8847   unsigned BitWidth = VT.getSizeInBits();
8848   assert(Op.getNumOperands() == 3 &&
8849          VT == Op.getOperand(1).getValueType() &&
8850          "Unexpected SRL!");
8851 
8852   // Expand into a bunch of logical ops.  Note that these ops
8853   // depend on the PPC behavior for oversized shift amounts.
8854   SDValue Lo = Op.getOperand(0);
8855   SDValue Hi = Op.getOperand(1);
8856   SDValue Amt = Op.getOperand(2);
8857   EVT AmtVT = Amt.getValueType();
8858 
8859   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8860                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8861   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8862   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8863   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8864   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8865                              DAG.getConstant(-BitWidth, dl, AmtVT));
8866   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8867   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8868   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8869   SDValue OutOps[] = { OutLo, OutHi };
8870   return DAG.getMergeValues(OutOps, dl);
8871 }
8872 
8873 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8874   SDLoc dl(Op);
8875   EVT VT = Op.getValueType();
8876   unsigned BitWidth = VT.getSizeInBits();
8877   assert(Op.getNumOperands() == 3 &&
8878          VT == Op.getOperand(1).getValueType() &&
8879          "Unexpected SRA!");
8880 
8881   // Expand into a bunch of logical ops, followed by a select_cc.
8882   SDValue Lo = Op.getOperand(0);
8883   SDValue Hi = Op.getOperand(1);
8884   SDValue Amt = Op.getOperand(2);
8885   EVT AmtVT = Amt.getValueType();
8886 
8887   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8888                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8889   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8890   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8891   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8892   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8893                              DAG.getConstant(-BitWidth, dl, AmtVT));
8894   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8895   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8896   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8897                                   Tmp4, Tmp6, ISD::SETLE);
8898   SDValue OutOps[] = { OutLo, OutHi };
8899   return DAG.getMergeValues(OutOps, dl);
8900 }
8901 
8902 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8903                                             SelectionDAG &DAG) const {
8904   SDLoc dl(Op);
8905   EVT VT = Op.getValueType();
8906   unsigned BitWidth = VT.getSizeInBits();
8907 
8908   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8909   SDValue X = Op.getOperand(0);
8910   SDValue Y = Op.getOperand(1);
8911   SDValue Z = Op.getOperand(2);
8912   EVT AmtVT = Z.getValueType();
8913 
8914   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8915   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8916   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8917   // on PowerPC shift by BW being well defined.
8918   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8919                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8920   SDValue SubZ =
8921       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8922   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8923   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8924   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8925 }
8926 
8927 //===----------------------------------------------------------------------===//
8928 // Vector related lowering.
8929 //
8930 
8931 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8932 /// element size of SplatSize. Cast the result to VT.
8933 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8934                                       SelectionDAG &DAG, const SDLoc &dl) {
8935   static const MVT VTys[] = { // canonical VT to use for each size.
8936     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8937   };
8938 
8939   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8940 
8941   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8942   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8943     SplatSize = 1;
8944     Val = 0xFF;
8945   }
8946 
8947   EVT CanonicalVT = VTys[SplatSize-1];
8948 
8949   // Build a canonical splat for this value.
8950   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8951 }
8952 
8953 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8954 /// specified intrinsic ID.
8955 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8956                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8957   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8958   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8959                      DAG.getConstant(IID, dl, MVT::i32), Op);
8960 }
8961 
8962 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8963 /// specified intrinsic ID.
8964 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8965                                 SelectionDAG &DAG, const SDLoc &dl,
8966                                 EVT DestVT = MVT::Other) {
8967   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8968   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8969                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8970 }
8971 
8972 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8973 /// specified intrinsic ID.
8974 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8975                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8976                                 EVT DestVT = MVT::Other) {
8977   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8978   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8979                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8980 }
8981 
8982 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8983 /// amount.  The result has the specified value type.
8984 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8985                            SelectionDAG &DAG, const SDLoc &dl) {
8986   // Force LHS/RHS to be the right type.
8987   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8988   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8989 
8990   int Ops[16];
8991   for (unsigned i = 0; i != 16; ++i)
8992     Ops[i] = i + Amt;
8993   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8994   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8995 }
8996 
8997 /// Do we have an efficient pattern in a .td file for this node?
8998 ///
8999 /// \param V - pointer to the BuildVectorSDNode being matched
9000 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9001 ///
9002 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9003 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9004 /// the opposite is true (expansion is beneficial) are:
9005 /// - The node builds a vector out of integers that are not 32 or 64-bits
9006 /// - The node builds a vector out of constants
9007 /// - The node is a "load-and-splat"
9008 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9009 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9010                                             bool HasDirectMove,
9011                                             bool HasP8Vector) {
9012   EVT VecVT = V->getValueType(0);
9013   bool RightType = VecVT == MVT::v2f64 ||
9014     (HasP8Vector && VecVT == MVT::v4f32) ||
9015     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9016   if (!RightType)
9017     return false;
9018 
9019   bool IsSplat = true;
9020   bool IsLoad = false;
9021   SDValue Op0 = V->getOperand(0);
9022 
9023   // This function is called in a block that confirms the node is not a constant
9024   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9025   // different constants.
9026   if (V->isConstant())
9027     return false;
9028   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9029     if (V->getOperand(i).isUndef())
9030       return false;
9031     // We want to expand nodes that represent load-and-splat even if the
9032     // loaded value is a floating point truncation or conversion to int.
9033     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9034         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9035          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9036         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9037          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9038         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9039          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9040       IsLoad = true;
9041     // If the operands are different or the input is not a load and has more
9042     // uses than just this BV node, then it isn't a splat.
9043     if (V->getOperand(i) != Op0 ||
9044         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9045       IsSplat = false;
9046   }
9047   return !(IsSplat && IsLoad);
9048 }
9049 
9050 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9051 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9052 
9053   SDLoc dl(Op);
9054   SDValue Op0 = Op->getOperand(0);
9055 
9056   if ((Op.getValueType() != MVT::f128) ||
9057       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9058       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9059       (Op0.getOperand(1).getValueType() != MVT::i64))
9060     return SDValue();
9061 
9062   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9063                      Op0.getOperand(1));
9064 }
9065 
9066 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9067   const SDValue *InputLoad = &Op;
9068   if (InputLoad->getOpcode() == ISD::BITCAST)
9069     InputLoad = &InputLoad->getOperand(0);
9070   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9071       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9072     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9073     InputLoad = &InputLoad->getOperand(0);
9074   }
9075   if (InputLoad->getOpcode() != ISD::LOAD)
9076     return nullptr;
9077   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9078   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9079 }
9080 
9081 // Convert the argument APFloat to a single precision APFloat if there is no
9082 // loss in information during the conversion to single precision APFloat and the
9083 // resulting number is not a denormal number. Return true if successful.
9084 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9085   APFloat APFloatToConvert = ArgAPFloat;
9086   bool LosesInfo = true;
9087   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9088                            &LosesInfo);
9089   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9090   if (Success)
9091     ArgAPFloat = APFloatToConvert;
9092   return Success;
9093 }
9094 
9095 // Bitcast the argument APInt to a double and convert it to a single precision
9096 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9097 // argument if there is no loss in information during the conversion from
9098 // double to single precision APFloat and the resulting number is not a denormal
9099 // number. Return true if successful.
9100 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9101   double DpValue = ArgAPInt.bitsToDouble();
9102   APFloat APFloatDp(DpValue);
9103   bool Success = convertToNonDenormSingle(APFloatDp);
9104   if (Success)
9105     ArgAPInt = APFloatDp.bitcastToAPInt();
9106   return Success;
9107 }
9108 
9109 // Nondestructive check for convertTonNonDenormSingle.
9110 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9111   // Only convert if it loses info, since XXSPLTIDP should
9112   // handle the other case.
9113   APFloat APFloatToConvert = ArgAPFloat;
9114   bool LosesInfo = true;
9115   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9116                            &LosesInfo);
9117 
9118   return (!LosesInfo && !APFloatToConvert.isDenormal());
9119 }
9120 
9121 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9122                              unsigned &Opcode) {
9123   LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9124   if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9125     return false;
9126 
9127   EVT Ty = Op->getValueType(0);
9128   // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9129   // as we cannot handle extending loads for these types.
9130   if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9131       ISD::isNON_EXTLoad(InputNode))
9132     return true;
9133 
9134   EVT MemVT = InputNode->getMemoryVT();
9135   // For v8i16 and v16i8 types, extending loads can be handled as long as the
9136   // memory VT is the same vector element VT type.
9137   // The loads feeding into the v8i16 and v16i8 types will be extending because
9138   // scalar i8/i16 are not legal types.
9139   if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9140       (MemVT == Ty.getVectorElementType()))
9141     return true;
9142 
9143   if (Ty == MVT::v2i64) {
9144     // Check the extend type, when the input type is i32, and the output vector
9145     // type is v2i64.
9146     if (MemVT == MVT::i32) {
9147       if (ISD::isZEXTLoad(InputNode))
9148         Opcode = PPCISD::ZEXT_LD_SPLAT;
9149       if (ISD::isSEXTLoad(InputNode))
9150         Opcode = PPCISD::SEXT_LD_SPLAT;
9151     }
9152     return true;
9153   }
9154   return false;
9155 }
9156 
9157 // If this is a case we can't handle, return null and let the default
9158 // expansion code take care of it.  If we CAN select this case, and if it
9159 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9160 // this case more efficiently than a constant pool load, lower it to the
9161 // sequence of ops that should be used.
9162 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9163                                              SelectionDAG &DAG) const {
9164   SDLoc dl(Op);
9165   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9166   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9167 
9168   // Check if this is a splat of a constant value.
9169   APInt APSplatBits, APSplatUndef;
9170   unsigned SplatBitSize;
9171   bool HasAnyUndefs;
9172   bool BVNIsConstantSplat =
9173       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9174                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9175 
9176   // If it is a splat of a double, check if we can shrink it to a 32 bit
9177   // non-denormal float which when converted back to double gives us the same
9178   // double. This is to exploit the XXSPLTIDP instruction.
9179   // If we lose precision, we use XXSPLTI32DX.
9180   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9181       Subtarget.hasPrefixInstrs()) {
9182     // Check the type first to short-circuit so we don't modify APSplatBits if
9183     // this block isn't executed.
9184     if ((Op->getValueType(0) == MVT::v2f64) &&
9185         convertToNonDenormSingle(APSplatBits)) {
9186       SDValue SplatNode = DAG.getNode(
9187           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9188           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9189       return DAG.getBitcast(Op.getValueType(), SplatNode);
9190     } else {
9191       // We may lose precision, so we have to use XXSPLTI32DX.
9192 
9193       uint32_t Hi =
9194           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9195       uint32_t Lo =
9196           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9197       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9198 
9199       if (!Hi || !Lo)
9200         // If either load is 0, then we should generate XXLXOR to set to 0.
9201         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9202 
9203       if (Hi)
9204         SplatNode = DAG.getNode(
9205             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9206             DAG.getTargetConstant(0, dl, MVT::i32),
9207             DAG.getTargetConstant(Hi, dl, MVT::i32));
9208 
9209       if (Lo)
9210         SplatNode =
9211             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9212                         DAG.getTargetConstant(1, dl, MVT::i32),
9213                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9214 
9215       return DAG.getBitcast(Op.getValueType(), SplatNode);
9216     }
9217   }
9218 
9219   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9220     unsigned NewOpcode = PPCISD::LD_SPLAT;
9221 
9222     // Handle load-and-splat patterns as we have instructions that will do this
9223     // in one go.
9224     if (DAG.isSplatValue(Op, true) &&
9225         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9226       const SDValue *InputLoad = &Op.getOperand(0);
9227       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9228 
9229       // If the input load is an extending load, it will be an i32 -> i64
9230       // extending load and isValidSplatLoad() will update NewOpcode.
9231       unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9232       unsigned ElementSize =
9233           MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9234 
9235       assert(((ElementSize == 2 * MemorySize)
9236                   ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9237                      NewOpcode == PPCISD::SEXT_LD_SPLAT)
9238                   : (NewOpcode == PPCISD::LD_SPLAT)) &&
9239              "Unmatched element size and opcode!\n");
9240 
9241       // Checking for a single use of this load, we have to check for vector
9242       // width (128 bits) / ElementSize uses (since each operand of the
9243       // BUILD_VECTOR is a separate use of the value.
9244       unsigned NumUsesOfInputLD = 128 / ElementSize;
9245       for (SDValue BVInOp : Op->ops())
9246         if (BVInOp.isUndef())
9247           NumUsesOfInputLD--;
9248 
9249       // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9250       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9251       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9252       // 15", but funciton IsValidSplatLoad() now will only return true when
9253       // the data at index 0 is not nullptr. So we will not get into trouble for
9254       // these cases.
9255       //
9256       // case 1 - lfiwzx/lfiwax
9257       // 1.1: load result is i32 and is sign/zero extend to i64;
9258       // 1.2: build a v2i64 vector type with above loaded value;
9259       // 1.3: the vector has only one value at index 0, others are all undef;
9260       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9261       if (NumUsesOfInputLD == 1 &&
9262           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9263            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9264            Subtarget.hasLFIWAX()))
9265         return SDValue();
9266 
9267       // case 2 - lxvr[hb]x
9268       // 2.1: load result is at most i16;
9269       // 2.2: build a vector with above loaded value;
9270       // 2.3: the vector has only one value at index 0, others are all undef;
9271       // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9272       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9273           Subtarget.isISA3_1() && ElementSize <= 16)
9274         return SDValue();
9275 
9276       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9277       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9278           Subtarget.hasVSX()) {
9279         SDValue Ops[] = {
9280           LD->getChain(),    // Chain
9281           LD->getBasePtr(),  // Ptr
9282           DAG.getValueType(Op.getValueType()) // VT
9283         };
9284         SDValue LdSplt = DAG.getMemIntrinsicNode(
9285             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9286             LD->getMemoryVT(), LD->getMemOperand());
9287         // Replace all uses of the output chain of the original load with the
9288         // output chain of the new load.
9289         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9290                                       LdSplt.getValue(1));
9291         return LdSplt;
9292       }
9293     }
9294 
9295     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9296     // 32-bits can be lowered to VSX instructions under certain conditions.
9297     // Without VSX, there is no pattern more efficient than expanding the node.
9298     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9299         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9300                                         Subtarget.hasP8Vector()))
9301       return Op;
9302     return SDValue();
9303   }
9304 
9305   uint64_t SplatBits = APSplatBits.getZExtValue();
9306   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9307   unsigned SplatSize = SplatBitSize / 8;
9308 
9309   // First, handle single instruction cases.
9310 
9311   // All zeros?
9312   if (SplatBits == 0) {
9313     // Canonicalize all zero vectors to be v4i32.
9314     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9315       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9316       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9317     }
9318     return Op;
9319   }
9320 
9321   // We have XXSPLTIW for constant splats four bytes wide.
9322   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9323   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9324   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9325   // turned into a 4-byte splat of 0xABABABAB.
9326   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9327     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9328                                   Op.getValueType(), DAG, dl);
9329 
9330   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9331     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9332                                   dl);
9333 
9334   // We have XXSPLTIB for constant splats one byte wide.
9335   if (Subtarget.hasP9Vector() && SplatSize == 1)
9336     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9337                                   dl);
9338 
9339   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9340   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9341                     (32-SplatBitSize));
9342   if (SextVal >= -16 && SextVal <= 15)
9343     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9344                                   dl);
9345 
9346   // Two instruction sequences.
9347 
9348   // If this value is in the range [-32,30] and is even, use:
9349   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9350   // If this value is in the range [17,31] and is odd, use:
9351   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9352   // If this value is in the range [-31,-17] and is odd, use:
9353   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9354   // Note the last two are three-instruction sequences.
9355   if (SextVal >= -32 && SextVal <= 31) {
9356     // To avoid having these optimizations undone by constant folding,
9357     // we convert to a pseudo that will be expanded later into one of
9358     // the above forms.
9359     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9360     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9361               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9362     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9363     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9364     if (VT == Op.getValueType())
9365       return RetVal;
9366     else
9367       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9368   }
9369 
9370   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9371   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9372   // for fneg/fabs.
9373   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9374     // Make -1 and vspltisw -1:
9375     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9376 
9377     // Make the VSLW intrinsic, computing 0x8000_0000.
9378     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9379                                    OnesV, DAG, dl);
9380 
9381     // xor by OnesV to invert it.
9382     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9383     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9384   }
9385 
9386   // Check to see if this is a wide variety of vsplti*, binop self cases.
9387   static const signed char SplatCsts[] = {
9388     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9389     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9390   };
9391 
9392   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9393     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9394     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9395     int i = SplatCsts[idx];
9396 
9397     // Figure out what shift amount will be used by altivec if shifted by i in
9398     // this splat size.
9399     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9400 
9401     // vsplti + shl self.
9402     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9403       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9404       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9405         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9406         Intrinsic::ppc_altivec_vslw
9407       };
9408       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9409       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9410     }
9411 
9412     // vsplti + srl self.
9413     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9414       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9415       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9416         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9417         Intrinsic::ppc_altivec_vsrw
9418       };
9419       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9420       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9421     }
9422 
9423     // vsplti + rol self.
9424     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9425                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9426       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9427       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9428         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9429         Intrinsic::ppc_altivec_vrlw
9430       };
9431       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9432       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9433     }
9434 
9435     // t = vsplti c, result = vsldoi t, t, 1
9436     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9437       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9438       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9439       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9440     }
9441     // t = vsplti c, result = vsldoi t, t, 2
9442     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9443       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9444       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9445       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9446     }
9447     // t = vsplti c, result = vsldoi t, t, 3
9448     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9449       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9450       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9451       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9452     }
9453   }
9454 
9455   return SDValue();
9456 }
9457 
9458 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9459 /// the specified operations to build the shuffle.
9460 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9461                                       SDValue RHS, SelectionDAG &DAG,
9462                                       const SDLoc &dl) {
9463   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9464   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9465   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9466 
9467   enum {
9468     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9469     OP_VMRGHW,
9470     OP_VMRGLW,
9471     OP_VSPLTISW0,
9472     OP_VSPLTISW1,
9473     OP_VSPLTISW2,
9474     OP_VSPLTISW3,
9475     OP_VSLDOI4,
9476     OP_VSLDOI8,
9477     OP_VSLDOI12
9478   };
9479 
9480   if (OpNum == OP_COPY) {
9481     if (LHSID == (1*9+2)*9+3) return LHS;
9482     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9483     return RHS;
9484   }
9485 
9486   SDValue OpLHS, OpRHS;
9487   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9488   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9489 
9490   int ShufIdxs[16];
9491   switch (OpNum) {
9492   default: llvm_unreachable("Unknown i32 permute!");
9493   case OP_VMRGHW:
9494     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9495     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9496     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9497     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9498     break;
9499   case OP_VMRGLW:
9500     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9501     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9502     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9503     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9504     break;
9505   case OP_VSPLTISW0:
9506     for (unsigned i = 0; i != 16; ++i)
9507       ShufIdxs[i] = (i&3)+0;
9508     break;
9509   case OP_VSPLTISW1:
9510     for (unsigned i = 0; i != 16; ++i)
9511       ShufIdxs[i] = (i&3)+4;
9512     break;
9513   case OP_VSPLTISW2:
9514     for (unsigned i = 0; i != 16; ++i)
9515       ShufIdxs[i] = (i&3)+8;
9516     break;
9517   case OP_VSPLTISW3:
9518     for (unsigned i = 0; i != 16; ++i)
9519       ShufIdxs[i] = (i&3)+12;
9520     break;
9521   case OP_VSLDOI4:
9522     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9523   case OP_VSLDOI8:
9524     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9525   case OP_VSLDOI12:
9526     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9527   }
9528   EVT VT = OpLHS.getValueType();
9529   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9530   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9531   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9532   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9533 }
9534 
9535 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9536 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9537 /// SDValue.
9538 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9539                                            SelectionDAG &DAG) const {
9540   const unsigned BytesInVector = 16;
9541   bool IsLE = Subtarget.isLittleEndian();
9542   SDLoc dl(N);
9543   SDValue V1 = N->getOperand(0);
9544   SDValue V2 = N->getOperand(1);
9545   unsigned ShiftElts = 0, InsertAtByte = 0;
9546   bool Swap = false;
9547 
9548   // Shifts required to get the byte we want at element 7.
9549   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9550                                    0, 15, 14, 13, 12, 11, 10, 9};
9551   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9552                                 1, 2,  3,  4,  5,  6,  7,  8};
9553 
9554   ArrayRef<int> Mask = N->getMask();
9555   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9556 
9557   // For each mask element, find out if we're just inserting something
9558   // from V2 into V1 or vice versa.
9559   // Possible permutations inserting an element from V2 into V1:
9560   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9561   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9562   //   ...
9563   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9564   // Inserting from V1 into V2 will be similar, except mask range will be
9565   // [16,31].
9566 
9567   bool FoundCandidate = false;
9568   // If both vector operands for the shuffle are the same vector, the mask
9569   // will contain only elements from the first one and the second one will be
9570   // undef.
9571   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9572   // Go through the mask of half-words to find an element that's being moved
9573   // from one vector to the other.
9574   for (unsigned i = 0; i < BytesInVector; ++i) {
9575     unsigned CurrentElement = Mask[i];
9576     // If 2nd operand is undefined, we should only look for element 7 in the
9577     // Mask.
9578     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9579       continue;
9580 
9581     bool OtherElementsInOrder = true;
9582     // Examine the other elements in the Mask to see if they're in original
9583     // order.
9584     for (unsigned j = 0; j < BytesInVector; ++j) {
9585       if (j == i)
9586         continue;
9587       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9588       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9589       // in which we always assume we're always picking from the 1st operand.
9590       int MaskOffset =
9591           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9592       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9593         OtherElementsInOrder = false;
9594         break;
9595       }
9596     }
9597     // If other elements are in original order, we record the number of shifts
9598     // we need to get the element we want into element 7. Also record which byte
9599     // in the vector we should insert into.
9600     if (OtherElementsInOrder) {
9601       // If 2nd operand is undefined, we assume no shifts and no swapping.
9602       if (V2.isUndef()) {
9603         ShiftElts = 0;
9604         Swap = false;
9605       } else {
9606         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9607         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9608                          : BigEndianShifts[CurrentElement & 0xF];
9609         Swap = CurrentElement < BytesInVector;
9610       }
9611       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9612       FoundCandidate = true;
9613       break;
9614     }
9615   }
9616 
9617   if (!FoundCandidate)
9618     return SDValue();
9619 
9620   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9621   // optionally with VECSHL if shift is required.
9622   if (Swap)
9623     std::swap(V1, V2);
9624   if (V2.isUndef())
9625     V2 = V1;
9626   if (ShiftElts) {
9627     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9628                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9629     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9630                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9631   }
9632   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9633                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9634 }
9635 
9636 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9637 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9638 /// SDValue.
9639 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9640                                            SelectionDAG &DAG) const {
9641   const unsigned NumHalfWords = 8;
9642   const unsigned BytesInVector = NumHalfWords * 2;
9643   // Check that the shuffle is on half-words.
9644   if (!isNByteElemShuffleMask(N, 2, 1))
9645     return SDValue();
9646 
9647   bool IsLE = Subtarget.isLittleEndian();
9648   SDLoc dl(N);
9649   SDValue V1 = N->getOperand(0);
9650   SDValue V2 = N->getOperand(1);
9651   unsigned ShiftElts = 0, InsertAtByte = 0;
9652   bool Swap = false;
9653 
9654   // Shifts required to get the half-word we want at element 3.
9655   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9656   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9657 
9658   uint32_t Mask = 0;
9659   uint32_t OriginalOrderLow = 0x1234567;
9660   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9661   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9662   // 32-bit space, only need 4-bit nibbles per element.
9663   for (unsigned i = 0; i < NumHalfWords; ++i) {
9664     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9665     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9666   }
9667 
9668   // For each mask element, find out if we're just inserting something
9669   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9670   // from V2 into V1:
9671   //   X, 1, 2, 3, 4, 5, 6, 7
9672   //   0, X, 2, 3, 4, 5, 6, 7
9673   //   0, 1, X, 3, 4, 5, 6, 7
9674   //   0, 1, 2, X, 4, 5, 6, 7
9675   //   0, 1, 2, 3, X, 5, 6, 7
9676   //   0, 1, 2, 3, 4, X, 6, 7
9677   //   0, 1, 2, 3, 4, 5, X, 7
9678   //   0, 1, 2, 3, 4, 5, 6, X
9679   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9680 
9681   bool FoundCandidate = false;
9682   // Go through the mask of half-words to find an element that's being moved
9683   // from one vector to the other.
9684   for (unsigned i = 0; i < NumHalfWords; ++i) {
9685     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9686     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9687     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9688     uint32_t TargetOrder = 0x0;
9689 
9690     // If both vector operands for the shuffle are the same vector, the mask
9691     // will contain only elements from the first one and the second one will be
9692     // undef.
9693     if (V2.isUndef()) {
9694       ShiftElts = 0;
9695       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9696       TargetOrder = OriginalOrderLow;
9697       Swap = false;
9698       // Skip if not the correct element or mask of other elements don't equal
9699       // to our expected order.
9700       if (MaskOneElt == VINSERTHSrcElem &&
9701           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9702         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9703         FoundCandidate = true;
9704         break;
9705       }
9706     } else { // If both operands are defined.
9707       // Target order is [8,15] if the current mask is between [0,7].
9708       TargetOrder =
9709           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9710       // Skip if mask of other elements don't equal our expected order.
9711       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9712         // We only need the last 3 bits for the number of shifts.
9713         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9714                          : BigEndianShifts[MaskOneElt & 0x7];
9715         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9716         Swap = MaskOneElt < NumHalfWords;
9717         FoundCandidate = true;
9718         break;
9719       }
9720     }
9721   }
9722 
9723   if (!FoundCandidate)
9724     return SDValue();
9725 
9726   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9727   // optionally with VECSHL if shift is required.
9728   if (Swap)
9729     std::swap(V1, V2);
9730   if (V2.isUndef())
9731     V2 = V1;
9732   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9733   if (ShiftElts) {
9734     // Double ShiftElts because we're left shifting on v16i8 type.
9735     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9736                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9737     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9738     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9739                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9740     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9741   }
9742   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9743   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9744                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9745   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9746 }
9747 
9748 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9749 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9750 /// return the default SDValue.
9751 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9752                                               SelectionDAG &DAG) const {
9753   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9754   // to v16i8. Peek through the bitcasts to get the actual operands.
9755   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9756   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9757 
9758   auto ShuffleMask = SVN->getMask();
9759   SDValue VecShuffle(SVN, 0);
9760   SDLoc DL(SVN);
9761 
9762   // Check that we have a four byte shuffle.
9763   if (!isNByteElemShuffleMask(SVN, 4, 1))
9764     return SDValue();
9765 
9766   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9767   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9768     std::swap(LHS, RHS);
9769     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9770     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9771   }
9772 
9773   // Ensure that the RHS is a vector of constants.
9774   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9775   if (!BVN)
9776     return SDValue();
9777 
9778   // Check if RHS is a splat of 4-bytes (or smaller).
9779   APInt APSplatValue, APSplatUndef;
9780   unsigned SplatBitSize;
9781   bool HasAnyUndefs;
9782   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9783                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9784       SplatBitSize > 32)
9785     return SDValue();
9786 
9787   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9788   // The instruction splats a constant C into two words of the source vector
9789   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9790   // Thus we check that the shuffle mask is the equivalent  of
9791   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9792   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9793   // within each word are consecutive, so we only need to check the first byte.
9794   SDValue Index;
9795   bool IsLE = Subtarget.isLittleEndian();
9796   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9797       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9798        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9799     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9800   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9801            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9802             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9803     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9804   else
9805     return SDValue();
9806 
9807   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9808   // for XXSPLTI32DX.
9809   unsigned SplatVal = APSplatValue.getZExtValue();
9810   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9811     SplatVal |= (SplatVal << SplatBitSize);
9812 
9813   SDValue SplatNode = DAG.getNode(
9814       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9815       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9816   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9817 }
9818 
9819 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9820 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9821 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9822 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9823 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9824   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9825   assert(Op.getValueType() == MVT::v1i128 &&
9826          "Only set v1i128 as custom, other type shouldn't reach here!");
9827   SDLoc dl(Op);
9828   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9829   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9830   unsigned SHLAmt = N1.getConstantOperandVal(0);
9831   if (SHLAmt % 8 == 0) {
9832     std::array<int, 16> Mask;
9833     std::iota(Mask.begin(), Mask.end(), 0);
9834     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9835     if (SDValue Shuffle =
9836             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9837                                  DAG.getUNDEF(MVT::v16i8), Mask))
9838       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9839   }
9840   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9841   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9842                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9843   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9844                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9845   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9846   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9847 }
9848 
9849 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9850 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9851 /// return the code it can be lowered into.  Worst case, it can always be
9852 /// lowered into a vperm.
9853 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9854                                                SelectionDAG &DAG) const {
9855   SDLoc dl(Op);
9856   SDValue V1 = Op.getOperand(0);
9857   SDValue V2 = Op.getOperand(1);
9858   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9859 
9860   // Any nodes that were combined in the target-independent combiner prior
9861   // to vector legalization will not be sent to the target combine. Try to
9862   // combine it here.
9863   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9864     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9865       return NewShuffle;
9866     Op = NewShuffle;
9867     SVOp = cast<ShuffleVectorSDNode>(Op);
9868     V1 = Op.getOperand(0);
9869     V2 = Op.getOperand(1);
9870   }
9871   EVT VT = Op.getValueType();
9872   bool isLittleEndian = Subtarget.isLittleEndian();
9873 
9874   unsigned ShiftElts, InsertAtByte;
9875   bool Swap = false;
9876 
9877   // If this is a load-and-splat, we can do that with a single instruction
9878   // in some cases. However if the load has multiple uses, we don't want to
9879   // combine it because that will just produce multiple loads.
9880   bool IsPermutedLoad = false;
9881   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9882   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9883       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9884       InputLoad->hasOneUse()) {
9885     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9886     int SplatIdx =
9887       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9888 
9889     // The splat index for permuted loads will be in the left half of the vector
9890     // which is strictly wider than the loaded value by 8 bytes. So we need to
9891     // adjust the splat index to point to the correct address in memory.
9892     if (IsPermutedLoad) {
9893       assert((isLittleEndian || IsFourByte) &&
9894              "Unexpected size for permuted load on big endian target");
9895       SplatIdx += IsFourByte ? 2 : 1;
9896       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9897              "Splat of a value outside of the loaded memory");
9898     }
9899 
9900     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9901     // For 4-byte load-and-splat, we need Power9.
9902     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9903       uint64_t Offset = 0;
9904       if (IsFourByte)
9905         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9906       else
9907         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9908 
9909       // If the width of the load is the same as the width of the splat,
9910       // loading with an offset would load the wrong memory.
9911       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9912         Offset = 0;
9913 
9914       SDValue BasePtr = LD->getBasePtr();
9915       if (Offset != 0)
9916         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9917                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9918       SDValue Ops[] = {
9919         LD->getChain(),    // Chain
9920         BasePtr,           // BasePtr
9921         DAG.getValueType(Op.getValueType()) // VT
9922       };
9923       SDVTList VTL =
9924         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9925       SDValue LdSplt =
9926         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9927                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9928       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9929       if (LdSplt.getValueType() != SVOp->getValueType(0))
9930         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9931       return LdSplt;
9932     }
9933   }
9934   if (Subtarget.hasP9Vector() &&
9935       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9936                            isLittleEndian)) {
9937     if (Swap)
9938       std::swap(V1, V2);
9939     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9940     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9941     if (ShiftElts) {
9942       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9943                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9944       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9945                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9946       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9947     }
9948     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9949                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9950     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9951   }
9952 
9953   if (Subtarget.hasPrefixInstrs()) {
9954     SDValue SplatInsertNode;
9955     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9956       return SplatInsertNode;
9957   }
9958 
9959   if (Subtarget.hasP9Altivec()) {
9960     SDValue NewISDNode;
9961     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9962       return NewISDNode;
9963 
9964     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9965       return NewISDNode;
9966   }
9967 
9968   if (Subtarget.hasVSX() &&
9969       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9970     if (Swap)
9971       std::swap(V1, V2);
9972     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9973     SDValue Conv2 =
9974         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9975 
9976     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9977                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9978     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9979   }
9980 
9981   if (Subtarget.hasVSX() &&
9982     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9983     if (Swap)
9984       std::swap(V1, V2);
9985     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9986     SDValue Conv2 =
9987         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9988 
9989     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9990                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9991     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9992   }
9993 
9994   if (Subtarget.hasP9Vector()) {
9995      if (PPC::isXXBRHShuffleMask(SVOp)) {
9996       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9997       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9998       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9999     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10000       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10001       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10002       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10003     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10004       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10005       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10006       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10007     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10008       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10009       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10010       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10011     }
10012   }
10013 
10014   if (Subtarget.hasVSX()) {
10015     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10016       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10017 
10018       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10019       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10020                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10021       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10022     }
10023 
10024     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10025     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10026       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10027       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10028       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10029     }
10030   }
10031 
10032   // Cases that are handled by instructions that take permute immediates
10033   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10034   // selected by the instruction selector.
10035   if (V2.isUndef()) {
10036     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10037         PPC::isSplatShuffleMask(SVOp, 2) ||
10038         PPC::isSplatShuffleMask(SVOp, 4) ||
10039         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10040         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10041         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10042         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10043         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10044         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10045         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10046         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10047         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10048         (Subtarget.hasP8Altivec() && (
10049          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10050          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10051          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10052       return Op;
10053     }
10054   }
10055 
10056   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10057   // and produce a fixed permutation.  If any of these match, do not lower to
10058   // VPERM.
10059   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10060   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10061       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10062       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10063       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10064       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10065       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10066       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10067       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10068       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10069       (Subtarget.hasP8Altivec() && (
10070        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10071        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10072        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10073     return Op;
10074 
10075   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10076   // perfect shuffle table to emit an optimal matching sequence.
10077   ArrayRef<int> PermMask = SVOp->getMask();
10078 
10079   if (!DisablePerfectShuffle && !isLittleEndian) {
10080     unsigned PFIndexes[4];
10081     bool isFourElementShuffle = true;
10082     for (unsigned i = 0; i != 4 && isFourElementShuffle;
10083          ++i) {                           // Element number
10084       unsigned EltNo = 8;                 // Start out undef.
10085       for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10086         if (PermMask[i * 4 + j] < 0)
10087           continue; // Undef, ignore it.
10088 
10089         unsigned ByteSource = PermMask[i * 4 + j];
10090         if ((ByteSource & 3) != j) {
10091           isFourElementShuffle = false;
10092           break;
10093         }
10094 
10095         if (EltNo == 8) {
10096           EltNo = ByteSource / 4;
10097         } else if (EltNo != ByteSource / 4) {
10098           isFourElementShuffle = false;
10099           break;
10100         }
10101       }
10102       PFIndexes[i] = EltNo;
10103     }
10104 
10105     // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10106     // perfect shuffle vector to determine if it is cost effective to do this as
10107     // discrete instructions, or whether we should use a vperm.
10108     // For now, we skip this for little endian until such time as we have a
10109     // little-endian perfect shuffle table.
10110     if (isFourElementShuffle) {
10111       // Compute the index in the perfect shuffle table.
10112       unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10113                               PFIndexes[2] * 9 + PFIndexes[3];
10114 
10115       unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10116       unsigned Cost = (PFEntry >> 30);
10117 
10118       // Determining when to avoid vperm is tricky.  Many things affect the cost
10119       // of vperm, particularly how many times the perm mask needs to be
10120       // computed. For example, if the perm mask can be hoisted out of a loop or
10121       // is already used (perhaps because there are multiple permutes with the
10122       // same shuffle mask?) the vperm has a cost of 1.  OTOH, hoisting the
10123       // permute mask out of the loop requires an extra register.
10124       //
10125       // As a compromise, we only emit discrete instructions if the shuffle can
10126       // be generated in 3 or fewer operations.  When we have loop information
10127       // available, if this block is within a loop, we should avoid using vperm
10128       // for 3-operation perms and use a constant pool load instead.
10129       if (Cost < 3)
10130         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10131     }
10132   }
10133 
10134   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10135   // vector that will get spilled to the constant pool.
10136   if (V2.isUndef()) V2 = V1;
10137 
10138   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10139   // that it is in input element units, not in bytes.  Convert now.
10140 
10141   // For little endian, the order of the input vectors is reversed, and
10142   // the permutation mask is complemented with respect to 31.  This is
10143   // necessary to produce proper semantics with the big-endian-biased vperm
10144   // instruction.
10145   EVT EltVT = V1.getValueType().getVectorElementType();
10146   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10147 
10148   SmallVector<SDValue, 16> ResultMask;
10149   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10150     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10151 
10152     for (unsigned j = 0; j != BytesPerElement; ++j)
10153       if (isLittleEndian)
10154         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10155                                              dl, MVT::i32));
10156       else
10157         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10158                                              MVT::i32));
10159   }
10160 
10161   ShufflesHandledWithVPERM++;
10162   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10163   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10164   LLVM_DEBUG(SVOp->dump());
10165   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10166   LLVM_DEBUG(VPermMask.dump());
10167 
10168   if (isLittleEndian)
10169     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10170                        V2, V1, VPermMask);
10171   else
10172     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10173                        V1, V2, VPermMask);
10174 }
10175 
10176 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10177 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10178 /// information about the intrinsic.
10179 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10180                                  bool &isDot, const PPCSubtarget &Subtarget) {
10181   unsigned IntrinsicID =
10182       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10183   CompareOpc = -1;
10184   isDot = false;
10185   switch (IntrinsicID) {
10186   default:
10187     return false;
10188   // Comparison predicates.
10189   case Intrinsic::ppc_altivec_vcmpbfp_p:
10190     CompareOpc = 966;
10191     isDot = true;
10192     break;
10193   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10194     CompareOpc = 198;
10195     isDot = true;
10196     break;
10197   case Intrinsic::ppc_altivec_vcmpequb_p:
10198     CompareOpc = 6;
10199     isDot = true;
10200     break;
10201   case Intrinsic::ppc_altivec_vcmpequh_p:
10202     CompareOpc = 70;
10203     isDot = true;
10204     break;
10205   case Intrinsic::ppc_altivec_vcmpequw_p:
10206     CompareOpc = 134;
10207     isDot = true;
10208     break;
10209   case Intrinsic::ppc_altivec_vcmpequd_p:
10210     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10211       CompareOpc = 199;
10212       isDot = true;
10213     } else
10214       return false;
10215     break;
10216   case Intrinsic::ppc_altivec_vcmpneb_p:
10217   case Intrinsic::ppc_altivec_vcmpneh_p:
10218   case Intrinsic::ppc_altivec_vcmpnew_p:
10219   case Intrinsic::ppc_altivec_vcmpnezb_p:
10220   case Intrinsic::ppc_altivec_vcmpnezh_p:
10221   case Intrinsic::ppc_altivec_vcmpnezw_p:
10222     if (Subtarget.hasP9Altivec()) {
10223       switch (IntrinsicID) {
10224       default:
10225         llvm_unreachable("Unknown comparison intrinsic.");
10226       case Intrinsic::ppc_altivec_vcmpneb_p:
10227         CompareOpc = 7;
10228         break;
10229       case Intrinsic::ppc_altivec_vcmpneh_p:
10230         CompareOpc = 71;
10231         break;
10232       case Intrinsic::ppc_altivec_vcmpnew_p:
10233         CompareOpc = 135;
10234         break;
10235       case Intrinsic::ppc_altivec_vcmpnezb_p:
10236         CompareOpc = 263;
10237         break;
10238       case Intrinsic::ppc_altivec_vcmpnezh_p:
10239         CompareOpc = 327;
10240         break;
10241       case Intrinsic::ppc_altivec_vcmpnezw_p:
10242         CompareOpc = 391;
10243         break;
10244       }
10245       isDot = true;
10246     } else
10247       return false;
10248     break;
10249   case Intrinsic::ppc_altivec_vcmpgefp_p:
10250     CompareOpc = 454;
10251     isDot = true;
10252     break;
10253   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10254     CompareOpc = 710;
10255     isDot = true;
10256     break;
10257   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10258     CompareOpc = 774;
10259     isDot = true;
10260     break;
10261   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10262     CompareOpc = 838;
10263     isDot = true;
10264     break;
10265   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10266     CompareOpc = 902;
10267     isDot = true;
10268     break;
10269   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10270     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10271       CompareOpc = 967;
10272       isDot = true;
10273     } else
10274       return false;
10275     break;
10276   case Intrinsic::ppc_altivec_vcmpgtub_p:
10277     CompareOpc = 518;
10278     isDot = true;
10279     break;
10280   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10281     CompareOpc = 582;
10282     isDot = true;
10283     break;
10284   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10285     CompareOpc = 646;
10286     isDot = true;
10287     break;
10288   case Intrinsic::ppc_altivec_vcmpgtud_p:
10289     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10290       CompareOpc = 711;
10291       isDot = true;
10292     } else
10293       return false;
10294     break;
10295 
10296   case Intrinsic::ppc_altivec_vcmpequq:
10297   case Intrinsic::ppc_altivec_vcmpgtsq:
10298   case Intrinsic::ppc_altivec_vcmpgtuq:
10299     if (!Subtarget.isISA3_1())
10300       return false;
10301     switch (IntrinsicID) {
10302     default:
10303       llvm_unreachable("Unknown comparison intrinsic.");
10304     case Intrinsic::ppc_altivec_vcmpequq:
10305       CompareOpc = 455;
10306       break;
10307     case Intrinsic::ppc_altivec_vcmpgtsq:
10308       CompareOpc = 903;
10309       break;
10310     case Intrinsic::ppc_altivec_vcmpgtuq:
10311       CompareOpc = 647;
10312       break;
10313     }
10314     break;
10315 
10316   // VSX predicate comparisons use the same infrastructure
10317   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10318   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10319   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10320   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10321   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10322   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10323     if (Subtarget.hasVSX()) {
10324       switch (IntrinsicID) {
10325       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10326         CompareOpc = 99;
10327         break;
10328       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10329         CompareOpc = 115;
10330         break;
10331       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10332         CompareOpc = 107;
10333         break;
10334       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10335         CompareOpc = 67;
10336         break;
10337       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10338         CompareOpc = 83;
10339         break;
10340       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10341         CompareOpc = 75;
10342         break;
10343       }
10344       isDot = true;
10345     } else
10346       return false;
10347     break;
10348 
10349   // Normal Comparisons.
10350   case Intrinsic::ppc_altivec_vcmpbfp:
10351     CompareOpc = 966;
10352     break;
10353   case Intrinsic::ppc_altivec_vcmpeqfp:
10354     CompareOpc = 198;
10355     break;
10356   case Intrinsic::ppc_altivec_vcmpequb:
10357     CompareOpc = 6;
10358     break;
10359   case Intrinsic::ppc_altivec_vcmpequh:
10360     CompareOpc = 70;
10361     break;
10362   case Intrinsic::ppc_altivec_vcmpequw:
10363     CompareOpc = 134;
10364     break;
10365   case Intrinsic::ppc_altivec_vcmpequd:
10366     if (Subtarget.hasP8Altivec())
10367       CompareOpc = 199;
10368     else
10369       return false;
10370     break;
10371   case Intrinsic::ppc_altivec_vcmpneb:
10372   case Intrinsic::ppc_altivec_vcmpneh:
10373   case Intrinsic::ppc_altivec_vcmpnew:
10374   case Intrinsic::ppc_altivec_vcmpnezb:
10375   case Intrinsic::ppc_altivec_vcmpnezh:
10376   case Intrinsic::ppc_altivec_vcmpnezw:
10377     if (Subtarget.hasP9Altivec())
10378       switch (IntrinsicID) {
10379       default:
10380         llvm_unreachable("Unknown comparison intrinsic.");
10381       case Intrinsic::ppc_altivec_vcmpneb:
10382         CompareOpc = 7;
10383         break;
10384       case Intrinsic::ppc_altivec_vcmpneh:
10385         CompareOpc = 71;
10386         break;
10387       case Intrinsic::ppc_altivec_vcmpnew:
10388         CompareOpc = 135;
10389         break;
10390       case Intrinsic::ppc_altivec_vcmpnezb:
10391         CompareOpc = 263;
10392         break;
10393       case Intrinsic::ppc_altivec_vcmpnezh:
10394         CompareOpc = 327;
10395         break;
10396       case Intrinsic::ppc_altivec_vcmpnezw:
10397         CompareOpc = 391;
10398         break;
10399       }
10400     else
10401       return false;
10402     break;
10403   case Intrinsic::ppc_altivec_vcmpgefp:
10404     CompareOpc = 454;
10405     break;
10406   case Intrinsic::ppc_altivec_vcmpgtfp:
10407     CompareOpc = 710;
10408     break;
10409   case Intrinsic::ppc_altivec_vcmpgtsb:
10410     CompareOpc = 774;
10411     break;
10412   case Intrinsic::ppc_altivec_vcmpgtsh:
10413     CompareOpc = 838;
10414     break;
10415   case Intrinsic::ppc_altivec_vcmpgtsw:
10416     CompareOpc = 902;
10417     break;
10418   case Intrinsic::ppc_altivec_vcmpgtsd:
10419     if (Subtarget.hasP8Altivec())
10420       CompareOpc = 967;
10421     else
10422       return false;
10423     break;
10424   case Intrinsic::ppc_altivec_vcmpgtub:
10425     CompareOpc = 518;
10426     break;
10427   case Intrinsic::ppc_altivec_vcmpgtuh:
10428     CompareOpc = 582;
10429     break;
10430   case Intrinsic::ppc_altivec_vcmpgtuw:
10431     CompareOpc = 646;
10432     break;
10433   case Intrinsic::ppc_altivec_vcmpgtud:
10434     if (Subtarget.hasP8Altivec())
10435       CompareOpc = 711;
10436     else
10437       return false;
10438     break;
10439   case Intrinsic::ppc_altivec_vcmpequq_p:
10440   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10441   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10442     if (!Subtarget.isISA3_1())
10443       return false;
10444     switch (IntrinsicID) {
10445     default:
10446       llvm_unreachable("Unknown comparison intrinsic.");
10447     case Intrinsic::ppc_altivec_vcmpequq_p:
10448       CompareOpc = 455;
10449       break;
10450     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10451       CompareOpc = 903;
10452       break;
10453     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10454       CompareOpc = 647;
10455       break;
10456     }
10457     isDot = true;
10458     break;
10459   }
10460   return true;
10461 }
10462 
10463 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10464 /// lower, do it, otherwise return null.
10465 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10466                                                    SelectionDAG &DAG) const {
10467   unsigned IntrinsicID =
10468     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10469 
10470   SDLoc dl(Op);
10471 
10472   switch (IntrinsicID) {
10473   case Intrinsic::thread_pointer:
10474     // Reads the thread pointer register, used for __builtin_thread_pointer.
10475     if (Subtarget.isPPC64())
10476       return DAG.getRegister(PPC::X13, MVT::i64);
10477     return DAG.getRegister(PPC::R2, MVT::i32);
10478 
10479   case Intrinsic::ppc_mma_disassemble_acc:
10480   case Intrinsic::ppc_vsx_disassemble_pair: {
10481     int NumVecs = 2;
10482     SDValue WideVec = Op.getOperand(1);
10483     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10484       NumVecs = 4;
10485       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10486     }
10487     SmallVector<SDValue, 4> RetOps;
10488     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10489       SDValue Extract = DAG.getNode(
10490           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10491           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10492                                                      : VecNo,
10493                           dl, getPointerTy(DAG.getDataLayout())));
10494       RetOps.push_back(Extract);
10495     }
10496     return DAG.getMergeValues(RetOps, dl);
10497   }
10498 
10499   case Intrinsic::ppc_unpack_longdouble: {
10500     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10501     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10502            "Argument of long double unpack must be 0 or 1!");
10503     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10504                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10505                                        Idx->getValueType(0)));
10506   }
10507 
10508   case Intrinsic::ppc_compare_exp_lt:
10509   case Intrinsic::ppc_compare_exp_gt:
10510   case Intrinsic::ppc_compare_exp_eq:
10511   case Intrinsic::ppc_compare_exp_uo: {
10512     unsigned Pred;
10513     switch (IntrinsicID) {
10514     case Intrinsic::ppc_compare_exp_lt:
10515       Pred = PPC::PRED_LT;
10516       break;
10517     case Intrinsic::ppc_compare_exp_gt:
10518       Pred = PPC::PRED_GT;
10519       break;
10520     case Intrinsic::ppc_compare_exp_eq:
10521       Pred = PPC::PRED_EQ;
10522       break;
10523     case Intrinsic::ppc_compare_exp_uo:
10524       Pred = PPC::PRED_UN;
10525       break;
10526     }
10527     return SDValue(
10528         DAG.getMachineNode(
10529             PPC::SELECT_CC_I4, dl, MVT::i32,
10530             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10531                                         Op.getOperand(1), Op.getOperand(2)),
10532                      0),
10533              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10534              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10535         0);
10536   }
10537   case Intrinsic::ppc_test_data_class_d:
10538   case Intrinsic::ppc_test_data_class_f: {
10539     unsigned CmprOpc = PPC::XSTSTDCDP;
10540     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10541       CmprOpc = PPC::XSTSTDCSP;
10542     return SDValue(
10543         DAG.getMachineNode(
10544             PPC::SELECT_CC_I4, dl, MVT::i32,
10545             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10546                                         Op.getOperand(1)),
10547                      0),
10548              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10549              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10550         0);
10551   }
10552   case Intrinsic::ppc_convert_f128_to_ppcf128:
10553   case Intrinsic::ppc_convert_ppcf128_to_f128: {
10554     RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10555                             ? RTLIB::CONVERT_PPCF128_F128
10556                             : RTLIB::CONVERT_F128_PPCF128;
10557     MakeLibCallOptions CallOptions;
10558     std::pair<SDValue, SDValue> Result =
10559         makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10560                     dl, SDValue());
10561     return Result.first;
10562   }
10563   }
10564 
10565   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10566   // opcode number of the comparison.
10567   int CompareOpc;
10568   bool isDot;
10569   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10570     return SDValue();    // Don't custom lower most intrinsics.
10571 
10572   // If this is a non-dot comparison, make the VCMP node and we are done.
10573   if (!isDot) {
10574     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10575                               Op.getOperand(1), Op.getOperand(2),
10576                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10577     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10578   }
10579 
10580   // Create the PPCISD altivec 'dot' comparison node.
10581   SDValue Ops[] = {
10582     Op.getOperand(2),  // LHS
10583     Op.getOperand(3),  // RHS
10584     DAG.getConstant(CompareOpc, dl, MVT::i32)
10585   };
10586   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10587   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10588 
10589   // Now that we have the comparison, emit a copy from the CR to a GPR.
10590   // This is flagged to the above dot comparison.
10591   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10592                                 DAG.getRegister(PPC::CR6, MVT::i32),
10593                                 CompNode.getValue(1));
10594 
10595   // Unpack the result based on how the target uses it.
10596   unsigned BitNo;   // Bit # of CR6.
10597   bool InvertBit;   // Invert result?
10598   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10599   default:  // Can't happen, don't crash on invalid number though.
10600   case 0:   // Return the value of the EQ bit of CR6.
10601     BitNo = 0; InvertBit = false;
10602     break;
10603   case 1:   // Return the inverted value of the EQ bit of CR6.
10604     BitNo = 0; InvertBit = true;
10605     break;
10606   case 2:   // Return the value of the LT bit of CR6.
10607     BitNo = 2; InvertBit = false;
10608     break;
10609   case 3:   // Return the inverted value of the LT bit of CR6.
10610     BitNo = 2; InvertBit = true;
10611     break;
10612   }
10613 
10614   // Shift the bit into the low position.
10615   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10616                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10617   // Isolate the bit.
10618   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10619                       DAG.getConstant(1, dl, MVT::i32));
10620 
10621   // If we are supposed to, toggle the bit.
10622   if (InvertBit)
10623     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10624                         DAG.getConstant(1, dl, MVT::i32));
10625   return Flags;
10626 }
10627 
10628 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10629                                                SelectionDAG &DAG) const {
10630   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10631   // the beginning of the argument list.
10632   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10633   SDLoc DL(Op);
10634   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10635   case Intrinsic::ppc_cfence: {
10636     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10637     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10638     SDValue Val = Op.getOperand(ArgStart + 1);
10639     EVT Ty = Val.getValueType();
10640     if (Ty == MVT::i128) {
10641       // FIXME: Testing one of two paired registers is sufficient to guarantee
10642       // ordering?
10643       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10644     }
10645     return SDValue(
10646         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10647                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10648                            Op.getOperand(0)),
10649         0);
10650   }
10651   default:
10652     break;
10653   }
10654   return SDValue();
10655 }
10656 
10657 // Lower scalar BSWAP64 to xxbrd.
10658 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10659   SDLoc dl(Op);
10660   if (!Subtarget.isPPC64())
10661     return Op;
10662   // MTVSRDD
10663   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10664                    Op.getOperand(0));
10665   // XXBRD
10666   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10667   // MFVSRD
10668   int VectorIndex = 0;
10669   if (Subtarget.isLittleEndian())
10670     VectorIndex = 1;
10671   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10672                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10673   return Op;
10674 }
10675 
10676 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10677 // compared to a value that is atomically loaded (atomic loads zero-extend).
10678 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10679                                                 SelectionDAG &DAG) const {
10680   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10681          "Expecting an atomic compare-and-swap here.");
10682   SDLoc dl(Op);
10683   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10684   EVT MemVT = AtomicNode->getMemoryVT();
10685   if (MemVT.getSizeInBits() >= 32)
10686     return Op;
10687 
10688   SDValue CmpOp = Op.getOperand(2);
10689   // If this is already correctly zero-extended, leave it alone.
10690   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10691   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10692     return Op;
10693 
10694   // Clear the high bits of the compare operand.
10695   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10696   SDValue NewCmpOp =
10697     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10698                 DAG.getConstant(MaskVal, dl, MVT::i32));
10699 
10700   // Replace the existing compare operand with the properly zero-extended one.
10701   SmallVector<SDValue, 4> Ops;
10702   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10703     Ops.push_back(AtomicNode->getOperand(i));
10704   Ops[2] = NewCmpOp;
10705   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10706   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10707   auto NodeTy =
10708     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10709   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10710 }
10711 
10712 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10713                                                   SelectionDAG &DAG) const {
10714   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10715   EVT MemVT = N->getMemoryVT();
10716   assert(MemVT.getSimpleVT() == MVT::i128 &&
10717          "Expect quadword atomic operations");
10718   SDLoc dl(N);
10719   unsigned Opc = N->getOpcode();
10720   switch (Opc) {
10721   case ISD::ATOMIC_LOAD: {
10722     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10723     // lowered to ppc instructions by pattern matching instruction selector.
10724     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10725     SmallVector<SDValue, 4> Ops{
10726         N->getOperand(0),
10727         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10728     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10729       Ops.push_back(N->getOperand(I));
10730     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10731                                                 Ops, MemVT, N->getMemOperand());
10732     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10733     SDValue ValHi =
10734         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10735     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10736                         DAG.getConstant(64, dl, MVT::i32));
10737     SDValue Val =
10738         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10739     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10740                        {Val, LoadedVal.getValue(2)});
10741   }
10742   case ISD::ATOMIC_STORE: {
10743     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10744     // lowered to ppc instructions by pattern matching instruction selector.
10745     SDVTList Tys = DAG.getVTList(MVT::Other);
10746     SmallVector<SDValue, 4> Ops{
10747         N->getOperand(0),
10748         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10749     SDValue Val = N->getOperand(2);
10750     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10751     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10752                                 DAG.getConstant(64, dl, MVT::i32));
10753     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10754     Ops.push_back(ValLo);
10755     Ops.push_back(ValHi);
10756     Ops.push_back(N->getOperand(1));
10757     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10758                                    N->getMemOperand());
10759   }
10760   default:
10761     llvm_unreachable("Unexpected atomic opcode");
10762   }
10763 }
10764 
10765 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10766                                                  SelectionDAG &DAG) const {
10767   SDLoc dl(Op);
10768   // Create a stack slot that is 16-byte aligned.
10769   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10770   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10771   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10772   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10773 
10774   // Store the input value into Value#0 of the stack slot.
10775   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10776                                MachinePointerInfo());
10777   // Load it out.
10778   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10779 }
10780 
10781 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10782                                                   SelectionDAG &DAG) const {
10783   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10784          "Should only be called for ISD::INSERT_VECTOR_ELT");
10785 
10786   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10787 
10788   EVT VT = Op.getValueType();
10789   SDLoc dl(Op);
10790   SDValue V1 = Op.getOperand(0);
10791   SDValue V2 = Op.getOperand(1);
10792 
10793   if (VT == MVT::v2f64 && C)
10794     return Op;
10795 
10796   if (Subtarget.hasP9Vector()) {
10797     // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
10798     // because on P10, it allows this specific insert_vector_elt load pattern to
10799     // utilize the refactored load and store infrastructure in order to exploit
10800     // prefixed loads.
10801     // On targets with inexpensive direct moves (Power9 and up), a
10802     // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
10803     // load since a single precision load will involve conversion to double
10804     // precision on the load followed by another conversion to single precision.
10805     if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
10806         (isa<LoadSDNode>(V2))) {
10807       SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
10808       SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
10809       SDValue InsVecElt =
10810           DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
10811                       BitcastLoad, Op.getOperand(2));
10812       return DAG.getBitcast(MVT::v4f32, InsVecElt);
10813     }
10814   }
10815 
10816   if (Subtarget.isISA3_1()) {
10817     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10818       return SDValue();
10819     // On P10, we have legal lowering for constant and variable indices for
10820     // all vectors.
10821     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10822         VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
10823       return Op;
10824   }
10825 
10826   // Before P10, we have legal lowering for constant indices but not for
10827   // variable ones.
10828   if (!C)
10829     return SDValue();
10830 
10831   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10832   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10833     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10834     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10835     unsigned InsertAtElement = C->getZExtValue();
10836     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10837     if (Subtarget.isLittleEndian()) {
10838       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10839     }
10840     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10841                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10842   }
10843   return Op;
10844 }
10845 
10846 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10847                                            SelectionDAG &DAG) const {
10848   SDLoc dl(Op);
10849   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10850   SDValue LoadChain = LN->getChain();
10851   SDValue BasePtr = LN->getBasePtr();
10852   EVT VT = Op.getValueType();
10853 
10854   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10855     return Op;
10856 
10857   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10858   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10859   // 2 or 4 vsx registers.
10860   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10861          "Type unsupported without MMA");
10862   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10863          "Type unsupported without paired vector support");
10864   Align Alignment = LN->getAlign();
10865   SmallVector<SDValue, 4> Loads;
10866   SmallVector<SDValue, 4> LoadChains;
10867   unsigned NumVecs = VT.getSizeInBits() / 128;
10868   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10869     SDValue Load =
10870         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10871                     LN->getPointerInfo().getWithOffset(Idx * 16),
10872                     commonAlignment(Alignment, Idx * 16),
10873                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10874     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10875                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10876     Loads.push_back(Load);
10877     LoadChains.push_back(Load.getValue(1));
10878   }
10879   if (Subtarget.isLittleEndian()) {
10880     std::reverse(Loads.begin(), Loads.end());
10881     std::reverse(LoadChains.begin(), LoadChains.end());
10882   }
10883   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10884   SDValue Value =
10885       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10886                   dl, VT, Loads);
10887   SDValue RetOps[] = {Value, TF};
10888   return DAG.getMergeValues(RetOps, dl);
10889 }
10890 
10891 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10892                                             SelectionDAG &DAG) const {
10893   SDLoc dl(Op);
10894   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10895   SDValue StoreChain = SN->getChain();
10896   SDValue BasePtr = SN->getBasePtr();
10897   SDValue Value = SN->getValue();
10898   EVT StoreVT = Value.getValueType();
10899 
10900   if (StoreVT != MVT::v256i1 && StoreVT != 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 stores to store the pair or accumulator
10905   // underlying registers individually.
10906   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10907          "Type unsupported without MMA");
10908   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10909          "Type unsupported without paired vector support");
10910   Align Alignment = SN->getAlign();
10911   SmallVector<SDValue, 4> Stores;
10912   unsigned NumVecs = 2;
10913   if (StoreVT == MVT::v512i1) {
10914     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10915     NumVecs = 4;
10916   }
10917   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10918     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10919     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10920                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10921     SDValue Store =
10922         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10923                      SN->getPointerInfo().getWithOffset(Idx * 16),
10924                      commonAlignment(Alignment, Idx * 16),
10925                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10926     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10927                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10928     Stores.push_back(Store);
10929   }
10930   SDValue TF = DAG.getTokenFactor(dl, Stores);
10931   return TF;
10932 }
10933 
10934 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10935   SDLoc dl(Op);
10936   if (Op.getValueType() == MVT::v4i32) {
10937     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10938 
10939     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10940     // +16 as shift amt.
10941     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10942     SDValue RHSSwap =   // = vrlw RHS, 16
10943       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10944 
10945     // Shrinkify inputs to v8i16.
10946     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10947     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10948     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10949 
10950     // Low parts multiplied together, generating 32-bit results (we ignore the
10951     // top parts).
10952     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10953                                         LHS, RHS, DAG, dl, MVT::v4i32);
10954 
10955     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10956                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10957     // Shift the high parts up 16 bits.
10958     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10959                               Neg16, DAG, dl);
10960     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10961   } else if (Op.getValueType() == MVT::v16i8) {
10962     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10963     bool isLittleEndian = Subtarget.isLittleEndian();
10964 
10965     // Multiply the even 8-bit parts, producing 16-bit sums.
10966     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10967                                            LHS, RHS, DAG, dl, MVT::v8i16);
10968     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10969 
10970     // Multiply the odd 8-bit parts, producing 16-bit sums.
10971     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10972                                           LHS, RHS, DAG, dl, MVT::v8i16);
10973     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10974 
10975     // Merge the results together.  Because vmuleub and vmuloub are
10976     // instructions with a big-endian bias, we must reverse the
10977     // element numbering and reverse the meaning of "odd" and "even"
10978     // when generating little endian code.
10979     int Ops[16];
10980     for (unsigned i = 0; i != 8; ++i) {
10981       if (isLittleEndian) {
10982         Ops[i*2  ] = 2*i;
10983         Ops[i*2+1] = 2*i+16;
10984       } else {
10985         Ops[i*2  ] = 2*i+1;
10986         Ops[i*2+1] = 2*i+1+16;
10987       }
10988     }
10989     if (isLittleEndian)
10990       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10991     else
10992       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10993   } else {
10994     llvm_unreachable("Unknown mul to lower!");
10995   }
10996 }
10997 
10998 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10999   bool IsStrict = Op->isStrictFPOpcode();
11000   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
11001       !Subtarget.hasP9Vector())
11002     return SDValue();
11003 
11004   return Op;
11005 }
11006 
11007 // Custom lowering for fpext vf32 to v2f64
11008 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11009 
11010   assert(Op.getOpcode() == ISD::FP_EXTEND &&
11011          "Should only be called for ISD::FP_EXTEND");
11012 
11013   // FIXME: handle extends from half precision float vectors on P9.
11014   // We only want to custom lower an extend from v2f32 to v2f64.
11015   if (Op.getValueType() != MVT::v2f64 ||
11016       Op.getOperand(0).getValueType() != MVT::v2f32)
11017     return SDValue();
11018 
11019   SDLoc dl(Op);
11020   SDValue Op0 = Op.getOperand(0);
11021 
11022   switch (Op0.getOpcode()) {
11023   default:
11024     return SDValue();
11025   case ISD::EXTRACT_SUBVECTOR: {
11026     assert(Op0.getNumOperands() == 2 &&
11027            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11028            "Node should have 2 operands with second one being a constant!");
11029 
11030     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11031       return SDValue();
11032 
11033     // Custom lower is only done for high or low doubleword.
11034     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11035     if (Idx % 2 != 0)
11036       return SDValue();
11037 
11038     // Since input is v4f32, at this point Idx is either 0 or 2.
11039     // Shift to get the doubleword position we want.
11040     int DWord = Idx >> 1;
11041 
11042     // High and low word positions are different on little endian.
11043     if (Subtarget.isLittleEndian())
11044       DWord ^= 0x1;
11045 
11046     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11047                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11048   }
11049   case ISD::FADD:
11050   case ISD::FMUL:
11051   case ISD::FSUB: {
11052     SDValue NewLoad[2];
11053     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11054       // Ensure both input are loads.
11055       SDValue LdOp = Op0.getOperand(i);
11056       if (LdOp.getOpcode() != ISD::LOAD)
11057         return SDValue();
11058       // Generate new load node.
11059       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11060       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11061       NewLoad[i] = DAG.getMemIntrinsicNode(
11062           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11063           LD->getMemoryVT(), LD->getMemOperand());
11064     }
11065     SDValue NewOp =
11066         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11067                     NewLoad[1], Op0.getNode()->getFlags());
11068     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11069                        DAG.getConstant(0, dl, MVT::i32));
11070   }
11071   case ISD::LOAD: {
11072     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11073     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11074     SDValue NewLd = DAG.getMemIntrinsicNode(
11075         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11076         LD->getMemoryVT(), LD->getMemOperand());
11077     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11078                        DAG.getConstant(0, dl, MVT::i32));
11079   }
11080   }
11081   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11082 }
11083 
11084 /// LowerOperation - Provide custom lowering hooks for some operations.
11085 ///
11086 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11087   switch (Op.getOpcode()) {
11088   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11089   case ISD::FPOW:               return lowerPow(Op, DAG);
11090   case ISD::FSIN:               return lowerSin(Op, DAG);
11091   case ISD::FCOS:               return lowerCos(Op, DAG);
11092   case ISD::FLOG:               return lowerLog(Op, DAG);
11093   case ISD::FLOG10:             return lowerLog10(Op, DAG);
11094   case ISD::FEXP:               return lowerExp(Op, DAG);
11095   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11096   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11097   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11098   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11099   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11100   case ISD::STRICT_FSETCC:
11101   case ISD::STRICT_FSETCCS:
11102   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11103   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11104   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11105 
11106   case ISD::INLINEASM:
11107   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11108   // Variable argument lowering.
11109   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11110   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11111   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11112 
11113   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11114   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11115   case ISD::GET_DYNAMIC_AREA_OFFSET:
11116     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11117 
11118   // Exception handling lowering.
11119   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11120   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11121   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11122 
11123   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11124   case ISD::STORE:              return LowerSTORE(Op, DAG);
11125   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11126   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11127   case ISD::STRICT_FP_TO_UINT:
11128   case ISD::STRICT_FP_TO_SINT:
11129   case ISD::FP_TO_UINT:
11130   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11131   case ISD::STRICT_UINT_TO_FP:
11132   case ISD::STRICT_SINT_TO_FP:
11133   case ISD::UINT_TO_FP:
11134   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11135   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11136 
11137   // Lower 64-bit shifts.
11138   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11139   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11140   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11141 
11142   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11143   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11144 
11145   // Vector-related lowering.
11146   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11147   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11148   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11149   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11150   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11151   case ISD::MUL:                return LowerMUL(Op, DAG);
11152   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11153   case ISD::STRICT_FP_ROUND:
11154   case ISD::FP_ROUND:
11155     return LowerFP_ROUND(Op, DAG);
11156   case ISD::ROTL:               return LowerROTL(Op, DAG);
11157 
11158   // For counter-based loop handling.
11159   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11160 
11161   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11162 
11163   // Frame & Return address.
11164   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11165   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11166 
11167   case ISD::INTRINSIC_VOID:
11168     return LowerINTRINSIC_VOID(Op, DAG);
11169   case ISD::BSWAP:
11170     return LowerBSWAP(Op, DAG);
11171   case ISD::ATOMIC_CMP_SWAP:
11172     return LowerATOMIC_CMP_SWAP(Op, DAG);
11173   case ISD::ATOMIC_STORE:
11174     return LowerATOMIC_LOAD_STORE(Op, DAG);
11175   }
11176 }
11177 
11178 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11179                                            SmallVectorImpl<SDValue>&Results,
11180                                            SelectionDAG &DAG) const {
11181   SDLoc dl(N);
11182   switch (N->getOpcode()) {
11183   default:
11184     llvm_unreachable("Do not know how to custom type legalize this operation!");
11185   case ISD::ATOMIC_LOAD: {
11186     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11187     Results.push_back(Res);
11188     Results.push_back(Res.getValue(1));
11189     break;
11190   }
11191   case ISD::READCYCLECOUNTER: {
11192     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11193     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11194 
11195     Results.push_back(
11196         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11197     Results.push_back(RTB.getValue(2));
11198     break;
11199   }
11200   case ISD::INTRINSIC_W_CHAIN: {
11201     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11202         Intrinsic::loop_decrement)
11203       break;
11204 
11205     assert(N->getValueType(0) == MVT::i1 &&
11206            "Unexpected result type for CTR decrement intrinsic");
11207     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11208                                  N->getValueType(0));
11209     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11210     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11211                                  N->getOperand(1));
11212 
11213     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11214     Results.push_back(NewInt.getValue(1));
11215     break;
11216   }
11217   case ISD::INTRINSIC_WO_CHAIN: {
11218     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11219     case Intrinsic::ppc_pack_longdouble:
11220       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11221                                     N->getOperand(2), N->getOperand(1)));
11222       break;
11223     case Intrinsic::ppc_convert_f128_to_ppcf128:
11224       Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11225       break;
11226     }
11227     break;
11228   }
11229   case ISD::VAARG: {
11230     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11231       return;
11232 
11233     EVT VT = N->getValueType(0);
11234 
11235     if (VT == MVT::i64) {
11236       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11237 
11238       Results.push_back(NewNode);
11239       Results.push_back(NewNode.getValue(1));
11240     }
11241     return;
11242   }
11243   case ISD::STRICT_FP_TO_SINT:
11244   case ISD::STRICT_FP_TO_UINT:
11245   case ISD::FP_TO_SINT:
11246   case ISD::FP_TO_UINT: {
11247     // LowerFP_TO_INT() can only handle f32 and f64.
11248     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11249         MVT::ppcf128)
11250       return;
11251     SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11252     Results.push_back(LoweredValue);
11253     if (N->isStrictFPOpcode())
11254       Results.push_back(LoweredValue.getValue(1));
11255     return;
11256   }
11257   case ISD::TRUNCATE: {
11258     if (!N->getValueType(0).isVector())
11259       return;
11260     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11261     if (Lowered)
11262       Results.push_back(Lowered);
11263     return;
11264   }
11265   case ISD::FSHL:
11266   case ISD::FSHR:
11267     // Don't handle funnel shifts here.
11268     return;
11269   case ISD::BITCAST:
11270     // Don't handle bitcast here.
11271     return;
11272   case ISD::FP_EXTEND:
11273     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11274     if (Lowered)
11275       Results.push_back(Lowered);
11276     return;
11277   }
11278 }
11279 
11280 //===----------------------------------------------------------------------===//
11281 //  Other Lowering Code
11282 //===----------------------------------------------------------------------===//
11283 
11284 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11285   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11286   Function *Func = Intrinsic::getDeclaration(M, Id);
11287   return Builder.CreateCall(Func, {});
11288 }
11289 
11290 // The mappings for emitLeading/TrailingFence is taken from
11291 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11292 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11293                                                  Instruction *Inst,
11294                                                  AtomicOrdering Ord) const {
11295   if (Ord == AtomicOrdering::SequentiallyConsistent)
11296     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11297   if (isReleaseOrStronger(Ord))
11298     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11299   return nullptr;
11300 }
11301 
11302 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11303                                                   Instruction *Inst,
11304                                                   AtomicOrdering Ord) const {
11305   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11306     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11307     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11308     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11309     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11310       return Builder.CreateCall(
11311           Intrinsic::getDeclaration(
11312               Builder.GetInsertBlock()->getParent()->getParent(),
11313               Intrinsic::ppc_cfence, {Inst->getType()}),
11314           {Inst});
11315     // FIXME: Can use isync for rmw operation.
11316     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11317   }
11318   return nullptr;
11319 }
11320 
11321 MachineBasicBlock *
11322 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11323                                     unsigned AtomicSize,
11324                                     unsigned BinOpcode,
11325                                     unsigned CmpOpcode,
11326                                     unsigned CmpPred) const {
11327   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11328   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11329 
11330   auto LoadMnemonic = PPC::LDARX;
11331   auto StoreMnemonic = PPC::STDCX;
11332   switch (AtomicSize) {
11333   default:
11334     llvm_unreachable("Unexpected size of atomic entity");
11335   case 1:
11336     LoadMnemonic = PPC::LBARX;
11337     StoreMnemonic = PPC::STBCX;
11338     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11339     break;
11340   case 2:
11341     LoadMnemonic = PPC::LHARX;
11342     StoreMnemonic = PPC::STHCX;
11343     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11344     break;
11345   case 4:
11346     LoadMnemonic = PPC::LWARX;
11347     StoreMnemonic = PPC::STWCX;
11348     break;
11349   case 8:
11350     LoadMnemonic = PPC::LDARX;
11351     StoreMnemonic = PPC::STDCX;
11352     break;
11353   }
11354 
11355   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11356   MachineFunction *F = BB->getParent();
11357   MachineFunction::iterator It = ++BB->getIterator();
11358 
11359   Register dest = MI.getOperand(0).getReg();
11360   Register ptrA = MI.getOperand(1).getReg();
11361   Register ptrB = MI.getOperand(2).getReg();
11362   Register incr = MI.getOperand(3).getReg();
11363   DebugLoc dl = MI.getDebugLoc();
11364 
11365   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11366   MachineBasicBlock *loop2MBB =
11367     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11368   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11369   F->insert(It, loopMBB);
11370   if (CmpOpcode)
11371     F->insert(It, loop2MBB);
11372   F->insert(It, exitMBB);
11373   exitMBB->splice(exitMBB->begin(), BB,
11374                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11375   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11376 
11377   MachineRegisterInfo &RegInfo = F->getRegInfo();
11378   Register TmpReg = (!BinOpcode) ? incr :
11379     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11380                                            : &PPC::GPRCRegClass);
11381 
11382   //  thisMBB:
11383   //   ...
11384   //   fallthrough --> loopMBB
11385   BB->addSuccessor(loopMBB);
11386 
11387   //  loopMBB:
11388   //   l[wd]arx dest, ptr
11389   //   add r0, dest, incr
11390   //   st[wd]cx. r0, ptr
11391   //   bne- loopMBB
11392   //   fallthrough --> exitMBB
11393 
11394   // For max/min...
11395   //  loopMBB:
11396   //   l[wd]arx dest, ptr
11397   //   cmpl?[wd] incr, dest
11398   //   bgt exitMBB
11399   //  loop2MBB:
11400   //   st[wd]cx. dest, ptr
11401   //   bne- loopMBB
11402   //   fallthrough --> exitMBB
11403 
11404   BB = loopMBB;
11405   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11406     .addReg(ptrA).addReg(ptrB);
11407   if (BinOpcode)
11408     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11409   if (CmpOpcode) {
11410     // Signed comparisons of byte or halfword values must be sign-extended.
11411     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11412       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11413       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11414               ExtReg).addReg(dest);
11415       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11416         .addReg(incr).addReg(ExtReg);
11417     } else
11418       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11419         .addReg(incr).addReg(dest);
11420 
11421     BuildMI(BB, dl, TII->get(PPC::BCC))
11422       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11423     BB->addSuccessor(loop2MBB);
11424     BB->addSuccessor(exitMBB);
11425     BB = loop2MBB;
11426   }
11427   BuildMI(BB, dl, TII->get(StoreMnemonic))
11428     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11429   BuildMI(BB, dl, TII->get(PPC::BCC))
11430     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11431   BB->addSuccessor(loopMBB);
11432   BB->addSuccessor(exitMBB);
11433 
11434   //  exitMBB:
11435   //   ...
11436   BB = exitMBB;
11437   return BB;
11438 }
11439 
11440 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11441   switch(MI.getOpcode()) {
11442   default:
11443     return false;
11444   case PPC::COPY:
11445     return TII->isSignExtended(MI);
11446   case PPC::LHA:
11447   case PPC::LHA8:
11448   case PPC::LHAU:
11449   case PPC::LHAU8:
11450   case PPC::LHAUX:
11451   case PPC::LHAUX8:
11452   case PPC::LHAX:
11453   case PPC::LHAX8:
11454   case PPC::LWA:
11455   case PPC::LWAUX:
11456   case PPC::LWAX:
11457   case PPC::LWAX_32:
11458   case PPC::LWA_32:
11459   case PPC::PLHA:
11460   case PPC::PLHA8:
11461   case PPC::PLHA8pc:
11462   case PPC::PLHApc:
11463   case PPC::PLWA:
11464   case PPC::PLWA8:
11465   case PPC::PLWA8pc:
11466   case PPC::PLWApc:
11467   case PPC::EXTSB:
11468   case PPC::EXTSB8:
11469   case PPC::EXTSB8_32_64:
11470   case PPC::EXTSB8_rec:
11471   case PPC::EXTSB_rec:
11472   case PPC::EXTSH:
11473   case PPC::EXTSH8:
11474   case PPC::EXTSH8_32_64:
11475   case PPC::EXTSH8_rec:
11476   case PPC::EXTSH_rec:
11477   case PPC::EXTSW:
11478   case PPC::EXTSWSLI:
11479   case PPC::EXTSWSLI_32_64:
11480   case PPC::EXTSWSLI_32_64_rec:
11481   case PPC::EXTSWSLI_rec:
11482   case PPC::EXTSW_32:
11483   case PPC::EXTSW_32_64:
11484   case PPC::EXTSW_32_64_rec:
11485   case PPC::EXTSW_rec:
11486   case PPC::SRAW:
11487   case PPC::SRAWI:
11488   case PPC::SRAWI_rec:
11489   case PPC::SRAW_rec:
11490     return true;
11491   }
11492   return false;
11493 }
11494 
11495 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11496     MachineInstr &MI, MachineBasicBlock *BB,
11497     bool is8bit, // operation
11498     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11499   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11500   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11501 
11502   // If this is a signed comparison and the value being compared is not known
11503   // to be sign extended, sign extend it here.
11504   DebugLoc dl = MI.getDebugLoc();
11505   MachineFunction *F = BB->getParent();
11506   MachineRegisterInfo &RegInfo = F->getRegInfo();
11507   Register incr = MI.getOperand(3).getReg();
11508   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11509     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11510 
11511   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11512     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11513     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11514         .addReg(MI.getOperand(3).getReg());
11515     MI.getOperand(3).setReg(ValueReg);
11516   }
11517   // If we support part-word atomic mnemonics, just use them
11518   if (Subtarget.hasPartwordAtomics())
11519     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11520                             CmpPred);
11521 
11522   // In 64 bit mode we have to use 64 bits for addresses, even though the
11523   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11524   // registers without caring whether they're 32 or 64, but here we're
11525   // doing actual arithmetic on the addresses.
11526   bool is64bit = Subtarget.isPPC64();
11527   bool isLittleEndian = Subtarget.isLittleEndian();
11528   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11529 
11530   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11531   MachineFunction::iterator It = ++BB->getIterator();
11532 
11533   Register dest = MI.getOperand(0).getReg();
11534   Register ptrA = MI.getOperand(1).getReg();
11535   Register ptrB = MI.getOperand(2).getReg();
11536 
11537   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11538   MachineBasicBlock *loop2MBB =
11539       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11540   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11541   F->insert(It, loopMBB);
11542   if (CmpOpcode)
11543     F->insert(It, loop2MBB);
11544   F->insert(It, exitMBB);
11545   exitMBB->splice(exitMBB->begin(), BB,
11546                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11547   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11548 
11549   const TargetRegisterClass *RC =
11550       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11551   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11552 
11553   Register PtrReg = RegInfo.createVirtualRegister(RC);
11554   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11555   Register ShiftReg =
11556       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11557   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11558   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11559   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11560   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11561   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11562   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11563   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11564   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11565   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11566   Register Ptr1Reg;
11567   Register TmpReg =
11568       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11569 
11570   //  thisMBB:
11571   //   ...
11572   //   fallthrough --> loopMBB
11573   BB->addSuccessor(loopMBB);
11574 
11575   // The 4-byte load must be aligned, while a char or short may be
11576   // anywhere in the word.  Hence all this nasty bookkeeping code.
11577   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11578   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11579   //   xori shift, shift1, 24 [16]
11580   //   rlwinm ptr, ptr1, 0, 0, 29
11581   //   slw incr2, incr, shift
11582   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11583   //   slw mask, mask2, shift
11584   //  loopMBB:
11585   //   lwarx tmpDest, ptr
11586   //   add tmp, tmpDest, incr2
11587   //   andc tmp2, tmpDest, mask
11588   //   and tmp3, tmp, mask
11589   //   or tmp4, tmp3, tmp2
11590   //   stwcx. tmp4, ptr
11591   //   bne- loopMBB
11592   //   fallthrough --> exitMBB
11593   //   srw SrwDest, tmpDest, shift
11594   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11595   if (ptrA != ZeroReg) {
11596     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11597     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11598         .addReg(ptrA)
11599         .addReg(ptrB);
11600   } else {
11601     Ptr1Reg = ptrB;
11602   }
11603   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11604   // mode.
11605   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11606       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11607       .addImm(3)
11608       .addImm(27)
11609       .addImm(is8bit ? 28 : 27);
11610   if (!isLittleEndian)
11611     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11612         .addReg(Shift1Reg)
11613         .addImm(is8bit ? 24 : 16);
11614   if (is64bit)
11615     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11616         .addReg(Ptr1Reg)
11617         .addImm(0)
11618         .addImm(61);
11619   else
11620     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11621         .addReg(Ptr1Reg)
11622         .addImm(0)
11623         .addImm(0)
11624         .addImm(29);
11625   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11626   if (is8bit)
11627     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11628   else {
11629     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11630     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11631         .addReg(Mask3Reg)
11632         .addImm(65535);
11633   }
11634   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11635       .addReg(Mask2Reg)
11636       .addReg(ShiftReg);
11637 
11638   BB = loopMBB;
11639   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11640       .addReg(ZeroReg)
11641       .addReg(PtrReg);
11642   if (BinOpcode)
11643     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11644         .addReg(Incr2Reg)
11645         .addReg(TmpDestReg);
11646   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11647       .addReg(TmpDestReg)
11648       .addReg(MaskReg);
11649   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11650   if (CmpOpcode) {
11651     // For unsigned comparisons, we can directly compare the shifted values.
11652     // For signed comparisons we shift and sign extend.
11653     Register SReg = RegInfo.createVirtualRegister(GPRC);
11654     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11655         .addReg(TmpDestReg)
11656         .addReg(MaskReg);
11657     unsigned ValueReg = SReg;
11658     unsigned CmpReg = Incr2Reg;
11659     if (CmpOpcode == PPC::CMPW) {
11660       ValueReg = RegInfo.createVirtualRegister(GPRC);
11661       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11662           .addReg(SReg)
11663           .addReg(ShiftReg);
11664       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11665       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11666           .addReg(ValueReg);
11667       ValueReg = ValueSReg;
11668       CmpReg = incr;
11669     }
11670     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11671         .addReg(CmpReg)
11672         .addReg(ValueReg);
11673     BuildMI(BB, dl, TII->get(PPC::BCC))
11674         .addImm(CmpPred)
11675         .addReg(PPC::CR0)
11676         .addMBB(exitMBB);
11677     BB->addSuccessor(loop2MBB);
11678     BB->addSuccessor(exitMBB);
11679     BB = loop2MBB;
11680   }
11681   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11682   BuildMI(BB, dl, TII->get(PPC::STWCX))
11683       .addReg(Tmp4Reg)
11684       .addReg(ZeroReg)
11685       .addReg(PtrReg);
11686   BuildMI(BB, dl, TII->get(PPC::BCC))
11687       .addImm(PPC::PRED_NE)
11688       .addReg(PPC::CR0)
11689       .addMBB(loopMBB);
11690   BB->addSuccessor(loopMBB);
11691   BB->addSuccessor(exitMBB);
11692 
11693   //  exitMBB:
11694   //   ...
11695   BB = exitMBB;
11696   // Since the shift amount is not a constant, we need to clear
11697   // the upper bits with a separate RLWINM.
11698   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11699       .addReg(SrwDestReg)
11700       .addImm(0)
11701       .addImm(is8bit ? 24 : 16)
11702       .addImm(31);
11703   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11704       .addReg(TmpDestReg)
11705       .addReg(ShiftReg);
11706   return BB;
11707 }
11708 
11709 llvm::MachineBasicBlock *
11710 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11711                                     MachineBasicBlock *MBB) const {
11712   DebugLoc DL = MI.getDebugLoc();
11713   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11714   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11715 
11716   MachineFunction *MF = MBB->getParent();
11717   MachineRegisterInfo &MRI = MF->getRegInfo();
11718 
11719   const BasicBlock *BB = MBB->getBasicBlock();
11720   MachineFunction::iterator I = ++MBB->getIterator();
11721 
11722   Register DstReg = MI.getOperand(0).getReg();
11723   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11724   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11725   Register mainDstReg = MRI.createVirtualRegister(RC);
11726   Register restoreDstReg = MRI.createVirtualRegister(RC);
11727 
11728   MVT PVT = getPointerTy(MF->getDataLayout());
11729   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11730          "Invalid Pointer Size!");
11731   // For v = setjmp(buf), we generate
11732   //
11733   // thisMBB:
11734   //  SjLjSetup mainMBB
11735   //  bl mainMBB
11736   //  v_restore = 1
11737   //  b sinkMBB
11738   //
11739   // mainMBB:
11740   //  buf[LabelOffset] = LR
11741   //  v_main = 0
11742   //
11743   // sinkMBB:
11744   //  v = phi(main, restore)
11745   //
11746 
11747   MachineBasicBlock *thisMBB = MBB;
11748   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11749   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11750   MF->insert(I, mainMBB);
11751   MF->insert(I, sinkMBB);
11752 
11753   MachineInstrBuilder MIB;
11754 
11755   // Transfer the remainder of BB and its successor edges to sinkMBB.
11756   sinkMBB->splice(sinkMBB->begin(), MBB,
11757                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11758   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11759 
11760   // Note that the structure of the jmp_buf used here is not compatible
11761   // with that used by libc, and is not designed to be. Specifically, it
11762   // stores only those 'reserved' registers that LLVM does not otherwise
11763   // understand how to spill. Also, by convention, by the time this
11764   // intrinsic is called, Clang has already stored the frame address in the
11765   // first slot of the buffer and stack address in the third. Following the
11766   // X86 target code, we'll store the jump address in the second slot. We also
11767   // need to save the TOC pointer (R2) to handle jumps between shared
11768   // libraries, and that will be stored in the fourth slot. The thread
11769   // identifier (R13) is not affected.
11770 
11771   // thisMBB:
11772   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11773   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11774   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11775 
11776   // Prepare IP either in reg.
11777   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11778   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11779   Register BufReg = MI.getOperand(1).getReg();
11780 
11781   if (Subtarget.is64BitELFABI()) {
11782     setUsesTOCBasePtr(*MBB->getParent());
11783     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11784               .addReg(PPC::X2)
11785               .addImm(TOCOffset)
11786               .addReg(BufReg)
11787               .cloneMemRefs(MI);
11788   }
11789 
11790   // Naked functions never have a base pointer, and so we use r1. For all
11791   // other functions, this decision must be delayed until during PEI.
11792   unsigned BaseReg;
11793   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11794     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11795   else
11796     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11797 
11798   MIB = BuildMI(*thisMBB, MI, DL,
11799                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11800             .addReg(BaseReg)
11801             .addImm(BPOffset)
11802             .addReg(BufReg)
11803             .cloneMemRefs(MI);
11804 
11805   // Setup
11806   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11807   MIB.addRegMask(TRI->getNoPreservedMask());
11808 
11809   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11810 
11811   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11812           .addMBB(mainMBB);
11813   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11814 
11815   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11816   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11817 
11818   // mainMBB:
11819   //  mainDstReg = 0
11820   MIB =
11821       BuildMI(mainMBB, DL,
11822               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11823 
11824   // Store IP
11825   if (Subtarget.isPPC64()) {
11826     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11827             .addReg(LabelReg)
11828             .addImm(LabelOffset)
11829             .addReg(BufReg);
11830   } else {
11831     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11832             .addReg(LabelReg)
11833             .addImm(LabelOffset)
11834             .addReg(BufReg);
11835   }
11836   MIB.cloneMemRefs(MI);
11837 
11838   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11839   mainMBB->addSuccessor(sinkMBB);
11840 
11841   // sinkMBB:
11842   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11843           TII->get(PPC::PHI), DstReg)
11844     .addReg(mainDstReg).addMBB(mainMBB)
11845     .addReg(restoreDstReg).addMBB(thisMBB);
11846 
11847   MI.eraseFromParent();
11848   return sinkMBB;
11849 }
11850 
11851 MachineBasicBlock *
11852 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11853                                      MachineBasicBlock *MBB) const {
11854   DebugLoc DL = MI.getDebugLoc();
11855   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11856 
11857   MachineFunction *MF = MBB->getParent();
11858   MachineRegisterInfo &MRI = MF->getRegInfo();
11859 
11860   MVT PVT = getPointerTy(MF->getDataLayout());
11861   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11862          "Invalid Pointer Size!");
11863 
11864   const TargetRegisterClass *RC =
11865     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11866   Register Tmp = MRI.createVirtualRegister(RC);
11867   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11868   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11869   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11870   unsigned BP =
11871       (PVT == MVT::i64)
11872           ? PPC::X30
11873           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11874                                                               : PPC::R30);
11875 
11876   MachineInstrBuilder MIB;
11877 
11878   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11879   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11880   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11881   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11882 
11883   Register BufReg = MI.getOperand(0).getReg();
11884 
11885   // Reload FP (the jumped-to function may not have had a
11886   // frame pointer, and if so, then its r31 will be restored
11887   // as necessary).
11888   if (PVT == MVT::i64) {
11889     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11890             .addImm(0)
11891             .addReg(BufReg);
11892   } else {
11893     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11894             .addImm(0)
11895             .addReg(BufReg);
11896   }
11897   MIB.cloneMemRefs(MI);
11898 
11899   // Reload IP
11900   if (PVT == MVT::i64) {
11901     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11902             .addImm(LabelOffset)
11903             .addReg(BufReg);
11904   } else {
11905     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11906             .addImm(LabelOffset)
11907             .addReg(BufReg);
11908   }
11909   MIB.cloneMemRefs(MI);
11910 
11911   // Reload SP
11912   if (PVT == MVT::i64) {
11913     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11914             .addImm(SPOffset)
11915             .addReg(BufReg);
11916   } else {
11917     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11918             .addImm(SPOffset)
11919             .addReg(BufReg);
11920   }
11921   MIB.cloneMemRefs(MI);
11922 
11923   // Reload BP
11924   if (PVT == MVT::i64) {
11925     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11926             .addImm(BPOffset)
11927             .addReg(BufReg);
11928   } else {
11929     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11930             .addImm(BPOffset)
11931             .addReg(BufReg);
11932   }
11933   MIB.cloneMemRefs(MI);
11934 
11935   // Reload TOC
11936   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11937     setUsesTOCBasePtr(*MBB->getParent());
11938     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11939               .addImm(TOCOffset)
11940               .addReg(BufReg)
11941               .cloneMemRefs(MI);
11942   }
11943 
11944   // Jump
11945   BuildMI(*MBB, MI, DL,
11946           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11947   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11948 
11949   MI.eraseFromParent();
11950   return MBB;
11951 }
11952 
11953 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11954   // If the function specifically requests inline stack probes, emit them.
11955   if (MF.getFunction().hasFnAttribute("probe-stack"))
11956     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11957            "inline-asm";
11958   return false;
11959 }
11960 
11961 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11962   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11963   unsigned StackAlign = TFI->getStackAlignment();
11964   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11965          "Unexpected stack alignment");
11966   // The default stack probe size is 4096 if the function has no
11967   // stack-probe-size attribute.
11968   unsigned StackProbeSize = 4096;
11969   const Function &Fn = MF.getFunction();
11970   if (Fn.hasFnAttribute("stack-probe-size"))
11971     Fn.getFnAttribute("stack-probe-size")
11972         .getValueAsString()
11973         .getAsInteger(0, StackProbeSize);
11974   // Round down to the stack alignment.
11975   StackProbeSize &= ~(StackAlign - 1);
11976   return StackProbeSize ? StackProbeSize : StackAlign;
11977 }
11978 
11979 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11980 // into three phases. In the first phase, it uses pseudo instruction
11981 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11982 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11983 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11984 // MaxCallFrameSize so that it can calculate correct data area pointer.
11985 MachineBasicBlock *
11986 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11987                                     MachineBasicBlock *MBB) const {
11988   const bool isPPC64 = Subtarget.isPPC64();
11989   MachineFunction *MF = MBB->getParent();
11990   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11991   DebugLoc DL = MI.getDebugLoc();
11992   const unsigned ProbeSize = getStackProbeSize(*MF);
11993   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11994   MachineRegisterInfo &MRI = MF->getRegInfo();
11995   // The CFG of probing stack looks as
11996   //         +-----+
11997   //         | MBB |
11998   //         +--+--+
11999   //            |
12000   //       +----v----+
12001   //  +--->+ TestMBB +---+
12002   //  |    +----+----+   |
12003   //  |         |        |
12004   //  |   +-----v----+   |
12005   //  +---+ BlockMBB |   |
12006   //      +----------+   |
12007   //                     |
12008   //       +---------+   |
12009   //       | TailMBB +<--+
12010   //       +---------+
12011   // In MBB, calculate previous frame pointer and final stack pointer.
12012   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
12013   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
12014   // TailMBB is spliced via \p MI.
12015   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
12016   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
12017   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
12018 
12019   MachineFunction::iterator MBBIter = ++MBB->getIterator();
12020   MF->insert(MBBIter, TestMBB);
12021   MF->insert(MBBIter, BlockMBB);
12022   MF->insert(MBBIter, TailMBB);
12023 
12024   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
12025   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12026 
12027   Register DstReg = MI.getOperand(0).getReg();
12028   Register NegSizeReg = MI.getOperand(1).getReg();
12029   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12030   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12031   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12032   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12033 
12034   // Since value of NegSizeReg might be realigned in prologepilog, insert a
12035   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
12036   // NegSize.
12037   unsigned ProbeOpc;
12038   if (!MRI.hasOneNonDBGUse(NegSizeReg))
12039     ProbeOpc =
12040         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
12041   else
12042     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
12043     // and NegSizeReg will be allocated in the same phyreg to avoid
12044     // redundant copy when NegSizeReg has only one use which is current MI and
12045     // will be replaced by PREPARE_PROBED_ALLOCA then.
12046     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
12047                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
12048   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
12049       .addDef(ActualNegSizeReg)
12050       .addReg(NegSizeReg)
12051       .add(MI.getOperand(2))
12052       .add(MI.getOperand(3));
12053 
12054   // Calculate final stack pointer, which equals to SP + ActualNegSize.
12055   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12056           FinalStackPtr)
12057       .addReg(SPReg)
12058       .addReg(ActualNegSizeReg);
12059 
12060   // Materialize a scratch register for update.
12061   int64_t NegProbeSize = -(int64_t)ProbeSize;
12062   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
12063   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12064   if (!isInt<16>(NegProbeSize)) {
12065     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12066     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12067         .addImm(NegProbeSize >> 16);
12068     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12069             ScratchReg)
12070         .addReg(TempReg)
12071         .addImm(NegProbeSize & 0xFFFF);
12072   } else
12073     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12074         .addImm(NegProbeSize);
12075 
12076   {
12077     // Probing leading residual part.
12078     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12079     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12080         .addReg(ActualNegSizeReg)
12081         .addReg(ScratchReg);
12082     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12083     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12084         .addReg(Div)
12085         .addReg(ScratchReg);
12086     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12087     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12088         .addReg(Mul)
12089         .addReg(ActualNegSizeReg);
12090     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12091         .addReg(FramePointer)
12092         .addReg(SPReg)
12093         .addReg(NegMod);
12094   }
12095 
12096   {
12097     // Remaining part should be multiple of ProbeSize.
12098     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12099     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12100         .addReg(SPReg)
12101         .addReg(FinalStackPtr);
12102     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12103         .addImm(PPC::PRED_EQ)
12104         .addReg(CmpResult)
12105         .addMBB(TailMBB);
12106     TestMBB->addSuccessor(BlockMBB);
12107     TestMBB->addSuccessor(TailMBB);
12108   }
12109 
12110   {
12111     // Touch the block.
12112     // |P...|P...|P...
12113     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12114         .addReg(FramePointer)
12115         .addReg(SPReg)
12116         .addReg(ScratchReg);
12117     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12118     BlockMBB->addSuccessor(TestMBB);
12119   }
12120 
12121   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12122   // DYNAREAOFFSET pseudo instruction to get the future result.
12123   Register MaxCallFrameSizeReg =
12124       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12125   BuildMI(TailMBB, DL,
12126           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12127           MaxCallFrameSizeReg)
12128       .add(MI.getOperand(2))
12129       .add(MI.getOperand(3));
12130   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12131       .addReg(SPReg)
12132       .addReg(MaxCallFrameSizeReg);
12133 
12134   // Splice instructions after MI to TailMBB.
12135   TailMBB->splice(TailMBB->end(), MBB,
12136                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12137   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12138   MBB->addSuccessor(TestMBB);
12139 
12140   // Delete the pseudo instruction.
12141   MI.eraseFromParent();
12142 
12143   ++NumDynamicAllocaProbed;
12144   return TailMBB;
12145 }
12146 
12147 MachineBasicBlock *
12148 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12149                                                MachineBasicBlock *BB) const {
12150   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12151       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12152     if (Subtarget.is64BitELFABI() &&
12153         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12154         !Subtarget.isUsingPCRelativeCalls()) {
12155       // Call lowering should have added an r2 operand to indicate a dependence
12156       // on the TOC base pointer value. It can't however, because there is no
12157       // way to mark the dependence as implicit there, and so the stackmap code
12158       // will confuse it with a regular operand. Instead, add the dependence
12159       // here.
12160       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12161     }
12162 
12163     return emitPatchPoint(MI, BB);
12164   }
12165 
12166   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12167       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12168     return emitEHSjLjSetJmp(MI, BB);
12169   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12170              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12171     return emitEHSjLjLongJmp(MI, BB);
12172   }
12173 
12174   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12175 
12176   // To "insert" these instructions we actually have to insert their
12177   // control-flow patterns.
12178   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12179   MachineFunction::iterator It = ++BB->getIterator();
12180 
12181   MachineFunction *F = BB->getParent();
12182   MachineRegisterInfo &MRI = F->getRegInfo();
12183 
12184   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12185       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12186       MI.getOpcode() == PPC::SELECT_I8) {
12187     SmallVector<MachineOperand, 2> Cond;
12188     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12189         MI.getOpcode() == PPC::SELECT_CC_I8)
12190       Cond.push_back(MI.getOperand(4));
12191     else
12192       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12193     Cond.push_back(MI.getOperand(1));
12194 
12195     DebugLoc dl = MI.getDebugLoc();
12196     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12197                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12198   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12199              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12200              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12201              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12202              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12203              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12204              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12205              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12206              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12207              MI.getOpcode() == PPC::SELECT_F4 ||
12208              MI.getOpcode() == PPC::SELECT_F8 ||
12209              MI.getOpcode() == PPC::SELECT_F16 ||
12210              MI.getOpcode() == PPC::SELECT_SPE ||
12211              MI.getOpcode() == PPC::SELECT_SPE4 ||
12212              MI.getOpcode() == PPC::SELECT_VRRC ||
12213              MI.getOpcode() == PPC::SELECT_VSFRC ||
12214              MI.getOpcode() == PPC::SELECT_VSSRC ||
12215              MI.getOpcode() == PPC::SELECT_VSRC) {
12216     // The incoming instruction knows the destination vreg to set, the
12217     // condition code register to branch on, the true/false values to
12218     // select between, and a branch opcode to use.
12219 
12220     //  thisMBB:
12221     //  ...
12222     //   TrueVal = ...
12223     //   cmpTY ccX, r1, r2
12224     //   bCC copy1MBB
12225     //   fallthrough --> copy0MBB
12226     MachineBasicBlock *thisMBB = BB;
12227     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12228     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12229     DebugLoc dl = MI.getDebugLoc();
12230     F->insert(It, copy0MBB);
12231     F->insert(It, sinkMBB);
12232 
12233     // Transfer the remainder of BB and its successor edges to sinkMBB.
12234     sinkMBB->splice(sinkMBB->begin(), BB,
12235                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12236     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12237 
12238     // Next, add the true and fallthrough blocks as its successors.
12239     BB->addSuccessor(copy0MBB);
12240     BB->addSuccessor(sinkMBB);
12241 
12242     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12243         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12244         MI.getOpcode() == PPC::SELECT_F16 ||
12245         MI.getOpcode() == PPC::SELECT_SPE4 ||
12246         MI.getOpcode() == PPC::SELECT_SPE ||
12247         MI.getOpcode() == PPC::SELECT_VRRC ||
12248         MI.getOpcode() == PPC::SELECT_VSFRC ||
12249         MI.getOpcode() == PPC::SELECT_VSSRC ||
12250         MI.getOpcode() == PPC::SELECT_VSRC) {
12251       BuildMI(BB, dl, TII->get(PPC::BC))
12252           .addReg(MI.getOperand(1).getReg())
12253           .addMBB(sinkMBB);
12254     } else {
12255       unsigned SelectPred = MI.getOperand(4).getImm();
12256       BuildMI(BB, dl, TII->get(PPC::BCC))
12257           .addImm(SelectPred)
12258           .addReg(MI.getOperand(1).getReg())
12259           .addMBB(sinkMBB);
12260     }
12261 
12262     //  copy0MBB:
12263     //   %FalseValue = ...
12264     //   # fallthrough to sinkMBB
12265     BB = copy0MBB;
12266 
12267     // Update machine-CFG edges
12268     BB->addSuccessor(sinkMBB);
12269 
12270     //  sinkMBB:
12271     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12272     //  ...
12273     BB = sinkMBB;
12274     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12275         .addReg(MI.getOperand(3).getReg())
12276         .addMBB(copy0MBB)
12277         .addReg(MI.getOperand(2).getReg())
12278         .addMBB(thisMBB);
12279   } else if (MI.getOpcode() == PPC::ReadTB) {
12280     // To read the 64-bit time-base register on a 32-bit target, we read the
12281     // two halves. Should the counter have wrapped while it was being read, we
12282     // need to try again.
12283     // ...
12284     // readLoop:
12285     // mfspr Rx,TBU # load from TBU
12286     // mfspr Ry,TB  # load from TB
12287     // mfspr Rz,TBU # load from TBU
12288     // cmpw crX,Rx,Rz # check if 'old'='new'
12289     // bne readLoop   # branch if they're not equal
12290     // ...
12291 
12292     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12293     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12294     DebugLoc dl = MI.getDebugLoc();
12295     F->insert(It, readMBB);
12296     F->insert(It, sinkMBB);
12297 
12298     // Transfer the remainder of BB and its successor edges to sinkMBB.
12299     sinkMBB->splice(sinkMBB->begin(), BB,
12300                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12301     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12302 
12303     BB->addSuccessor(readMBB);
12304     BB = readMBB;
12305 
12306     MachineRegisterInfo &RegInfo = F->getRegInfo();
12307     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12308     Register LoReg = MI.getOperand(0).getReg();
12309     Register HiReg = MI.getOperand(1).getReg();
12310 
12311     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12312     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12313     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12314 
12315     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12316 
12317     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12318         .addReg(HiReg)
12319         .addReg(ReadAgainReg);
12320     BuildMI(BB, dl, TII->get(PPC::BCC))
12321         .addImm(PPC::PRED_NE)
12322         .addReg(CmpReg)
12323         .addMBB(readMBB);
12324 
12325     BB->addSuccessor(readMBB);
12326     BB->addSuccessor(sinkMBB);
12327   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12328     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12329   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12330     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12331   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12332     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12333   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12334     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12335 
12336   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12337     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12338   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12339     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12340   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12341     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12342   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12343     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12344 
12345   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12346     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12347   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12348     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12349   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12350     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12351   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12352     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12353 
12354   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12355     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12356   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12357     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12358   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12359     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12360   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12361     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12362 
12363   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12364     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12365   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12366     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12367   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12368     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12369   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12370     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12371 
12372   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12373     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12374   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12375     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12376   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12377     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12378   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12379     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12380 
12381   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12382     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12383   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12384     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12385   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12386     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12387   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12388     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12389 
12390   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12391     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12392   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12393     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12394   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12395     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12396   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12397     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12398 
12399   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12400     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12401   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12402     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12403   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12404     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12405   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12406     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12407 
12408   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12409     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12410   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12411     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12412   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12413     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12414   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12415     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12416 
12417   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12418     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12419   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12420     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12421   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12422     BB = EmitAtomicBinary(MI, BB, 4, 0);
12423   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12424     BB = EmitAtomicBinary(MI, BB, 8, 0);
12425   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12426            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12427            (Subtarget.hasPartwordAtomics() &&
12428             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12429            (Subtarget.hasPartwordAtomics() &&
12430             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12431     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12432 
12433     auto LoadMnemonic = PPC::LDARX;
12434     auto StoreMnemonic = PPC::STDCX;
12435     switch (MI.getOpcode()) {
12436     default:
12437       llvm_unreachable("Compare and swap of unknown size");
12438     case PPC::ATOMIC_CMP_SWAP_I8:
12439       LoadMnemonic = PPC::LBARX;
12440       StoreMnemonic = PPC::STBCX;
12441       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12442       break;
12443     case PPC::ATOMIC_CMP_SWAP_I16:
12444       LoadMnemonic = PPC::LHARX;
12445       StoreMnemonic = PPC::STHCX;
12446       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12447       break;
12448     case PPC::ATOMIC_CMP_SWAP_I32:
12449       LoadMnemonic = PPC::LWARX;
12450       StoreMnemonic = PPC::STWCX;
12451       break;
12452     case PPC::ATOMIC_CMP_SWAP_I64:
12453       LoadMnemonic = PPC::LDARX;
12454       StoreMnemonic = PPC::STDCX;
12455       break;
12456     }
12457     Register dest = MI.getOperand(0).getReg();
12458     Register ptrA = MI.getOperand(1).getReg();
12459     Register ptrB = MI.getOperand(2).getReg();
12460     Register oldval = MI.getOperand(3).getReg();
12461     Register newval = MI.getOperand(4).getReg();
12462     DebugLoc dl = MI.getDebugLoc();
12463 
12464     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12465     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12466     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12467     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12468     F->insert(It, loop1MBB);
12469     F->insert(It, loop2MBB);
12470     F->insert(It, midMBB);
12471     F->insert(It, exitMBB);
12472     exitMBB->splice(exitMBB->begin(), BB,
12473                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12474     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12475 
12476     //  thisMBB:
12477     //   ...
12478     //   fallthrough --> loopMBB
12479     BB->addSuccessor(loop1MBB);
12480 
12481     // loop1MBB:
12482     //   l[bhwd]arx dest, ptr
12483     //   cmp[wd] dest, oldval
12484     //   bne- midMBB
12485     // loop2MBB:
12486     //   st[bhwd]cx. newval, ptr
12487     //   bne- loopMBB
12488     //   b exitBB
12489     // midMBB:
12490     //   st[bhwd]cx. dest, ptr
12491     // exitBB:
12492     BB = loop1MBB;
12493     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12494     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12495         .addReg(oldval)
12496         .addReg(dest);
12497     BuildMI(BB, dl, TII->get(PPC::BCC))
12498         .addImm(PPC::PRED_NE)
12499         .addReg(PPC::CR0)
12500         .addMBB(midMBB);
12501     BB->addSuccessor(loop2MBB);
12502     BB->addSuccessor(midMBB);
12503 
12504     BB = loop2MBB;
12505     BuildMI(BB, dl, TII->get(StoreMnemonic))
12506         .addReg(newval)
12507         .addReg(ptrA)
12508         .addReg(ptrB);
12509     BuildMI(BB, dl, TII->get(PPC::BCC))
12510         .addImm(PPC::PRED_NE)
12511         .addReg(PPC::CR0)
12512         .addMBB(loop1MBB);
12513     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12514     BB->addSuccessor(loop1MBB);
12515     BB->addSuccessor(exitMBB);
12516 
12517     BB = midMBB;
12518     BuildMI(BB, dl, TII->get(StoreMnemonic))
12519         .addReg(dest)
12520         .addReg(ptrA)
12521         .addReg(ptrB);
12522     BB->addSuccessor(exitMBB);
12523 
12524     //  exitMBB:
12525     //   ...
12526     BB = exitMBB;
12527   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12528              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12529     // We must use 64-bit registers for addresses when targeting 64-bit,
12530     // since we're actually doing arithmetic on them.  Other registers
12531     // can be 32-bit.
12532     bool is64bit = Subtarget.isPPC64();
12533     bool isLittleEndian = Subtarget.isLittleEndian();
12534     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12535 
12536     Register dest = MI.getOperand(0).getReg();
12537     Register ptrA = MI.getOperand(1).getReg();
12538     Register ptrB = MI.getOperand(2).getReg();
12539     Register oldval = MI.getOperand(3).getReg();
12540     Register newval = MI.getOperand(4).getReg();
12541     DebugLoc dl = MI.getDebugLoc();
12542 
12543     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12544     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12545     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12546     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12547     F->insert(It, loop1MBB);
12548     F->insert(It, loop2MBB);
12549     F->insert(It, midMBB);
12550     F->insert(It, exitMBB);
12551     exitMBB->splice(exitMBB->begin(), BB,
12552                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12553     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12554 
12555     MachineRegisterInfo &RegInfo = F->getRegInfo();
12556     const TargetRegisterClass *RC =
12557         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12558     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12559 
12560     Register PtrReg = RegInfo.createVirtualRegister(RC);
12561     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12562     Register ShiftReg =
12563         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12564     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12565     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12566     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12567     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12568     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12569     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12570     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12571     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12572     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12573     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12574     Register Ptr1Reg;
12575     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12576     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12577     //  thisMBB:
12578     //   ...
12579     //   fallthrough --> loopMBB
12580     BB->addSuccessor(loop1MBB);
12581 
12582     // The 4-byte load must be aligned, while a char or short may be
12583     // anywhere in the word.  Hence all this nasty bookkeeping code.
12584     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12585     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12586     //   xori shift, shift1, 24 [16]
12587     //   rlwinm ptr, ptr1, 0, 0, 29
12588     //   slw newval2, newval, shift
12589     //   slw oldval2, oldval,shift
12590     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12591     //   slw mask, mask2, shift
12592     //   and newval3, newval2, mask
12593     //   and oldval3, oldval2, mask
12594     // loop1MBB:
12595     //   lwarx tmpDest, ptr
12596     //   and tmp, tmpDest, mask
12597     //   cmpw tmp, oldval3
12598     //   bne- midMBB
12599     // loop2MBB:
12600     //   andc tmp2, tmpDest, mask
12601     //   or tmp4, tmp2, newval3
12602     //   stwcx. tmp4, ptr
12603     //   bne- loop1MBB
12604     //   b exitBB
12605     // midMBB:
12606     //   stwcx. tmpDest, ptr
12607     // exitBB:
12608     //   srw dest, tmpDest, shift
12609     if (ptrA != ZeroReg) {
12610       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12611       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12612           .addReg(ptrA)
12613           .addReg(ptrB);
12614     } else {
12615       Ptr1Reg = ptrB;
12616     }
12617 
12618     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12619     // mode.
12620     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12621         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12622         .addImm(3)
12623         .addImm(27)
12624         .addImm(is8bit ? 28 : 27);
12625     if (!isLittleEndian)
12626       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12627           .addReg(Shift1Reg)
12628           .addImm(is8bit ? 24 : 16);
12629     if (is64bit)
12630       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12631           .addReg(Ptr1Reg)
12632           .addImm(0)
12633           .addImm(61);
12634     else
12635       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12636           .addReg(Ptr1Reg)
12637           .addImm(0)
12638           .addImm(0)
12639           .addImm(29);
12640     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12641         .addReg(newval)
12642         .addReg(ShiftReg);
12643     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12644         .addReg(oldval)
12645         .addReg(ShiftReg);
12646     if (is8bit)
12647       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12648     else {
12649       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12650       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12651           .addReg(Mask3Reg)
12652           .addImm(65535);
12653     }
12654     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12655         .addReg(Mask2Reg)
12656         .addReg(ShiftReg);
12657     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12658         .addReg(NewVal2Reg)
12659         .addReg(MaskReg);
12660     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12661         .addReg(OldVal2Reg)
12662         .addReg(MaskReg);
12663 
12664     BB = loop1MBB;
12665     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12666         .addReg(ZeroReg)
12667         .addReg(PtrReg);
12668     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12669         .addReg(TmpDestReg)
12670         .addReg(MaskReg);
12671     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12672         .addReg(TmpReg)
12673         .addReg(OldVal3Reg);
12674     BuildMI(BB, dl, TII->get(PPC::BCC))
12675         .addImm(PPC::PRED_NE)
12676         .addReg(PPC::CR0)
12677         .addMBB(midMBB);
12678     BB->addSuccessor(loop2MBB);
12679     BB->addSuccessor(midMBB);
12680 
12681     BB = loop2MBB;
12682     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12683         .addReg(TmpDestReg)
12684         .addReg(MaskReg);
12685     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12686         .addReg(Tmp2Reg)
12687         .addReg(NewVal3Reg);
12688     BuildMI(BB, dl, TII->get(PPC::STWCX))
12689         .addReg(Tmp4Reg)
12690         .addReg(ZeroReg)
12691         .addReg(PtrReg);
12692     BuildMI(BB, dl, TII->get(PPC::BCC))
12693         .addImm(PPC::PRED_NE)
12694         .addReg(PPC::CR0)
12695         .addMBB(loop1MBB);
12696     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12697     BB->addSuccessor(loop1MBB);
12698     BB->addSuccessor(exitMBB);
12699 
12700     BB = midMBB;
12701     BuildMI(BB, dl, TII->get(PPC::STWCX))
12702         .addReg(TmpDestReg)
12703         .addReg(ZeroReg)
12704         .addReg(PtrReg);
12705     BB->addSuccessor(exitMBB);
12706 
12707     //  exitMBB:
12708     //   ...
12709     BB = exitMBB;
12710     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12711         .addReg(TmpReg)
12712         .addReg(ShiftReg);
12713   } else if (MI.getOpcode() == PPC::FADDrtz) {
12714     // This pseudo performs an FADD with rounding mode temporarily forced
12715     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12716     // is not modeled at the SelectionDAG level.
12717     Register Dest = MI.getOperand(0).getReg();
12718     Register Src1 = MI.getOperand(1).getReg();
12719     Register Src2 = MI.getOperand(2).getReg();
12720     DebugLoc dl = MI.getDebugLoc();
12721 
12722     MachineRegisterInfo &RegInfo = F->getRegInfo();
12723     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12724 
12725     // Save FPSCR value.
12726     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12727 
12728     // Set rounding mode to round-to-zero.
12729     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12730         .addImm(31)
12731         .addReg(PPC::RM, RegState::ImplicitDefine);
12732 
12733     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12734         .addImm(30)
12735         .addReg(PPC::RM, RegState::ImplicitDefine);
12736 
12737     // Perform addition.
12738     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12739                    .addReg(Src1)
12740                    .addReg(Src2);
12741     if (MI.getFlag(MachineInstr::NoFPExcept))
12742       MIB.setMIFlag(MachineInstr::NoFPExcept);
12743 
12744     // Restore FPSCR value.
12745     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12746   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12747              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12748              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12749              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12750     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12751                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12752                           ? PPC::ANDI8_rec
12753                           : PPC::ANDI_rec;
12754     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12755                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12756 
12757     MachineRegisterInfo &RegInfo = F->getRegInfo();
12758     Register Dest = RegInfo.createVirtualRegister(
12759         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12760 
12761     DebugLoc Dl = MI.getDebugLoc();
12762     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12763         .addReg(MI.getOperand(1).getReg())
12764         .addImm(1);
12765     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12766             MI.getOperand(0).getReg())
12767         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12768   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12769     DebugLoc Dl = MI.getDebugLoc();
12770     MachineRegisterInfo &RegInfo = F->getRegInfo();
12771     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12772     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12773     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12774             MI.getOperand(0).getReg())
12775         .addReg(CRReg);
12776   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12777     DebugLoc Dl = MI.getDebugLoc();
12778     unsigned Imm = MI.getOperand(1).getImm();
12779     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12780     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12781             MI.getOperand(0).getReg())
12782         .addReg(PPC::CR0EQ);
12783   } else if (MI.getOpcode() == PPC::SETRNDi) {
12784     DebugLoc dl = MI.getDebugLoc();
12785     Register OldFPSCRReg = MI.getOperand(0).getReg();
12786 
12787     // Save FPSCR value.
12788     if (MRI.use_empty(OldFPSCRReg))
12789       BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12790     else
12791       BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12792 
12793     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12794     // the following settings:
12795     //   00 Round to nearest
12796     //   01 Round to 0
12797     //   10 Round to +inf
12798     //   11 Round to -inf
12799 
12800     // When the operand is immediate, using the two least significant bits of
12801     // the immediate to set the bits 62:63 of FPSCR.
12802     unsigned Mode = MI.getOperand(1).getImm();
12803     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12804         .addImm(31)
12805         .addReg(PPC::RM, RegState::ImplicitDefine);
12806 
12807     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12808         .addImm(30)
12809         .addReg(PPC::RM, RegState::ImplicitDefine);
12810   } else if (MI.getOpcode() == PPC::SETRND) {
12811     DebugLoc dl = MI.getDebugLoc();
12812 
12813     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12814     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12815     // If the target doesn't have DirectMove, we should use stack to do the
12816     // conversion, because the target doesn't have the instructions like mtvsrd
12817     // or mfvsrd to do this conversion directly.
12818     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12819       if (Subtarget.hasDirectMove()) {
12820         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12821           .addReg(SrcReg);
12822       } else {
12823         // Use stack to do the register copy.
12824         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12825         MachineRegisterInfo &RegInfo = F->getRegInfo();
12826         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12827         if (RC == &PPC::F8RCRegClass) {
12828           // Copy register from F8RCRegClass to G8RCRegclass.
12829           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12830                  "Unsupported RegClass.");
12831 
12832           StoreOp = PPC::STFD;
12833           LoadOp = PPC::LD;
12834         } else {
12835           // Copy register from G8RCRegClass to F8RCRegclass.
12836           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12837                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12838                  "Unsupported RegClass.");
12839         }
12840 
12841         MachineFrameInfo &MFI = F->getFrameInfo();
12842         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12843 
12844         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12845             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12846             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12847             MFI.getObjectAlign(FrameIdx));
12848 
12849         // Store the SrcReg into the stack.
12850         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12851           .addReg(SrcReg)
12852           .addImm(0)
12853           .addFrameIndex(FrameIdx)
12854           .addMemOperand(MMOStore);
12855 
12856         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12857             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12858             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12859             MFI.getObjectAlign(FrameIdx));
12860 
12861         // Load from the stack where SrcReg is stored, and save to DestReg,
12862         // so we have done the RegClass conversion from RegClass::SrcReg to
12863         // RegClass::DestReg.
12864         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12865           .addImm(0)
12866           .addFrameIndex(FrameIdx)
12867           .addMemOperand(MMOLoad);
12868       }
12869     };
12870 
12871     Register OldFPSCRReg = MI.getOperand(0).getReg();
12872 
12873     // Save FPSCR value.
12874     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12875 
12876     // When the operand is gprc register, use two least significant bits of the
12877     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12878     //
12879     // copy OldFPSCRTmpReg, OldFPSCRReg
12880     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12881     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12882     // copy NewFPSCRReg, NewFPSCRTmpReg
12883     // mtfsf 255, NewFPSCRReg
12884     MachineOperand SrcOp = MI.getOperand(1);
12885     MachineRegisterInfo &RegInfo = F->getRegInfo();
12886     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12887 
12888     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12889 
12890     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12891     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12892 
12893     // The first operand of INSERT_SUBREG should be a register which has
12894     // subregisters, we only care about its RegClass, so we should use an
12895     // IMPLICIT_DEF register.
12896     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12897     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12898       .addReg(ImDefReg)
12899       .add(SrcOp)
12900       .addImm(1);
12901 
12902     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12903     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12904       .addReg(OldFPSCRTmpReg)
12905       .addReg(ExtSrcReg)
12906       .addImm(0)
12907       .addImm(62);
12908 
12909     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12910     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12911 
12912     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12913     // bits of FPSCR.
12914     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12915       .addImm(255)
12916       .addReg(NewFPSCRReg)
12917       .addImm(0)
12918       .addImm(0);
12919   } else if (MI.getOpcode() == PPC::SETFLM) {
12920     DebugLoc Dl = MI.getDebugLoc();
12921 
12922     // Result of setflm is previous FPSCR content, so we need to save it first.
12923     Register OldFPSCRReg = MI.getOperand(0).getReg();
12924     if (MRI.use_empty(OldFPSCRReg))
12925       BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12926     else
12927       BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12928 
12929     // Put bits in 32:63 to FPSCR.
12930     Register NewFPSCRReg = MI.getOperand(1).getReg();
12931     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12932         .addImm(255)
12933         .addReg(NewFPSCRReg)
12934         .addImm(0)
12935         .addImm(0);
12936   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12937              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12938     return emitProbedAlloca(MI, BB);
12939   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12940     DebugLoc DL = MI.getDebugLoc();
12941     Register Src = MI.getOperand(2).getReg();
12942     Register Lo = MI.getOperand(0).getReg();
12943     Register Hi = MI.getOperand(1).getReg();
12944     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12945         .addDef(Lo)
12946         .addUse(Src, 0, PPC::sub_gp8_x1);
12947     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12948         .addDef(Hi)
12949         .addUse(Src, 0, PPC::sub_gp8_x0);
12950   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12951              MI.getOpcode() == PPC::STQX_PSEUDO) {
12952     DebugLoc DL = MI.getDebugLoc();
12953     // Ptr is used as the ptr_rc_no_r0 part
12954     // of LQ/STQ's memory operand and adding result of RA and RB,
12955     // so it has to be g8rc_and_g8rc_nox0.
12956     Register Ptr =
12957         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12958     Register Val = MI.getOperand(0).getReg();
12959     Register RA = MI.getOperand(1).getReg();
12960     Register RB = MI.getOperand(2).getReg();
12961     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12962     BuildMI(*BB, MI, DL,
12963             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12964                                               : TII->get(PPC::STQ))
12965         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12966         .addImm(0)
12967         .addReg(Ptr);
12968   } else {
12969     llvm_unreachable("Unexpected instr type to insert");
12970   }
12971 
12972   MI.eraseFromParent(); // The pseudo instruction is gone now.
12973   return BB;
12974 }
12975 
12976 //===----------------------------------------------------------------------===//
12977 // Target Optimization Hooks
12978 //===----------------------------------------------------------------------===//
12979 
12980 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12981   // For the estimates, convergence is quadratic, so we essentially double the
12982   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12983   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12984   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12985   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12986   if (VT.getScalarType() == MVT::f64)
12987     RefinementSteps++;
12988   return RefinementSteps;
12989 }
12990 
12991 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12992                                             const DenormalMode &Mode) const {
12993   // We only have VSX Vector Test for software Square Root.
12994   EVT VT = Op.getValueType();
12995   if (!isTypeLegal(MVT::i1) ||
12996       (VT != MVT::f64 &&
12997        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
12998     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
12999 
13000   SDLoc DL(Op);
13001   // The output register of FTSQRT is CR field.
13002   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
13003   // ftsqrt BF,FRB
13004   // Let e_b be the unbiased exponent of the double-precision
13005   // floating-point operand in register FRB.
13006   // fe_flag is set to 1 if either of the following conditions occurs.
13007   //   - The double-precision floating-point operand in register FRB is a zero,
13008   //     a NaN, or an infinity, or a negative value.
13009   //   - e_b is less than or equal to -970.
13010   // Otherwise fe_flag is set to 0.
13011   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
13012   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
13013   // exponent is less than -970)
13014   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
13015   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
13016                                     FTSQRT, SRIdxVal),
13017                  0);
13018 }
13019 
13020 SDValue
13021 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
13022                                                SelectionDAG &DAG) const {
13023   // We only have VSX Vector Square Root.
13024   EVT VT = Op.getValueType();
13025   if (VT != MVT::f64 &&
13026       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
13027     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
13028 
13029   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
13030 }
13031 
13032 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
13033                                            int Enabled, int &RefinementSteps,
13034                                            bool &UseOneConstNR,
13035                                            bool Reciprocal) const {
13036   EVT VT = Operand.getValueType();
13037   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
13038       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
13039       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13040       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13041     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13042       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13043 
13044     // The Newton-Raphson computation with a single constant does not provide
13045     // enough accuracy on some CPUs.
13046     UseOneConstNR = !Subtarget.needsTwoConstNR();
13047     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
13048   }
13049   return SDValue();
13050 }
13051 
13052 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
13053                                             int Enabled,
13054                                             int &RefinementSteps) const {
13055   EVT VT = Operand.getValueType();
13056   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13057       (VT == MVT::f64 && Subtarget.hasFRE()) ||
13058       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13059       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13060     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13061       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13062     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13063   }
13064   return SDValue();
13065 }
13066 
13067 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13068   // Note: This functionality is used only when unsafe-fp-math is enabled, and
13069   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13070   // enabled for division), this functionality is redundant with the default
13071   // combiner logic (once the division -> reciprocal/multiply transformation
13072   // has taken place). As a result, this matters more for older cores than for
13073   // newer ones.
13074 
13075   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13076   // reciprocal if there are two or more FDIVs (for embedded cores with only
13077   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13078   switch (Subtarget.getCPUDirective()) {
13079   default:
13080     return 3;
13081   case PPC::DIR_440:
13082   case PPC::DIR_A2:
13083   case PPC::DIR_E500:
13084   case PPC::DIR_E500mc:
13085   case PPC::DIR_E5500:
13086     return 2;
13087   }
13088 }
13089 
13090 // isConsecutiveLSLoc needs to work even if all adds have not yet been
13091 // collapsed, and so we need to look through chains of them.
13092 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13093                                      int64_t& Offset, SelectionDAG &DAG) {
13094   if (DAG.isBaseWithConstantOffset(Loc)) {
13095     Base = Loc.getOperand(0);
13096     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13097 
13098     // The base might itself be a base plus an offset, and if so, accumulate
13099     // that as well.
13100     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13101   }
13102 }
13103 
13104 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13105                             unsigned Bytes, int Dist,
13106                             SelectionDAG &DAG) {
13107   if (VT.getSizeInBits() / 8 != Bytes)
13108     return false;
13109 
13110   SDValue BaseLoc = Base->getBasePtr();
13111   if (Loc.getOpcode() == ISD::FrameIndex) {
13112     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13113       return false;
13114     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13115     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13116     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13117     int FS  = MFI.getObjectSize(FI);
13118     int BFS = MFI.getObjectSize(BFI);
13119     if (FS != BFS || FS != (int)Bytes) return false;
13120     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13121   }
13122 
13123   SDValue Base1 = Loc, Base2 = BaseLoc;
13124   int64_t Offset1 = 0, Offset2 = 0;
13125   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13126   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13127   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13128     return true;
13129 
13130   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13131   const GlobalValue *GV1 = nullptr;
13132   const GlobalValue *GV2 = nullptr;
13133   Offset1 = 0;
13134   Offset2 = 0;
13135   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13136   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13137   if (isGA1 && isGA2 && GV1 == GV2)
13138     return Offset1 == (Offset2 + Dist*Bytes);
13139   return false;
13140 }
13141 
13142 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13143 // not enforce equality of the chain operands.
13144 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13145                             unsigned Bytes, int Dist,
13146                             SelectionDAG &DAG) {
13147   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13148     EVT VT = LS->getMemoryVT();
13149     SDValue Loc = LS->getBasePtr();
13150     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13151   }
13152 
13153   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13154     EVT VT;
13155     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13156     default: return false;
13157     case Intrinsic::ppc_altivec_lvx:
13158     case Intrinsic::ppc_altivec_lvxl:
13159     case Intrinsic::ppc_vsx_lxvw4x:
13160     case Intrinsic::ppc_vsx_lxvw4x_be:
13161       VT = MVT::v4i32;
13162       break;
13163     case Intrinsic::ppc_vsx_lxvd2x:
13164     case Intrinsic::ppc_vsx_lxvd2x_be:
13165       VT = MVT::v2f64;
13166       break;
13167     case Intrinsic::ppc_altivec_lvebx:
13168       VT = MVT::i8;
13169       break;
13170     case Intrinsic::ppc_altivec_lvehx:
13171       VT = MVT::i16;
13172       break;
13173     case Intrinsic::ppc_altivec_lvewx:
13174       VT = MVT::i32;
13175       break;
13176     }
13177 
13178     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13179   }
13180 
13181   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13182     EVT VT;
13183     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13184     default: return false;
13185     case Intrinsic::ppc_altivec_stvx:
13186     case Intrinsic::ppc_altivec_stvxl:
13187     case Intrinsic::ppc_vsx_stxvw4x:
13188       VT = MVT::v4i32;
13189       break;
13190     case Intrinsic::ppc_vsx_stxvd2x:
13191       VT = MVT::v2f64;
13192       break;
13193     case Intrinsic::ppc_vsx_stxvw4x_be:
13194       VT = MVT::v4i32;
13195       break;
13196     case Intrinsic::ppc_vsx_stxvd2x_be:
13197       VT = MVT::v2f64;
13198       break;
13199     case Intrinsic::ppc_altivec_stvebx:
13200       VT = MVT::i8;
13201       break;
13202     case Intrinsic::ppc_altivec_stvehx:
13203       VT = MVT::i16;
13204       break;
13205     case Intrinsic::ppc_altivec_stvewx:
13206       VT = MVT::i32;
13207       break;
13208     }
13209 
13210     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13211   }
13212 
13213   return false;
13214 }
13215 
13216 // Return true is there is a nearyby consecutive load to the one provided
13217 // (regardless of alignment). We search up and down the chain, looking though
13218 // token factors and other loads (but nothing else). As a result, a true result
13219 // indicates that it is safe to create a new consecutive load adjacent to the
13220 // load provided.
13221 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13222   SDValue Chain = LD->getChain();
13223   EVT VT = LD->getMemoryVT();
13224 
13225   SmallSet<SDNode *, 16> LoadRoots;
13226   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13227   SmallSet<SDNode *, 16> Visited;
13228 
13229   // First, search up the chain, branching to follow all token-factor operands.
13230   // If we find a consecutive load, then we're done, otherwise, record all
13231   // nodes just above the top-level loads and token factors.
13232   while (!Queue.empty()) {
13233     SDNode *ChainNext = Queue.pop_back_val();
13234     if (!Visited.insert(ChainNext).second)
13235       continue;
13236 
13237     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13238       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13239         return true;
13240 
13241       if (!Visited.count(ChainLD->getChain().getNode()))
13242         Queue.push_back(ChainLD->getChain().getNode());
13243     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13244       for (const SDUse &O : ChainNext->ops())
13245         if (!Visited.count(O.getNode()))
13246           Queue.push_back(O.getNode());
13247     } else
13248       LoadRoots.insert(ChainNext);
13249   }
13250 
13251   // Second, search down the chain, starting from the top-level nodes recorded
13252   // in the first phase. These top-level nodes are the nodes just above all
13253   // loads and token factors. Starting with their uses, recursively look though
13254   // all loads (just the chain uses) and token factors to find a consecutive
13255   // load.
13256   Visited.clear();
13257   Queue.clear();
13258 
13259   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13260        IE = LoadRoots.end(); I != IE; ++I) {
13261     Queue.push_back(*I);
13262 
13263     while (!Queue.empty()) {
13264       SDNode *LoadRoot = Queue.pop_back_val();
13265       if (!Visited.insert(LoadRoot).second)
13266         continue;
13267 
13268       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13269         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13270           return true;
13271 
13272       for (SDNode *U : LoadRoot->uses())
13273         if (((isa<MemSDNode>(U) &&
13274               cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13275              U->getOpcode() == ISD::TokenFactor) &&
13276             !Visited.count(U))
13277           Queue.push_back(U);
13278     }
13279   }
13280 
13281   return false;
13282 }
13283 
13284 /// This function is called when we have proved that a SETCC node can be replaced
13285 /// by subtraction (and other supporting instructions) so that the result of
13286 /// comparison is kept in a GPR instead of CR. This function is purely for
13287 /// codegen purposes and has some flags to guide the codegen process.
13288 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13289                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13290   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13291 
13292   // Zero extend the operands to the largest legal integer. Originally, they
13293   // must be of a strictly smaller size.
13294   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13295                          DAG.getConstant(Size, DL, MVT::i32));
13296   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13297                          DAG.getConstant(Size, DL, MVT::i32));
13298 
13299   // Swap if needed. Depends on the condition code.
13300   if (Swap)
13301     std::swap(Op0, Op1);
13302 
13303   // Subtract extended integers.
13304   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13305 
13306   // Move the sign bit to the least significant position and zero out the rest.
13307   // Now the least significant bit carries the result of original comparison.
13308   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13309                              DAG.getConstant(Size - 1, DL, MVT::i32));
13310   auto Final = Shifted;
13311 
13312   // Complement the result if needed. Based on the condition code.
13313   if (Complement)
13314     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13315                         DAG.getConstant(1, DL, MVT::i64));
13316 
13317   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13318 }
13319 
13320 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13321                                                   DAGCombinerInfo &DCI) const {
13322   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13323 
13324   SelectionDAG &DAG = DCI.DAG;
13325   SDLoc DL(N);
13326 
13327   // Size of integers being compared has a critical role in the following
13328   // analysis, so we prefer to do this when all types are legal.
13329   if (!DCI.isAfterLegalizeDAG())
13330     return SDValue();
13331 
13332   // If all users of SETCC extend its value to a legal integer type
13333   // then we replace SETCC with a subtraction
13334   for (const SDNode *U : N->uses())
13335     if (U->getOpcode() != ISD::ZERO_EXTEND)
13336       return SDValue();
13337 
13338   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13339   auto OpSize = N->getOperand(0).getValueSizeInBits();
13340 
13341   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13342 
13343   if (OpSize < Size) {
13344     switch (CC) {
13345     default: break;
13346     case ISD::SETULT:
13347       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13348     case ISD::SETULE:
13349       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13350     case ISD::SETUGT:
13351       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13352     case ISD::SETUGE:
13353       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13354     }
13355   }
13356 
13357   return SDValue();
13358 }
13359 
13360 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13361                                                   DAGCombinerInfo &DCI) const {
13362   SelectionDAG &DAG = DCI.DAG;
13363   SDLoc dl(N);
13364 
13365   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13366   // If we're tracking CR bits, we need to be careful that we don't have:
13367   //   trunc(binary-ops(zext(x), zext(y)))
13368   // or
13369   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13370   // such that we're unnecessarily moving things into GPRs when it would be
13371   // better to keep them in CR bits.
13372 
13373   // Note that trunc here can be an actual i1 trunc, or can be the effective
13374   // truncation that comes from a setcc or select_cc.
13375   if (N->getOpcode() == ISD::TRUNCATE &&
13376       N->getValueType(0) != MVT::i1)
13377     return SDValue();
13378 
13379   if (N->getOperand(0).getValueType() != MVT::i32 &&
13380       N->getOperand(0).getValueType() != MVT::i64)
13381     return SDValue();
13382 
13383   if (N->getOpcode() == ISD::SETCC ||
13384       N->getOpcode() == ISD::SELECT_CC) {
13385     // If we're looking at a comparison, then we need to make sure that the
13386     // high bits (all except for the first) don't matter the result.
13387     ISD::CondCode CC =
13388       cast<CondCodeSDNode>(N->getOperand(
13389         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13390     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13391 
13392     if (ISD::isSignedIntSetCC(CC)) {
13393       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13394           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13395         return SDValue();
13396     } else if (ISD::isUnsignedIntSetCC(CC)) {
13397       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13398                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13399           !DAG.MaskedValueIsZero(N->getOperand(1),
13400                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13401         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13402                                              : SDValue());
13403     } else {
13404       // This is neither a signed nor an unsigned comparison, just make sure
13405       // that the high bits are equal.
13406       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13407       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13408 
13409       // We don't really care about what is known about the first bit (if
13410       // anything), so pretend that it is known zero for both to ensure they can
13411       // be compared as constants.
13412       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13413       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13414 
13415       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13416           Op1Known.getConstant() != Op2Known.getConstant())
13417         return SDValue();
13418     }
13419   }
13420 
13421   // We now know that the higher-order bits are irrelevant, we just need to
13422   // make sure that all of the intermediate operations are bit operations, and
13423   // all inputs are extensions.
13424   if (N->getOperand(0).getOpcode() != ISD::AND &&
13425       N->getOperand(0).getOpcode() != ISD::OR  &&
13426       N->getOperand(0).getOpcode() != ISD::XOR &&
13427       N->getOperand(0).getOpcode() != ISD::SELECT &&
13428       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13429       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13430       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13431       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13432       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13433     return SDValue();
13434 
13435   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13436       N->getOperand(1).getOpcode() != ISD::AND &&
13437       N->getOperand(1).getOpcode() != ISD::OR  &&
13438       N->getOperand(1).getOpcode() != ISD::XOR &&
13439       N->getOperand(1).getOpcode() != ISD::SELECT &&
13440       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13441       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13442       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13443       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13444       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13445     return SDValue();
13446 
13447   SmallVector<SDValue, 4> Inputs;
13448   SmallVector<SDValue, 8> BinOps, PromOps;
13449   SmallPtrSet<SDNode *, 16> Visited;
13450 
13451   for (unsigned i = 0; i < 2; ++i) {
13452     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13453           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13454           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13455           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13456         isa<ConstantSDNode>(N->getOperand(i)))
13457       Inputs.push_back(N->getOperand(i));
13458     else
13459       BinOps.push_back(N->getOperand(i));
13460 
13461     if (N->getOpcode() == ISD::TRUNCATE)
13462       break;
13463   }
13464 
13465   // Visit all inputs, collect all binary operations (and, or, xor and
13466   // select) that are all fed by extensions.
13467   while (!BinOps.empty()) {
13468     SDValue BinOp = BinOps.pop_back_val();
13469 
13470     if (!Visited.insert(BinOp.getNode()).second)
13471       continue;
13472 
13473     PromOps.push_back(BinOp);
13474 
13475     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13476       // The condition of the select is not promoted.
13477       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13478         continue;
13479       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13480         continue;
13481 
13482       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13483             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13484             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13485            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13486           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13487         Inputs.push_back(BinOp.getOperand(i));
13488       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13489                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13490                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13491                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13492                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13493                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13494                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13495                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13496                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13497         BinOps.push_back(BinOp.getOperand(i));
13498       } else {
13499         // We have an input that is not an extension or another binary
13500         // operation; we'll abort this transformation.
13501         return SDValue();
13502       }
13503     }
13504   }
13505 
13506   // Make sure that this is a self-contained cluster of operations (which
13507   // is not quite the same thing as saying that everything has only one
13508   // use).
13509   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13510     if (isa<ConstantSDNode>(Inputs[i]))
13511       continue;
13512 
13513     for (const SDNode *User : Inputs[i].getNode()->uses()) {
13514       if (User != N && !Visited.count(User))
13515         return SDValue();
13516 
13517       // Make sure that we're not going to promote the non-output-value
13518       // operand(s) or SELECT or SELECT_CC.
13519       // FIXME: Although we could sometimes handle this, and it does occur in
13520       // practice that one of the condition inputs to the select is also one of
13521       // the outputs, we currently can't deal with this.
13522       if (User->getOpcode() == ISD::SELECT) {
13523         if (User->getOperand(0) == Inputs[i])
13524           return SDValue();
13525       } else if (User->getOpcode() == ISD::SELECT_CC) {
13526         if (User->getOperand(0) == Inputs[i] ||
13527             User->getOperand(1) == Inputs[i])
13528           return SDValue();
13529       }
13530     }
13531   }
13532 
13533   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13534     for (const SDNode *User : PromOps[i].getNode()->uses()) {
13535       if (User != N && !Visited.count(User))
13536         return SDValue();
13537 
13538       // Make sure that we're not going to promote the non-output-value
13539       // operand(s) or SELECT or SELECT_CC.
13540       // FIXME: Although we could sometimes handle this, and it does occur in
13541       // practice that one of the condition inputs to the select is also one of
13542       // the outputs, we currently can't deal with this.
13543       if (User->getOpcode() == ISD::SELECT) {
13544         if (User->getOperand(0) == PromOps[i])
13545           return SDValue();
13546       } else if (User->getOpcode() == ISD::SELECT_CC) {
13547         if (User->getOperand(0) == PromOps[i] ||
13548             User->getOperand(1) == PromOps[i])
13549           return SDValue();
13550       }
13551     }
13552   }
13553 
13554   // Replace all inputs with the extension operand.
13555   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13556     // Constants may have users outside the cluster of to-be-promoted nodes,
13557     // and so we need to replace those as we do the promotions.
13558     if (isa<ConstantSDNode>(Inputs[i]))
13559       continue;
13560     else
13561       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13562   }
13563 
13564   std::list<HandleSDNode> PromOpHandles;
13565   for (auto &PromOp : PromOps)
13566     PromOpHandles.emplace_back(PromOp);
13567 
13568   // Replace all operations (these are all the same, but have a different
13569   // (i1) return type). DAG.getNode will validate that the types of
13570   // a binary operator match, so go through the list in reverse so that
13571   // we've likely promoted both operands first. Any intermediate truncations or
13572   // extensions disappear.
13573   while (!PromOpHandles.empty()) {
13574     SDValue PromOp = PromOpHandles.back().getValue();
13575     PromOpHandles.pop_back();
13576 
13577     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13578         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13579         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13580         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13581       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13582           PromOp.getOperand(0).getValueType() != MVT::i1) {
13583         // The operand is not yet ready (see comment below).
13584         PromOpHandles.emplace_front(PromOp);
13585         continue;
13586       }
13587 
13588       SDValue RepValue = PromOp.getOperand(0);
13589       if (isa<ConstantSDNode>(RepValue))
13590         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13591 
13592       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13593       continue;
13594     }
13595 
13596     unsigned C;
13597     switch (PromOp.getOpcode()) {
13598     default:             C = 0; break;
13599     case ISD::SELECT:    C = 1; break;
13600     case ISD::SELECT_CC: C = 2; break;
13601     }
13602 
13603     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13604          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13605         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13606          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13607       // The to-be-promoted operands of this node have not yet been
13608       // promoted (this should be rare because we're going through the
13609       // list backward, but if one of the operands has several users in
13610       // this cluster of to-be-promoted nodes, it is possible).
13611       PromOpHandles.emplace_front(PromOp);
13612       continue;
13613     }
13614 
13615     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13616                                 PromOp.getNode()->op_end());
13617 
13618     // If there are any constant inputs, make sure they're replaced now.
13619     for (unsigned i = 0; i < 2; ++i)
13620       if (isa<ConstantSDNode>(Ops[C+i]))
13621         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13622 
13623     DAG.ReplaceAllUsesOfValueWith(PromOp,
13624       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13625   }
13626 
13627   // Now we're left with the initial truncation itself.
13628   if (N->getOpcode() == ISD::TRUNCATE)
13629     return N->getOperand(0);
13630 
13631   // Otherwise, this is a comparison. The operands to be compared have just
13632   // changed type (to i1), but everything else is the same.
13633   return SDValue(N, 0);
13634 }
13635 
13636 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13637                                                   DAGCombinerInfo &DCI) const {
13638   SelectionDAG &DAG = DCI.DAG;
13639   SDLoc dl(N);
13640 
13641   // If we're tracking CR bits, we need to be careful that we don't have:
13642   //   zext(binary-ops(trunc(x), trunc(y)))
13643   // or
13644   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13645   // such that we're unnecessarily moving things into CR bits that can more
13646   // efficiently stay in GPRs. Note that if we're not certain that the high
13647   // bits are set as required by the final extension, we still may need to do
13648   // some masking to get the proper behavior.
13649 
13650   // This same functionality is important on PPC64 when dealing with
13651   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13652   // the return values of functions. Because it is so similar, it is handled
13653   // here as well.
13654 
13655   if (N->getValueType(0) != MVT::i32 &&
13656       N->getValueType(0) != MVT::i64)
13657     return SDValue();
13658 
13659   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13660         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13661     return SDValue();
13662 
13663   if (N->getOperand(0).getOpcode() != ISD::AND &&
13664       N->getOperand(0).getOpcode() != ISD::OR  &&
13665       N->getOperand(0).getOpcode() != ISD::XOR &&
13666       N->getOperand(0).getOpcode() != ISD::SELECT &&
13667       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13668     return SDValue();
13669 
13670   SmallVector<SDValue, 4> Inputs;
13671   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13672   SmallPtrSet<SDNode *, 16> Visited;
13673 
13674   // Visit all inputs, collect all binary operations (and, or, xor and
13675   // select) that are all fed by truncations.
13676   while (!BinOps.empty()) {
13677     SDValue BinOp = BinOps.pop_back_val();
13678 
13679     if (!Visited.insert(BinOp.getNode()).second)
13680       continue;
13681 
13682     PromOps.push_back(BinOp);
13683 
13684     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13685       // The condition of the select is not promoted.
13686       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13687         continue;
13688       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13689         continue;
13690 
13691       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13692           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13693         Inputs.push_back(BinOp.getOperand(i));
13694       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13695                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13696                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13697                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13698                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13699         BinOps.push_back(BinOp.getOperand(i));
13700       } else {
13701         // We have an input that is not a truncation or another binary
13702         // operation; we'll abort this transformation.
13703         return SDValue();
13704       }
13705     }
13706   }
13707 
13708   // The operands of a select that must be truncated when the select is
13709   // promoted because the operand is actually part of the to-be-promoted set.
13710   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13711 
13712   // Make sure that this is a self-contained cluster of operations (which
13713   // is not quite the same thing as saying that everything has only one
13714   // use).
13715   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13716     if (isa<ConstantSDNode>(Inputs[i]))
13717       continue;
13718 
13719     for (SDNode *User : Inputs[i].getNode()->uses()) {
13720       if (User != N && !Visited.count(User))
13721         return SDValue();
13722 
13723       // If we're going to promote the non-output-value operand(s) or SELECT or
13724       // SELECT_CC, record them for truncation.
13725       if (User->getOpcode() == ISD::SELECT) {
13726         if (User->getOperand(0) == Inputs[i])
13727           SelectTruncOp[0].insert(std::make_pair(User,
13728                                     User->getOperand(0).getValueType()));
13729       } else if (User->getOpcode() == ISD::SELECT_CC) {
13730         if (User->getOperand(0) == Inputs[i])
13731           SelectTruncOp[0].insert(std::make_pair(User,
13732                                     User->getOperand(0).getValueType()));
13733         if (User->getOperand(1) == Inputs[i])
13734           SelectTruncOp[1].insert(std::make_pair(User,
13735                                     User->getOperand(1).getValueType()));
13736       }
13737     }
13738   }
13739 
13740   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13741     for (SDNode *User : PromOps[i].getNode()->uses()) {
13742       if (User != N && !Visited.count(User))
13743         return SDValue();
13744 
13745       // If we're going to promote the non-output-value operand(s) or SELECT or
13746       // SELECT_CC, record them for truncation.
13747       if (User->getOpcode() == ISD::SELECT) {
13748         if (User->getOperand(0) == PromOps[i])
13749           SelectTruncOp[0].insert(std::make_pair(User,
13750                                     User->getOperand(0).getValueType()));
13751       } else if (User->getOpcode() == ISD::SELECT_CC) {
13752         if (User->getOperand(0) == PromOps[i])
13753           SelectTruncOp[0].insert(std::make_pair(User,
13754                                     User->getOperand(0).getValueType()));
13755         if (User->getOperand(1) == PromOps[i])
13756           SelectTruncOp[1].insert(std::make_pair(User,
13757                                     User->getOperand(1).getValueType()));
13758       }
13759     }
13760   }
13761 
13762   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13763   bool ReallyNeedsExt = false;
13764   if (N->getOpcode() != ISD::ANY_EXTEND) {
13765     // If all of the inputs are not already sign/zero extended, then
13766     // we'll still need to do that at the end.
13767     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13768       if (isa<ConstantSDNode>(Inputs[i]))
13769         continue;
13770 
13771       unsigned OpBits =
13772         Inputs[i].getOperand(0).getValueSizeInBits();
13773       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13774 
13775       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13776            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13777                                   APInt::getHighBitsSet(OpBits,
13778                                                         OpBits-PromBits))) ||
13779           (N->getOpcode() == ISD::SIGN_EXTEND &&
13780            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13781              (OpBits-(PromBits-1)))) {
13782         ReallyNeedsExt = true;
13783         break;
13784       }
13785     }
13786   }
13787 
13788   // Replace all inputs, either with the truncation operand, or a
13789   // truncation or extension to the final output type.
13790   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13791     // Constant inputs need to be replaced with the to-be-promoted nodes that
13792     // use them because they might have users outside of the cluster of
13793     // promoted nodes.
13794     if (isa<ConstantSDNode>(Inputs[i]))
13795       continue;
13796 
13797     SDValue InSrc = Inputs[i].getOperand(0);
13798     if (Inputs[i].getValueType() == N->getValueType(0))
13799       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13800     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13801       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13802         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13803     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13804       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13805         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13806     else
13807       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13808         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13809   }
13810 
13811   std::list<HandleSDNode> PromOpHandles;
13812   for (auto &PromOp : PromOps)
13813     PromOpHandles.emplace_back(PromOp);
13814 
13815   // Replace all operations (these are all the same, but have a different
13816   // (promoted) return type). DAG.getNode will validate that the types of
13817   // a binary operator match, so go through the list in reverse so that
13818   // we've likely promoted both operands first.
13819   while (!PromOpHandles.empty()) {
13820     SDValue PromOp = PromOpHandles.back().getValue();
13821     PromOpHandles.pop_back();
13822 
13823     unsigned C;
13824     switch (PromOp.getOpcode()) {
13825     default:             C = 0; break;
13826     case ISD::SELECT:    C = 1; break;
13827     case ISD::SELECT_CC: C = 2; break;
13828     }
13829 
13830     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13831          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13832         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13833          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13834       // The to-be-promoted operands of this node have not yet been
13835       // promoted (this should be rare because we're going through the
13836       // list backward, but if one of the operands has several users in
13837       // this cluster of to-be-promoted nodes, it is possible).
13838       PromOpHandles.emplace_front(PromOp);
13839       continue;
13840     }
13841 
13842     // For SELECT and SELECT_CC nodes, we do a similar check for any
13843     // to-be-promoted comparison inputs.
13844     if (PromOp.getOpcode() == ISD::SELECT ||
13845         PromOp.getOpcode() == ISD::SELECT_CC) {
13846       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13847            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13848           (SelectTruncOp[1].count(PromOp.getNode()) &&
13849            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13850         PromOpHandles.emplace_front(PromOp);
13851         continue;
13852       }
13853     }
13854 
13855     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13856                                 PromOp.getNode()->op_end());
13857 
13858     // If this node has constant inputs, then they'll need to be promoted here.
13859     for (unsigned i = 0; i < 2; ++i) {
13860       if (!isa<ConstantSDNode>(Ops[C+i]))
13861         continue;
13862       if (Ops[C+i].getValueType() == N->getValueType(0))
13863         continue;
13864 
13865       if (N->getOpcode() == ISD::SIGN_EXTEND)
13866         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13867       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13868         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13869       else
13870         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13871     }
13872 
13873     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13874     // truncate them again to the original value type.
13875     if (PromOp.getOpcode() == ISD::SELECT ||
13876         PromOp.getOpcode() == ISD::SELECT_CC) {
13877       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13878       if (SI0 != SelectTruncOp[0].end())
13879         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13880       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13881       if (SI1 != SelectTruncOp[1].end())
13882         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13883     }
13884 
13885     DAG.ReplaceAllUsesOfValueWith(PromOp,
13886       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13887   }
13888 
13889   // Now we're left with the initial extension itself.
13890   if (!ReallyNeedsExt)
13891     return N->getOperand(0);
13892 
13893   // To zero extend, just mask off everything except for the first bit (in the
13894   // i1 case).
13895   if (N->getOpcode() == ISD::ZERO_EXTEND)
13896     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13897                        DAG.getConstant(APInt::getLowBitsSet(
13898                                          N->getValueSizeInBits(0), PromBits),
13899                                        dl, N->getValueType(0)));
13900 
13901   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13902          "Invalid extension type");
13903   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13904   SDValue ShiftCst =
13905       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13906   return DAG.getNode(
13907       ISD::SRA, dl, N->getValueType(0),
13908       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13909       ShiftCst);
13910 }
13911 
13912 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13913                                         DAGCombinerInfo &DCI) const {
13914   assert(N->getOpcode() == ISD::SETCC &&
13915          "Should be called with a SETCC node");
13916 
13917   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13918   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13919     SDValue LHS = N->getOperand(0);
13920     SDValue RHS = N->getOperand(1);
13921 
13922     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13923     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13924         LHS.hasOneUse())
13925       std::swap(LHS, RHS);
13926 
13927     // x == 0-y --> x+y == 0
13928     // x != 0-y --> x+y != 0
13929     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13930         RHS.hasOneUse()) {
13931       SDLoc DL(N);
13932       SelectionDAG &DAG = DCI.DAG;
13933       EVT VT = N->getValueType(0);
13934       EVT OpVT = LHS.getValueType();
13935       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13936       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13937     }
13938   }
13939 
13940   return DAGCombineTruncBoolExt(N, DCI);
13941 }
13942 
13943 // Is this an extending load from an f32 to an f64?
13944 static bool isFPExtLoad(SDValue Op) {
13945   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13946     return LD->getExtensionType() == ISD::EXTLOAD &&
13947       Op.getValueType() == MVT::f64;
13948   return false;
13949 }
13950 
13951 /// Reduces the number of fp-to-int conversion when building a vector.
13952 ///
13953 /// If this vector is built out of floating to integer conversions,
13954 /// transform it to a vector built out of floating point values followed by a
13955 /// single floating to integer conversion of the vector.
13956 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13957 /// becomes (fptosi (build_vector ($A, $B, ...)))
13958 SDValue PPCTargetLowering::
13959 combineElementTruncationToVectorTruncation(SDNode *N,
13960                                            DAGCombinerInfo &DCI) const {
13961   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13962          "Should be called with a BUILD_VECTOR node");
13963 
13964   SelectionDAG &DAG = DCI.DAG;
13965   SDLoc dl(N);
13966 
13967   SDValue FirstInput = N->getOperand(0);
13968   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13969          "The input operand must be an fp-to-int conversion.");
13970 
13971   // This combine happens after legalization so the fp_to_[su]i nodes are
13972   // already converted to PPCSISD nodes.
13973   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13974   if (FirstConversion == PPCISD::FCTIDZ ||
13975       FirstConversion == PPCISD::FCTIDUZ ||
13976       FirstConversion == PPCISD::FCTIWZ ||
13977       FirstConversion == PPCISD::FCTIWUZ) {
13978     bool IsSplat = true;
13979     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13980       FirstConversion == PPCISD::FCTIWUZ;
13981     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13982     SmallVector<SDValue, 4> Ops;
13983     EVT TargetVT = N->getValueType(0);
13984     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13985       SDValue NextOp = N->getOperand(i);
13986       if (NextOp.getOpcode() != PPCISD::MFVSR)
13987         return SDValue();
13988       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13989       if (NextConversion != FirstConversion)
13990         return SDValue();
13991       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13992       // This is not valid if the input was originally double precision. It is
13993       // also not profitable to do unless this is an extending load in which
13994       // case doing this combine will allow us to combine consecutive loads.
13995       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13996         return SDValue();
13997       if (N->getOperand(i) != FirstInput)
13998         IsSplat = false;
13999     }
14000 
14001     // If this is a splat, we leave it as-is since there will be only a single
14002     // fp-to-int conversion followed by a splat of the integer. This is better
14003     // for 32-bit and smaller ints and neutral for 64-bit ints.
14004     if (IsSplat)
14005       return SDValue();
14006 
14007     // Now that we know we have the right type of node, get its operands
14008     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14009       SDValue In = N->getOperand(i).getOperand(0);
14010       if (Is32Bit) {
14011         // For 32-bit values, we need to add an FP_ROUND node (if we made it
14012         // here, we know that all inputs are extending loads so this is safe).
14013         if (In.isUndef())
14014           Ops.push_back(DAG.getUNDEF(SrcVT));
14015         else {
14016           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
14017                                       MVT::f32, In.getOperand(0),
14018                                       DAG.getIntPtrConstant(1, dl));
14019           Ops.push_back(Trunc);
14020         }
14021       } else
14022         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
14023     }
14024 
14025     unsigned Opcode;
14026     if (FirstConversion == PPCISD::FCTIDZ ||
14027         FirstConversion == PPCISD::FCTIWZ)
14028       Opcode = ISD::FP_TO_SINT;
14029     else
14030       Opcode = ISD::FP_TO_UINT;
14031 
14032     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
14033     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
14034     return DAG.getNode(Opcode, dl, TargetVT, BV);
14035   }
14036   return SDValue();
14037 }
14038 
14039 /// Reduce the number of loads when building a vector.
14040 ///
14041 /// Building a vector out of multiple loads can be converted to a load
14042 /// of the vector type if the loads are consecutive. If the loads are
14043 /// consecutive but in descending order, a shuffle is added at the end
14044 /// to reorder the vector.
14045 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
14046   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14047          "Should be called with a BUILD_VECTOR node");
14048 
14049   SDLoc dl(N);
14050 
14051   // Return early for non byte-sized type, as they can't be consecutive.
14052   if (!N->getValueType(0).getVectorElementType().isByteSized())
14053     return SDValue();
14054 
14055   bool InputsAreConsecutiveLoads = true;
14056   bool InputsAreReverseConsecutive = true;
14057   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14058   SDValue FirstInput = N->getOperand(0);
14059   bool IsRoundOfExtLoad = false;
14060 
14061   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14062       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14063     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
14064     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
14065   }
14066   // Not a build vector of (possibly fp_rounded) loads.
14067   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14068       N->getNumOperands() == 1)
14069     return SDValue();
14070 
14071   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14072     // If any inputs are fp_round(extload), they all must be.
14073     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14074       return SDValue();
14075 
14076     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14077       N->getOperand(i);
14078     if (NextInput.getOpcode() != ISD::LOAD)
14079       return SDValue();
14080 
14081     SDValue PreviousInput =
14082       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14083     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
14084     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
14085 
14086     // If any inputs are fp_round(extload), they all must be.
14087     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14088       return SDValue();
14089 
14090     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
14091       InputsAreConsecutiveLoads = false;
14092     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14093       InputsAreReverseConsecutive = false;
14094 
14095     // Exit early if the loads are neither consecutive nor reverse consecutive.
14096     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14097       return SDValue();
14098   }
14099 
14100   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14101          "The loads cannot be both consecutive and reverse consecutive.");
14102 
14103   SDValue FirstLoadOp =
14104     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14105   SDValue LastLoadOp =
14106     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14107                        N->getOperand(N->getNumOperands()-1);
14108 
14109   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14110   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14111   if (InputsAreConsecutiveLoads) {
14112     assert(LD1 && "Input needs to be a LoadSDNode.");
14113     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14114                        LD1->getBasePtr(), LD1->getPointerInfo(),
14115                        LD1->getAlignment());
14116   }
14117   if (InputsAreReverseConsecutive) {
14118     assert(LDL && "Input needs to be a LoadSDNode.");
14119     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14120                                LDL->getBasePtr(), LDL->getPointerInfo(),
14121                                LDL->getAlignment());
14122     SmallVector<int, 16> Ops;
14123     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14124       Ops.push_back(i);
14125 
14126     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14127                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14128   }
14129   return SDValue();
14130 }
14131 
14132 // This function adds the required vector_shuffle needed to get
14133 // the elements of the vector extract in the correct position
14134 // as specified by the CorrectElems encoding.
14135 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14136                                       SDValue Input, uint64_t Elems,
14137                                       uint64_t CorrectElems) {
14138   SDLoc dl(N);
14139 
14140   unsigned NumElems = Input.getValueType().getVectorNumElements();
14141   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14142 
14143   // Knowing the element indices being extracted from the original
14144   // vector and the order in which they're being inserted, just put
14145   // them at element indices required for the instruction.
14146   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14147     if (DAG.getDataLayout().isLittleEndian())
14148       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14149     else
14150       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14151     CorrectElems = CorrectElems >> 8;
14152     Elems = Elems >> 8;
14153   }
14154 
14155   SDValue Shuffle =
14156       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14157                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14158 
14159   EVT VT = N->getValueType(0);
14160   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14161 
14162   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14163                                Input.getValueType().getVectorElementType(),
14164                                VT.getVectorNumElements());
14165   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14166                      DAG.getValueType(ExtVT));
14167 }
14168 
14169 // Look for build vector patterns where input operands come from sign
14170 // extended vector_extract elements of specific indices. If the correct indices
14171 // aren't used, add a vector shuffle to fix up the indices and create
14172 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14173 // during instruction selection.
14174 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14175   // This array encodes the indices that the vector sign extend instructions
14176   // extract from when extending from one type to another for both BE and LE.
14177   // The right nibble of each byte corresponds to the LE incides.
14178   // and the left nibble of each byte corresponds to the BE incides.
14179   // For example: 0x3074B8FC  byte->word
14180   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14181   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14182   // For example: 0x000070F8  byte->double word
14183   // For LE: the allowed indices are: 0x0,0x8
14184   // For BE: the allowed indices are: 0x7,0xF
14185   uint64_t TargetElems[] = {
14186       0x3074B8FC, // b->w
14187       0x000070F8, // b->d
14188       0x10325476, // h->w
14189       0x00003074, // h->d
14190       0x00001032, // w->d
14191   };
14192 
14193   uint64_t Elems = 0;
14194   int Index;
14195   SDValue Input;
14196 
14197   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14198     if (!Op)
14199       return false;
14200     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14201         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14202       return false;
14203 
14204     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14205     // of the right width.
14206     SDValue Extract = Op.getOperand(0);
14207     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14208       Extract = Extract.getOperand(0);
14209     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14210       return false;
14211 
14212     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14213     if (!ExtOp)
14214       return false;
14215 
14216     Index = ExtOp->getZExtValue();
14217     if (Input && Input != Extract.getOperand(0))
14218       return false;
14219 
14220     if (!Input)
14221       Input = Extract.getOperand(0);
14222 
14223     Elems = Elems << 8;
14224     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14225     Elems |= Index;
14226 
14227     return true;
14228   };
14229 
14230   // If the build vector operands aren't sign extended vector extracts,
14231   // of the same input vector, then return.
14232   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14233     if (!isSExtOfVecExtract(N->getOperand(i))) {
14234       return SDValue();
14235     }
14236   }
14237 
14238   // If the vector extract indicies are not correct, add the appropriate
14239   // vector_shuffle.
14240   int TgtElemArrayIdx;
14241   int InputSize = Input.getValueType().getScalarSizeInBits();
14242   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14243   if (InputSize + OutputSize == 40)
14244     TgtElemArrayIdx = 0;
14245   else if (InputSize + OutputSize == 72)
14246     TgtElemArrayIdx = 1;
14247   else if (InputSize + OutputSize == 48)
14248     TgtElemArrayIdx = 2;
14249   else if (InputSize + OutputSize == 80)
14250     TgtElemArrayIdx = 3;
14251   else if (InputSize + OutputSize == 96)
14252     TgtElemArrayIdx = 4;
14253   else
14254     return SDValue();
14255 
14256   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14257   CorrectElems = DAG.getDataLayout().isLittleEndian()
14258                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14259                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14260   if (Elems != CorrectElems) {
14261     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14262   }
14263 
14264   // Regular lowering will catch cases where a shuffle is not needed.
14265   return SDValue();
14266 }
14267 
14268 // Look for the pattern of a load from a narrow width to i128, feeding
14269 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14270 // (LXVRZX). This node represents a zero extending load that will be matched
14271 // to the Load VSX Vector Rightmost instructions.
14272 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14273   SDLoc DL(N);
14274 
14275   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14276   if (N->getValueType(0) != MVT::v1i128)
14277     return SDValue();
14278 
14279   SDValue Operand = N->getOperand(0);
14280   // Proceed with the transformation if the operand to the BUILD_VECTOR
14281   // is a load instruction.
14282   if (Operand.getOpcode() != ISD::LOAD)
14283     return SDValue();
14284 
14285   auto *LD = cast<LoadSDNode>(Operand);
14286   EVT MemoryType = LD->getMemoryVT();
14287 
14288   // This transformation is only valid if the we are loading either a byte,
14289   // halfword, word, or doubleword.
14290   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14291                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14292 
14293   // Ensure that the load from the narrow width is being zero extended to i128.
14294   if (!ValidLDType ||
14295       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14296        LD->getExtensionType() != ISD::EXTLOAD))
14297     return SDValue();
14298 
14299   SDValue LoadOps[] = {
14300       LD->getChain(), LD->getBasePtr(),
14301       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14302 
14303   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14304                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14305                                  LoadOps, MemoryType, LD->getMemOperand());
14306 }
14307 
14308 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14309                                                  DAGCombinerInfo &DCI) const {
14310   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14311          "Should be called with a BUILD_VECTOR node");
14312 
14313   SelectionDAG &DAG = DCI.DAG;
14314   SDLoc dl(N);
14315 
14316   if (!Subtarget.hasVSX())
14317     return SDValue();
14318 
14319   // The target independent DAG combiner will leave a build_vector of
14320   // float-to-int conversions intact. We can generate MUCH better code for
14321   // a float-to-int conversion of a vector of floats.
14322   SDValue FirstInput = N->getOperand(0);
14323   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14324     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14325     if (Reduced)
14326       return Reduced;
14327   }
14328 
14329   // If we're building a vector out of consecutive loads, just load that
14330   // vector type.
14331   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14332   if (Reduced)
14333     return Reduced;
14334 
14335   // If we're building a vector out of extended elements from another vector
14336   // we have P9 vector integer extend instructions. The code assumes legal
14337   // input types (i.e. it can't handle things like v4i16) so do not run before
14338   // legalization.
14339   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14340     Reduced = combineBVOfVecSExt(N, DAG);
14341     if (Reduced)
14342       return Reduced;
14343   }
14344 
14345   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14346   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14347   // is a load from <valid narrow width> to i128.
14348   if (Subtarget.isISA3_1()) {
14349     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14350     if (BVOfZLoad)
14351       return BVOfZLoad;
14352   }
14353 
14354   if (N->getValueType(0) != MVT::v2f64)
14355     return SDValue();
14356 
14357   // Looking for:
14358   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14359   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14360       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14361     return SDValue();
14362   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14363       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14364     return SDValue();
14365   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14366     return SDValue();
14367 
14368   SDValue Ext1 = FirstInput.getOperand(0);
14369   SDValue Ext2 = N->getOperand(1).getOperand(0);
14370   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14371      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14372     return SDValue();
14373 
14374   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14375   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14376   if (!Ext1Op || !Ext2Op)
14377     return SDValue();
14378   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14379       Ext1.getOperand(0) != Ext2.getOperand(0))
14380     return SDValue();
14381 
14382   int FirstElem = Ext1Op->getZExtValue();
14383   int SecondElem = Ext2Op->getZExtValue();
14384   int SubvecIdx;
14385   if (FirstElem == 0 && SecondElem == 1)
14386     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14387   else if (FirstElem == 2 && SecondElem == 3)
14388     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14389   else
14390     return SDValue();
14391 
14392   SDValue SrcVec = Ext1.getOperand(0);
14393   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14394     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14395   return DAG.getNode(NodeType, dl, MVT::v2f64,
14396                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14397 }
14398 
14399 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14400                                               DAGCombinerInfo &DCI) const {
14401   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14402           N->getOpcode() == ISD::UINT_TO_FP) &&
14403          "Need an int -> FP conversion node here");
14404 
14405   if (useSoftFloat() || !Subtarget.has64BitSupport())
14406     return SDValue();
14407 
14408   SelectionDAG &DAG = DCI.DAG;
14409   SDLoc dl(N);
14410   SDValue Op(N, 0);
14411 
14412   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14413   // from the hardware.
14414   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14415     return SDValue();
14416   if (!Op.getOperand(0).getValueType().isSimple())
14417     return SDValue();
14418   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14419       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14420     return SDValue();
14421 
14422   SDValue FirstOperand(Op.getOperand(0));
14423   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14424     (FirstOperand.getValueType() == MVT::i8 ||
14425      FirstOperand.getValueType() == MVT::i16);
14426   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14427     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14428     bool DstDouble = Op.getValueType() == MVT::f64;
14429     unsigned ConvOp = Signed ?
14430       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14431       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14432     SDValue WidthConst =
14433       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14434                             dl, false);
14435     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14436     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14437     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14438                                          DAG.getVTList(MVT::f64, MVT::Other),
14439                                          Ops, MVT::i8, LDN->getMemOperand());
14440 
14441     // For signed conversion, we need to sign-extend the value in the VSR
14442     if (Signed) {
14443       SDValue ExtOps[] = { Ld, WidthConst };
14444       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14445       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14446     } else
14447       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14448   }
14449 
14450 
14451   // For i32 intermediate values, unfortunately, the conversion functions
14452   // leave the upper 32 bits of the value are undefined. Within the set of
14453   // scalar instructions, we have no method for zero- or sign-extending the
14454   // value. Thus, we cannot handle i32 intermediate values here.
14455   if (Op.getOperand(0).getValueType() == MVT::i32)
14456     return SDValue();
14457 
14458   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14459          "UINT_TO_FP is supported only with FPCVT");
14460 
14461   // If we have FCFIDS, then use it when converting to single-precision.
14462   // Otherwise, convert to double-precision and then round.
14463   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14464                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14465                                                             : PPCISD::FCFIDS)
14466                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14467                                                             : PPCISD::FCFID);
14468   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14469                   ? MVT::f32
14470                   : MVT::f64;
14471 
14472   // If we're converting from a float, to an int, and back to a float again,
14473   // then we don't need the store/load pair at all.
14474   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14475        Subtarget.hasFPCVT()) ||
14476       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14477     SDValue Src = Op.getOperand(0).getOperand(0);
14478     if (Src.getValueType() == MVT::f32) {
14479       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14480       DCI.AddToWorklist(Src.getNode());
14481     } else if (Src.getValueType() != MVT::f64) {
14482       // Make sure that we don't pick up a ppc_fp128 source value.
14483       return SDValue();
14484     }
14485 
14486     unsigned FCTOp =
14487       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14488                                                         PPCISD::FCTIDUZ;
14489 
14490     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14491     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14492 
14493     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14494       FP = DAG.getNode(ISD::FP_ROUND, dl,
14495                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14496       DCI.AddToWorklist(FP.getNode());
14497     }
14498 
14499     return FP;
14500   }
14501 
14502   return SDValue();
14503 }
14504 
14505 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14506 // builtins) into loads with swaps.
14507 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14508                                               DAGCombinerInfo &DCI) const {
14509   SelectionDAG &DAG = DCI.DAG;
14510   SDLoc dl(N);
14511   SDValue Chain;
14512   SDValue Base;
14513   MachineMemOperand *MMO;
14514 
14515   switch (N->getOpcode()) {
14516   default:
14517     llvm_unreachable("Unexpected opcode for little endian VSX load");
14518   case ISD::LOAD: {
14519     LoadSDNode *LD = cast<LoadSDNode>(N);
14520     Chain = LD->getChain();
14521     Base = LD->getBasePtr();
14522     MMO = LD->getMemOperand();
14523     // If the MMO suggests this isn't a load of a full vector, leave
14524     // things alone.  For a built-in, we have to make the change for
14525     // correctness, so if there is a size problem that will be a bug.
14526     if (MMO->getSize() < 16)
14527       return SDValue();
14528     break;
14529   }
14530   case ISD::INTRINSIC_W_CHAIN: {
14531     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14532     Chain = Intrin->getChain();
14533     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14534     // us what we want. Get operand 2 instead.
14535     Base = Intrin->getOperand(2);
14536     MMO = Intrin->getMemOperand();
14537     break;
14538   }
14539   }
14540 
14541   MVT VecTy = N->getValueType(0).getSimpleVT();
14542 
14543   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14544   // aligned and the type is a vector with elements up to 4 bytes
14545   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14546       VecTy.getScalarSizeInBits() <= 32) {
14547     return SDValue();
14548   }
14549 
14550   SDValue LoadOps[] = { Chain, Base };
14551   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14552                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14553                                          LoadOps, MVT::v2f64, MMO);
14554 
14555   DCI.AddToWorklist(Load.getNode());
14556   Chain = Load.getValue(1);
14557   SDValue Swap = DAG.getNode(
14558       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14559   DCI.AddToWorklist(Swap.getNode());
14560 
14561   // Add a bitcast if the resulting load type doesn't match v2f64.
14562   if (VecTy != MVT::v2f64) {
14563     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14564     DCI.AddToWorklist(N.getNode());
14565     // Package {bitcast value, swap's chain} to match Load's shape.
14566     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14567                        N, Swap.getValue(1));
14568   }
14569 
14570   return Swap;
14571 }
14572 
14573 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14574 // builtins) into stores with swaps.
14575 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14576                                                DAGCombinerInfo &DCI) const {
14577   SelectionDAG &DAG = DCI.DAG;
14578   SDLoc dl(N);
14579   SDValue Chain;
14580   SDValue Base;
14581   unsigned SrcOpnd;
14582   MachineMemOperand *MMO;
14583 
14584   switch (N->getOpcode()) {
14585   default:
14586     llvm_unreachable("Unexpected opcode for little endian VSX store");
14587   case ISD::STORE: {
14588     StoreSDNode *ST = cast<StoreSDNode>(N);
14589     Chain = ST->getChain();
14590     Base = ST->getBasePtr();
14591     MMO = ST->getMemOperand();
14592     SrcOpnd = 1;
14593     // If the MMO suggests this isn't a store of a full vector, leave
14594     // things alone.  For a built-in, we have to make the change for
14595     // correctness, so if there is a size problem that will be a bug.
14596     if (MMO->getSize() < 16)
14597       return SDValue();
14598     break;
14599   }
14600   case ISD::INTRINSIC_VOID: {
14601     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14602     Chain = Intrin->getChain();
14603     // Intrin->getBasePtr() oddly does not get what we want.
14604     Base = Intrin->getOperand(3);
14605     MMO = Intrin->getMemOperand();
14606     SrcOpnd = 2;
14607     break;
14608   }
14609   }
14610 
14611   SDValue Src = N->getOperand(SrcOpnd);
14612   MVT VecTy = Src.getValueType().getSimpleVT();
14613 
14614   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14615   // aligned and the type is a vector with elements up to 4 bytes
14616   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14617       VecTy.getScalarSizeInBits() <= 32) {
14618     return SDValue();
14619   }
14620 
14621   // All stores are done as v2f64 and possible bit cast.
14622   if (VecTy != MVT::v2f64) {
14623     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14624     DCI.AddToWorklist(Src.getNode());
14625   }
14626 
14627   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14628                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14629   DCI.AddToWorklist(Swap.getNode());
14630   Chain = Swap.getValue(1);
14631   SDValue StoreOps[] = { Chain, Swap, Base };
14632   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14633                                           DAG.getVTList(MVT::Other),
14634                                           StoreOps, VecTy, MMO);
14635   DCI.AddToWorklist(Store.getNode());
14636   return Store;
14637 }
14638 
14639 // Handle DAG combine for STORE (FP_TO_INT F).
14640 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14641                                                DAGCombinerInfo &DCI) const {
14642 
14643   SelectionDAG &DAG = DCI.DAG;
14644   SDLoc dl(N);
14645   unsigned Opcode = N->getOperand(1).getOpcode();
14646 
14647   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14648          && "Not a FP_TO_INT Instruction!");
14649 
14650   SDValue Val = N->getOperand(1).getOperand(0);
14651   EVT Op1VT = N->getOperand(1).getValueType();
14652   EVT ResVT = Val.getValueType();
14653 
14654   if (!isTypeLegal(ResVT))
14655     return SDValue();
14656 
14657   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14658   bool ValidTypeForStoreFltAsInt =
14659         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14660          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14661 
14662   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14663     return SDValue();
14664 
14665   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14666       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14667     return SDValue();
14668 
14669   // Extend f32 values to f64
14670   if (ResVT.getScalarSizeInBits() == 32) {
14671     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14672     DCI.AddToWorklist(Val.getNode());
14673   }
14674 
14675   // Set signed or unsigned conversion opcode.
14676   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14677                           PPCISD::FP_TO_SINT_IN_VSR :
14678                           PPCISD::FP_TO_UINT_IN_VSR;
14679 
14680   Val = DAG.getNode(ConvOpcode,
14681                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14682   DCI.AddToWorklist(Val.getNode());
14683 
14684   // Set number of bytes being converted.
14685   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14686   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14687                     DAG.getIntPtrConstant(ByteSize, dl, false),
14688                     DAG.getValueType(Op1VT) };
14689 
14690   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14691           DAG.getVTList(MVT::Other), Ops,
14692           cast<StoreSDNode>(N)->getMemoryVT(),
14693           cast<StoreSDNode>(N)->getMemOperand());
14694 
14695   DCI.AddToWorklist(Val.getNode());
14696   return Val;
14697 }
14698 
14699 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14700   // Check that the source of the element keeps flipping
14701   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14702   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14703   for (int i = 1, e = Mask.size(); i < e; i++) {
14704     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14705       return false;
14706     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14707       return false;
14708     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14709   }
14710   return true;
14711 }
14712 
14713 static bool isSplatBV(SDValue Op) {
14714   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14715     return false;
14716   SDValue FirstOp;
14717 
14718   // Find first non-undef input.
14719   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14720     FirstOp = Op.getOperand(i);
14721     if (!FirstOp.isUndef())
14722       break;
14723   }
14724 
14725   // All inputs are undef or the same as the first non-undef input.
14726   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14727     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14728       return false;
14729   return true;
14730 }
14731 
14732 static SDValue isScalarToVec(SDValue Op) {
14733   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14734     return Op;
14735   if (Op.getOpcode() != ISD::BITCAST)
14736     return SDValue();
14737   Op = Op.getOperand(0);
14738   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14739     return Op;
14740   return SDValue();
14741 }
14742 
14743 // Fix up the shuffle mask to account for the fact that the result of
14744 // scalar_to_vector is not in lane zero. This just takes all values in
14745 // the ranges specified by the min/max indices and adds the number of
14746 // elements required to ensure each element comes from the respective
14747 // position in the valid lane.
14748 // On little endian, that's just the corresponding element in the other
14749 // half of the vector. On big endian, it is in the same half but right
14750 // justified rather than left justified in that half.
14751 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14752                                             int LHSMaxIdx, int RHSMinIdx,
14753                                             int RHSMaxIdx, int HalfVec,
14754                                             unsigned ValidLaneWidth,
14755                                             const PPCSubtarget &Subtarget) {
14756   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14757     int Idx = ShuffV[i];
14758     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14759       ShuffV[i] +=
14760           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14761   }
14762 }
14763 
14764 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14765 // the original is:
14766 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14767 // In such a case, just change the shuffle mask to extract the element
14768 // from the permuted index.
14769 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14770                                const PPCSubtarget &Subtarget) {
14771   SDLoc dl(OrigSToV);
14772   EVT VT = OrigSToV.getValueType();
14773   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14774          "Expecting a SCALAR_TO_VECTOR here");
14775   SDValue Input = OrigSToV.getOperand(0);
14776 
14777   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14778     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14779     SDValue OrigVector = Input.getOperand(0);
14780 
14781     // Can't handle non-const element indices or different vector types
14782     // for the input to the extract and the output of the scalar_to_vector.
14783     if (Idx && VT == OrigVector.getValueType()) {
14784       unsigned NumElts = VT.getVectorNumElements();
14785       assert(
14786           NumElts > 1 &&
14787           "Cannot produce a permuted scalar_to_vector for one element vector");
14788       SmallVector<int, 16> NewMask(NumElts, -1);
14789       unsigned ResultInElt = NumElts / 2;
14790       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14791       NewMask[ResultInElt] = Idx->getZExtValue();
14792       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14793     }
14794   }
14795   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14796                      OrigSToV.getOperand(0));
14797 }
14798 
14799 // On little endian subtargets, combine shuffles such as:
14800 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14801 // into:
14802 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14803 // because the latter can be matched to a single instruction merge.
14804 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14805 // to put the value into element zero. Adjust the shuffle mask so that the
14806 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14807 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14808 // nodes with elements smaller than doubleword because all the ways
14809 // of getting scalar data into a vector register put the value in the
14810 // rightmost element of the left half of the vector.
14811 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14812                                                 SelectionDAG &DAG) const {
14813   SDValue LHS = SVN->getOperand(0);
14814   SDValue RHS = SVN->getOperand(1);
14815   auto Mask = SVN->getMask();
14816   int NumElts = LHS.getValueType().getVectorNumElements();
14817   SDValue Res(SVN, 0);
14818   SDLoc dl(SVN);
14819   bool IsLittleEndian = Subtarget.isLittleEndian();
14820 
14821   // On big endian targets this is only useful for subtargets with direct moves.
14822   // On little endian targets it would be useful for all subtargets with VSX.
14823   // However adding special handling for LE subtargets without direct moves
14824   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14825   // which includes direct moves.
14826   if (!Subtarget.hasDirectMove())
14827     return Res;
14828 
14829   // If this is not a shuffle of a shuffle and the first element comes from
14830   // the second vector, canonicalize to the commuted form. This will make it
14831   // more likely to match one of the single instruction patterns.
14832   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14833       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14834     std::swap(LHS, RHS);
14835     Res = DAG.getCommutedVectorShuffle(*SVN);
14836     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14837   }
14838 
14839   // Adjust the shuffle mask if either input vector comes from a
14840   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14841   // form (to prevent the need for a swap).
14842   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14843   SDValue SToVLHS = isScalarToVec(LHS);
14844   SDValue SToVRHS = isScalarToVec(RHS);
14845   if (SToVLHS || SToVRHS) {
14846     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14847                             : SToVRHS.getValueType().getVectorNumElements();
14848     int NumEltsOut = ShuffV.size();
14849     // The width of the "valid lane" (i.e. the lane that contains the value that
14850     // is vectorized) needs to be expressed in terms of the number of elements
14851     // of the shuffle. It is thereby the ratio of the values before and after
14852     // any bitcast.
14853     unsigned ValidLaneWidth =
14854         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14855                       LHS.getValueType().getScalarSizeInBits()
14856                 : SToVRHS.getValueType().getScalarSizeInBits() /
14857                       RHS.getValueType().getScalarSizeInBits();
14858 
14859     // Initially assume that neither input is permuted. These will be adjusted
14860     // accordingly if either input is.
14861     int LHSMaxIdx = -1;
14862     int RHSMinIdx = -1;
14863     int RHSMaxIdx = -1;
14864     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14865 
14866     // Get the permuted scalar to vector nodes for the source(s) that come from
14867     // ISD::SCALAR_TO_VECTOR.
14868     // On big endian systems, this only makes sense for element sizes smaller
14869     // than 64 bits since for 64-bit elements, all instructions already put
14870     // the value into element zero. Since scalar size of LHS and RHS may differ
14871     // after isScalarToVec, this should be checked using their own sizes.
14872     if (SToVLHS) {
14873       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14874         return Res;
14875       // Set up the values for the shuffle vector fixup.
14876       LHSMaxIdx = NumEltsOut / NumEltsIn;
14877       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14878       if (SToVLHS.getValueType() != LHS.getValueType())
14879         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14880       LHS = SToVLHS;
14881     }
14882     if (SToVRHS) {
14883       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14884         return Res;
14885       RHSMinIdx = NumEltsOut;
14886       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14887       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14888       if (SToVRHS.getValueType() != RHS.getValueType())
14889         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14890       RHS = SToVRHS;
14891     }
14892 
14893     // Fix up the shuffle mask to reflect where the desired element actually is.
14894     // The minimum and maximum indices that correspond to element zero for both
14895     // the LHS and RHS are computed and will control which shuffle mask entries
14896     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14897     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14898     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14899                                     HalfVec, ValidLaneWidth, Subtarget);
14900     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14901 
14902     // We may have simplified away the shuffle. We won't be able to do anything
14903     // further with it here.
14904     if (!isa<ShuffleVectorSDNode>(Res))
14905       return Res;
14906     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14907   }
14908 
14909   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14910   // The common case after we commuted the shuffle is that the RHS is a splat
14911   // and we have elements coming in from the splat at indices that are not
14912   // conducive to using a merge.
14913   // Example:
14914   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14915   if (!isSplatBV(TheSplat))
14916     return Res;
14917 
14918   // We are looking for a mask such that all even elements are from
14919   // one vector and all odd elements from the other.
14920   if (!isAlternatingShuffMask(Mask, NumElts))
14921     return Res;
14922 
14923   // Adjust the mask so we are pulling in the same index from the splat
14924   // as the index from the interesting vector in consecutive elements.
14925   if (IsLittleEndian) {
14926     // Example (even elements from first vector):
14927     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14928     if (Mask[0] < NumElts)
14929       for (int i = 1, e = Mask.size(); i < e; i += 2)
14930         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14931     // Example (odd elements from first vector):
14932     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14933     else
14934       for (int i = 0, e = Mask.size(); i < e; i += 2)
14935         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14936   } else {
14937     // Example (even elements from first vector):
14938     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14939     if (Mask[0] < NumElts)
14940       for (int i = 0, e = Mask.size(); i < e; i += 2)
14941         ShuffV[i] = ShuffV[i + 1] - NumElts;
14942     // Example (odd elements from first vector):
14943     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14944     else
14945       for (int i = 1, e = Mask.size(); i < e; i += 2)
14946         ShuffV[i] = ShuffV[i - 1] - NumElts;
14947   }
14948 
14949   // If the RHS has undefs, we need to remove them since we may have created
14950   // a shuffle that adds those instead of the splat value.
14951   SDValue SplatVal =
14952       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14953   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14954 
14955   if (IsLittleEndian)
14956     RHS = TheSplat;
14957   else
14958     LHS = TheSplat;
14959   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14960 }
14961 
14962 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14963                                                 LSBaseSDNode *LSBase,
14964                                                 DAGCombinerInfo &DCI) const {
14965   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14966         "Not a reverse memop pattern!");
14967 
14968   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14969     auto Mask = SVN->getMask();
14970     int i = 0;
14971     auto I = Mask.rbegin();
14972     auto E = Mask.rend();
14973 
14974     for (; I != E; ++I) {
14975       if (*I != i)
14976         return false;
14977       i++;
14978     }
14979     return true;
14980   };
14981 
14982   SelectionDAG &DAG = DCI.DAG;
14983   EVT VT = SVN->getValueType(0);
14984 
14985   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14986     return SDValue();
14987 
14988   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14989   // See comment in PPCVSXSwapRemoval.cpp.
14990   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14991   if (!Subtarget.hasP9Vector())
14992     return SDValue();
14993 
14994   if(!IsElementReverse(SVN))
14995     return SDValue();
14996 
14997   if (LSBase->getOpcode() == ISD::LOAD) {
14998     // If the load return value 0 has more than one user except the
14999     // shufflevector instruction, it is not profitable to replace the
15000     // shufflevector with a reverse load.
15001     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
15002          UI != UE; ++UI)
15003       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
15004         return SDValue();
15005 
15006     SDLoc dl(LSBase);
15007     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
15008     return DAG.getMemIntrinsicNode(
15009         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
15010         LSBase->getMemoryVT(), LSBase->getMemOperand());
15011   }
15012 
15013   if (LSBase->getOpcode() == ISD::STORE) {
15014     // If there are other uses of the shuffle, the swap cannot be avoided.
15015     // Forcing the use of an X-Form (since swapped stores only have
15016     // X-Forms) without removing the swap is unprofitable.
15017     if (!SVN->hasOneUse())
15018       return SDValue();
15019 
15020     SDLoc dl(LSBase);
15021     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
15022                           LSBase->getBasePtr()};
15023     return DAG.getMemIntrinsicNode(
15024         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
15025         LSBase->getMemoryVT(), LSBase->getMemOperand());
15026   }
15027 
15028   llvm_unreachable("Expected a load or store node here");
15029 }
15030 
15031 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
15032                                              DAGCombinerInfo &DCI) const {
15033   SelectionDAG &DAG = DCI.DAG;
15034   SDLoc dl(N);
15035   switch (N->getOpcode()) {
15036   default: break;
15037   case ISD::ADD:
15038     return combineADD(N, DCI);
15039   case ISD::SHL:
15040     return combineSHL(N, DCI);
15041   case ISD::SRA:
15042     return combineSRA(N, DCI);
15043   case ISD::SRL:
15044     return combineSRL(N, DCI);
15045   case ISD::MUL:
15046     return combineMUL(N, DCI);
15047   case ISD::FMA:
15048   case PPCISD::FNMSUB:
15049     return combineFMALike(N, DCI);
15050   case PPCISD::SHL:
15051     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
15052         return N->getOperand(0);
15053     break;
15054   case PPCISD::SRL:
15055     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15056         return N->getOperand(0);
15057     break;
15058   case PPCISD::SRA:
15059     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15060       if (C->isZero() ||  //  0 >>s V -> 0.
15061           C->isAllOnes()) // -1 >>s V -> -1.
15062         return N->getOperand(0);
15063     }
15064     break;
15065   case ISD::SIGN_EXTEND:
15066   case ISD::ZERO_EXTEND:
15067   case ISD::ANY_EXTEND:
15068     return DAGCombineExtBoolTrunc(N, DCI);
15069   case ISD::TRUNCATE:
15070     return combineTRUNCATE(N, DCI);
15071   case ISD::SETCC:
15072     if (SDValue CSCC = combineSetCC(N, DCI))
15073       return CSCC;
15074     LLVM_FALLTHROUGH;
15075   case ISD::SELECT_CC:
15076     return DAGCombineTruncBoolExt(N, DCI);
15077   case ISD::SINT_TO_FP:
15078   case ISD::UINT_TO_FP:
15079     return combineFPToIntToFP(N, DCI);
15080   case ISD::VECTOR_SHUFFLE:
15081     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15082       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15083       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15084     }
15085     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15086   case ISD::STORE: {
15087 
15088     EVT Op1VT = N->getOperand(1).getValueType();
15089     unsigned Opcode = N->getOperand(1).getOpcode();
15090 
15091     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15092       SDValue Val= combineStoreFPToInt(N, DCI);
15093       if (Val)
15094         return Val;
15095     }
15096 
15097     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15098       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15099       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15100       if (Val)
15101         return Val;
15102     }
15103 
15104     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15105     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15106         N->getOperand(1).getNode()->hasOneUse() &&
15107         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15108          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15109 
15110       // STBRX can only handle simple types and it makes no sense to store less
15111       // two bytes in byte-reversed order.
15112       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15113       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15114         break;
15115 
15116       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15117       // Do an any-extend to 32-bits if this is a half-word input.
15118       if (BSwapOp.getValueType() == MVT::i16)
15119         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15120 
15121       // If the type of BSWAP operand is wider than stored memory width
15122       // it need to be shifted to the right side before STBRX.
15123       if (Op1VT.bitsGT(mVT)) {
15124         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15125         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15126                               DAG.getConstant(Shift, dl, MVT::i32));
15127         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15128         if (Op1VT == MVT::i64)
15129           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15130       }
15131 
15132       SDValue Ops[] = {
15133         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15134       };
15135       return
15136         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15137                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15138                                 cast<StoreSDNode>(N)->getMemOperand());
15139     }
15140 
15141     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15142     // So it can increase the chance of CSE constant construction.
15143     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15144         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15145       // Need to sign-extended to 64-bits to handle negative values.
15146       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15147       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15148                                     MemVT.getSizeInBits());
15149       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15150 
15151       // DAG.getTruncStore() can't be used here because it doesn't accept
15152       // the general (base + offset) addressing mode.
15153       // So we use UpdateNodeOperands and setTruncatingStore instead.
15154       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15155                              N->getOperand(3));
15156       cast<StoreSDNode>(N)->setTruncatingStore(true);
15157       return SDValue(N, 0);
15158     }
15159 
15160     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15161     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15162     if (Op1VT.isSimple()) {
15163       MVT StoreVT = Op1VT.getSimpleVT();
15164       if (Subtarget.needsSwapsForVSXMemOps() &&
15165           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15166            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15167         return expandVSXStoreForLE(N, DCI);
15168     }
15169     break;
15170   }
15171   case ISD::LOAD: {
15172     LoadSDNode *LD = cast<LoadSDNode>(N);
15173     EVT VT = LD->getValueType(0);
15174 
15175     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15176     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15177     if (VT.isSimple()) {
15178       MVT LoadVT = VT.getSimpleVT();
15179       if (Subtarget.needsSwapsForVSXMemOps() &&
15180           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15181            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15182         return expandVSXLoadForLE(N, DCI);
15183     }
15184 
15185     // We sometimes end up with a 64-bit integer load, from which we extract
15186     // two single-precision floating-point numbers. This happens with
15187     // std::complex<float>, and other similar structures, because of the way we
15188     // canonicalize structure copies. However, if we lack direct moves,
15189     // then the final bitcasts from the extracted integer values to the
15190     // floating-point numbers turn into store/load pairs. Even with direct moves,
15191     // just loading the two floating-point numbers is likely better.
15192     auto ReplaceTwoFloatLoad = [&]() {
15193       if (VT != MVT::i64)
15194         return false;
15195 
15196       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15197           LD->isVolatile())
15198         return false;
15199 
15200       //  We're looking for a sequence like this:
15201       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15202       //      t16: i64 = srl t13, Constant:i32<32>
15203       //    t17: i32 = truncate t16
15204       //  t18: f32 = bitcast t17
15205       //    t19: i32 = truncate t13
15206       //  t20: f32 = bitcast t19
15207 
15208       if (!LD->hasNUsesOfValue(2, 0))
15209         return false;
15210 
15211       auto UI = LD->use_begin();
15212       while (UI.getUse().getResNo() != 0) ++UI;
15213       SDNode *Trunc = *UI++;
15214       while (UI.getUse().getResNo() != 0) ++UI;
15215       SDNode *RightShift = *UI;
15216       if (Trunc->getOpcode() != ISD::TRUNCATE)
15217         std::swap(Trunc, RightShift);
15218 
15219       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15220           Trunc->getValueType(0) != MVT::i32 ||
15221           !Trunc->hasOneUse())
15222         return false;
15223       if (RightShift->getOpcode() != ISD::SRL ||
15224           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15225           RightShift->getConstantOperandVal(1) != 32 ||
15226           !RightShift->hasOneUse())
15227         return false;
15228 
15229       SDNode *Trunc2 = *RightShift->use_begin();
15230       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15231           Trunc2->getValueType(0) != MVT::i32 ||
15232           !Trunc2->hasOneUse())
15233         return false;
15234 
15235       SDNode *Bitcast = *Trunc->use_begin();
15236       SDNode *Bitcast2 = *Trunc2->use_begin();
15237 
15238       if (Bitcast->getOpcode() != ISD::BITCAST ||
15239           Bitcast->getValueType(0) != MVT::f32)
15240         return false;
15241       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15242           Bitcast2->getValueType(0) != MVT::f32)
15243         return false;
15244 
15245       if (Subtarget.isLittleEndian())
15246         std::swap(Bitcast, Bitcast2);
15247 
15248       // Bitcast has the second float (in memory-layout order) and Bitcast2
15249       // has the first one.
15250 
15251       SDValue BasePtr = LD->getBasePtr();
15252       if (LD->isIndexed()) {
15253         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15254                "Non-pre-inc AM on PPC?");
15255         BasePtr =
15256           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15257                       LD->getOffset());
15258       }
15259 
15260       auto MMOFlags =
15261           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15262       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15263                                       LD->getPointerInfo(), LD->getAlignment(),
15264                                       MMOFlags, LD->getAAInfo());
15265       SDValue AddPtr =
15266         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15267                     BasePtr, DAG.getIntPtrConstant(4, dl));
15268       SDValue FloatLoad2 = DAG.getLoad(
15269           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15270           LD->getPointerInfo().getWithOffset(4),
15271           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15272 
15273       if (LD->isIndexed()) {
15274         // Note that DAGCombine should re-form any pre-increment load(s) from
15275         // what is produced here if that makes sense.
15276         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15277       }
15278 
15279       DCI.CombineTo(Bitcast2, FloatLoad);
15280       DCI.CombineTo(Bitcast, FloatLoad2);
15281 
15282       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15283                                     SDValue(FloatLoad2.getNode(), 1));
15284       return true;
15285     };
15286 
15287     if (ReplaceTwoFloatLoad())
15288       return SDValue(N, 0);
15289 
15290     EVT MemVT = LD->getMemoryVT();
15291     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15292     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15293     if (LD->isUnindexed() && VT.isVector() &&
15294         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15295           // P8 and later hardware should just use LOAD.
15296           !Subtarget.hasP8Vector() &&
15297           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15298            VT == MVT::v4f32))) &&
15299         LD->getAlign() < ABIAlignment) {
15300       // This is a type-legal unaligned Altivec load.
15301       SDValue Chain = LD->getChain();
15302       SDValue Ptr = LD->getBasePtr();
15303       bool isLittleEndian = Subtarget.isLittleEndian();
15304 
15305       // This implements the loading of unaligned vectors as described in
15306       // the venerable Apple Velocity Engine overview. Specifically:
15307       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15308       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15309       //
15310       // The general idea is to expand a sequence of one or more unaligned
15311       // loads into an alignment-based permutation-control instruction (lvsl
15312       // or lvsr), a series of regular vector loads (which always truncate
15313       // their input address to an aligned address), and a series of
15314       // permutations.  The results of these permutations are the requested
15315       // loaded values.  The trick is that the last "extra" load is not taken
15316       // from the address you might suspect (sizeof(vector) bytes after the
15317       // last requested load), but rather sizeof(vector) - 1 bytes after the
15318       // last requested vector. The point of this is to avoid a page fault if
15319       // the base address happened to be aligned. This works because if the
15320       // base address is aligned, then adding less than a full vector length
15321       // will cause the last vector in the sequence to be (re)loaded.
15322       // Otherwise, the next vector will be fetched as you might suspect was
15323       // necessary.
15324 
15325       // We might be able to reuse the permutation generation from
15326       // a different base address offset from this one by an aligned amount.
15327       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15328       // optimization later.
15329       Intrinsic::ID Intr, IntrLD, IntrPerm;
15330       MVT PermCntlTy, PermTy, LDTy;
15331       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15332                             : Intrinsic::ppc_altivec_lvsl;
15333       IntrLD = Intrinsic::ppc_altivec_lvx;
15334       IntrPerm = Intrinsic::ppc_altivec_vperm;
15335       PermCntlTy = MVT::v16i8;
15336       PermTy = MVT::v4i32;
15337       LDTy = MVT::v4i32;
15338 
15339       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15340 
15341       // Create the new MMO for the new base load. It is like the original MMO,
15342       // but represents an area in memory almost twice the vector size centered
15343       // on the original address. If the address is unaligned, we might start
15344       // reading up to (sizeof(vector)-1) bytes below the address of the
15345       // original unaligned load.
15346       MachineFunction &MF = DAG.getMachineFunction();
15347       MachineMemOperand *BaseMMO =
15348         MF.getMachineMemOperand(LD->getMemOperand(),
15349                                 -(long)MemVT.getStoreSize()+1,
15350                                 2*MemVT.getStoreSize()-1);
15351 
15352       // Create the new base load.
15353       SDValue LDXIntID =
15354           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15355       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15356       SDValue BaseLoad =
15357         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15358                                 DAG.getVTList(PermTy, MVT::Other),
15359                                 BaseLoadOps, LDTy, BaseMMO);
15360 
15361       // Note that the value of IncOffset (which is provided to the next
15362       // load's pointer info offset value, and thus used to calculate the
15363       // alignment), and the value of IncValue (which is actually used to
15364       // increment the pointer value) are different! This is because we
15365       // require the next load to appear to be aligned, even though it
15366       // is actually offset from the base pointer by a lesser amount.
15367       int IncOffset = VT.getSizeInBits() / 8;
15368       int IncValue = IncOffset;
15369 
15370       // Walk (both up and down) the chain looking for another load at the real
15371       // (aligned) offset (the alignment of the other load does not matter in
15372       // this case). If found, then do not use the offset reduction trick, as
15373       // that will prevent the loads from being later combined (as they would
15374       // otherwise be duplicates).
15375       if (!findConsecutiveLoad(LD, DAG))
15376         --IncValue;
15377 
15378       SDValue Increment =
15379           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15380       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15381 
15382       MachineMemOperand *ExtraMMO =
15383         MF.getMachineMemOperand(LD->getMemOperand(),
15384                                 1, 2*MemVT.getStoreSize()-1);
15385       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15386       SDValue ExtraLoad =
15387         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15388                                 DAG.getVTList(PermTy, MVT::Other),
15389                                 ExtraLoadOps, LDTy, ExtraMMO);
15390 
15391       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15392         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15393 
15394       // Because vperm has a big-endian bias, we must reverse the order
15395       // of the input vectors and complement the permute control vector
15396       // when generating little endian code.  We have already handled the
15397       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15398       // and ExtraLoad here.
15399       SDValue Perm;
15400       if (isLittleEndian)
15401         Perm = BuildIntrinsicOp(IntrPerm,
15402                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15403       else
15404         Perm = BuildIntrinsicOp(IntrPerm,
15405                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15406 
15407       if (VT != PermTy)
15408         Perm = Subtarget.hasAltivec()
15409                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15410                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15411                                  DAG.getTargetConstant(1, dl, MVT::i64));
15412                                // second argument is 1 because this rounding
15413                                // is always exact.
15414 
15415       // The output of the permutation is our loaded result, the TokenFactor is
15416       // our new chain.
15417       DCI.CombineTo(N, Perm, TF);
15418       return SDValue(N, 0);
15419     }
15420     }
15421     break;
15422     case ISD::INTRINSIC_WO_CHAIN: {
15423       bool isLittleEndian = Subtarget.isLittleEndian();
15424       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15425       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15426                                            : Intrinsic::ppc_altivec_lvsl);
15427       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15428         SDValue Add = N->getOperand(1);
15429 
15430         int Bits = 4 /* 16 byte alignment */;
15431 
15432         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15433                                   APInt::getAllOnes(Bits /* alignment */)
15434                                       .zext(Add.getScalarValueSizeInBits()))) {
15435           SDNode *BasePtr = Add->getOperand(0).getNode();
15436           for (SDNode *U : BasePtr->uses()) {
15437             if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15438                 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15439               // We've found another LVSL/LVSR, and this address is an aligned
15440               // multiple of that one. The results will be the same, so use the
15441               // one we've just found instead.
15442 
15443               return SDValue(U, 0);
15444             }
15445           }
15446         }
15447 
15448         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15449           SDNode *BasePtr = Add->getOperand(0).getNode();
15450           for (SDNode *U : BasePtr->uses()) {
15451             if (U->getOpcode() == ISD::ADD &&
15452                 isa<ConstantSDNode>(U->getOperand(1)) &&
15453                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15454                  cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15455                         (1ULL << Bits) ==
15456                     0) {
15457               SDNode *OtherAdd = U;
15458               for (SDNode *V : OtherAdd->uses()) {
15459                 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15460                     cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15461                         IID) {
15462                   return SDValue(V, 0);
15463                 }
15464               }
15465             }
15466           }
15467         }
15468       }
15469 
15470       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15471       // Expose the vabsduw/h/b opportunity for down stream
15472       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15473           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15474            IID == Intrinsic::ppc_altivec_vmaxsh ||
15475            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15476         SDValue V1 = N->getOperand(1);
15477         SDValue V2 = N->getOperand(2);
15478         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15479              V1.getSimpleValueType() == MVT::v8i16 ||
15480              V1.getSimpleValueType() == MVT::v16i8) &&
15481             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15482           // (0-a, a)
15483           if (V1.getOpcode() == ISD::SUB &&
15484               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15485               V1.getOperand(1) == V2) {
15486             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15487           }
15488           // (a, 0-a)
15489           if (V2.getOpcode() == ISD::SUB &&
15490               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15491               V2.getOperand(1) == V1) {
15492             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15493           }
15494           // (x-y, y-x)
15495           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15496               V1.getOperand(0) == V2.getOperand(1) &&
15497               V1.getOperand(1) == V2.getOperand(0)) {
15498             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15499           }
15500         }
15501       }
15502     }
15503 
15504     break;
15505   case ISD::INTRINSIC_W_CHAIN:
15506     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15507     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15508     if (Subtarget.needsSwapsForVSXMemOps()) {
15509       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15510       default:
15511         break;
15512       case Intrinsic::ppc_vsx_lxvw4x:
15513       case Intrinsic::ppc_vsx_lxvd2x:
15514         return expandVSXLoadForLE(N, DCI);
15515       }
15516     }
15517     break;
15518   case ISD::INTRINSIC_VOID:
15519     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15520     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15521     if (Subtarget.needsSwapsForVSXMemOps()) {
15522       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15523       default:
15524         break;
15525       case Intrinsic::ppc_vsx_stxvw4x:
15526       case Intrinsic::ppc_vsx_stxvd2x:
15527         return expandVSXStoreForLE(N, DCI);
15528       }
15529     }
15530     break;
15531   case ISD::BSWAP: {
15532     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15533     // For subtargets without LDBRX, we can still do better than the default
15534     // expansion even for 64-bit BSWAP (LOAD).
15535     bool Is64BitBswapOn64BitTgt =
15536         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15537     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15538                                N->getOperand(0).hasOneUse();
15539     if (IsSingleUseNormalLd &&
15540         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15541          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15542       SDValue Load = N->getOperand(0);
15543       LoadSDNode *LD = cast<LoadSDNode>(Load);
15544       // Create the byte-swapping load.
15545       SDValue Ops[] = {
15546         LD->getChain(),    // Chain
15547         LD->getBasePtr(),  // Ptr
15548         DAG.getValueType(N->getValueType(0)) // VT
15549       };
15550       SDValue BSLoad =
15551         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15552                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15553                                               MVT::i64 : MVT::i32, MVT::Other),
15554                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15555 
15556       // If this is an i16 load, insert the truncate.
15557       SDValue ResVal = BSLoad;
15558       if (N->getValueType(0) == MVT::i16)
15559         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15560 
15561       // First, combine the bswap away.  This makes the value produced by the
15562       // load dead.
15563       DCI.CombineTo(N, ResVal);
15564 
15565       // Next, combine the load away, we give it a bogus result value but a real
15566       // chain result.  The result value is dead because the bswap is dead.
15567       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15568 
15569       // Return N so it doesn't get rechecked!
15570       return SDValue(N, 0);
15571     }
15572     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15573     // before legalization so that the BUILD_PAIR is handled correctly.
15574     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15575         !IsSingleUseNormalLd)
15576       return SDValue();
15577     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15578 
15579     // Can't split volatile or atomic loads.
15580     if (!LD->isSimple())
15581       return SDValue();
15582     SDValue BasePtr = LD->getBasePtr();
15583     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15584                              LD->getPointerInfo(), LD->getAlignment());
15585     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15586     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15587                           DAG.getIntPtrConstant(4, dl));
15588     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15589         LD->getMemOperand(), 4, 4);
15590     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15591     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15592     SDValue Res;
15593     if (Subtarget.isLittleEndian())
15594       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15595     else
15596       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15597     SDValue TF =
15598         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15599                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15600     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15601     return Res;
15602   }
15603   case PPCISD::VCMP:
15604     // If a VCMP_rec node already exists with exactly the same operands as this
15605     // node, use its result instead of this node (VCMP_rec computes both a CR6
15606     // and a normal output).
15607     //
15608     if (!N->getOperand(0).hasOneUse() &&
15609         !N->getOperand(1).hasOneUse() &&
15610         !N->getOperand(2).hasOneUse()) {
15611 
15612       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15613       SDNode *VCMPrecNode = nullptr;
15614 
15615       SDNode *LHSN = N->getOperand(0).getNode();
15616       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15617            UI != E; ++UI)
15618         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15619             UI->getOperand(1) == N->getOperand(1) &&
15620             UI->getOperand(2) == N->getOperand(2) &&
15621             UI->getOperand(0) == N->getOperand(0)) {
15622           VCMPrecNode = *UI;
15623           break;
15624         }
15625 
15626       // If there is no VCMP_rec node, or if the flag value has a single use,
15627       // don't transform this.
15628       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15629         break;
15630 
15631       // Look at the (necessarily single) use of the flag value.  If it has a
15632       // chain, this transformation is more complex.  Note that multiple things
15633       // could use the value result, which we should ignore.
15634       SDNode *FlagUser = nullptr;
15635       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15636            FlagUser == nullptr; ++UI) {
15637         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15638         SDNode *User = *UI;
15639         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15640           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15641             FlagUser = User;
15642             break;
15643           }
15644         }
15645       }
15646 
15647       // If the user is a MFOCRF instruction, we know this is safe.
15648       // Otherwise we give up for right now.
15649       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15650         return SDValue(VCMPrecNode, 0);
15651     }
15652     break;
15653   case ISD::BRCOND: {
15654     SDValue Cond = N->getOperand(1);
15655     SDValue Target = N->getOperand(2);
15656 
15657     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15658         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15659           Intrinsic::loop_decrement) {
15660 
15661       // We now need to make the intrinsic dead (it cannot be instruction
15662       // selected).
15663       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15664       assert(Cond.getNode()->hasOneUse() &&
15665              "Counter decrement has more than one use");
15666 
15667       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15668                          N->getOperand(0), Target);
15669     }
15670   }
15671   break;
15672   case ISD::BR_CC: {
15673     // If this is a branch on an altivec predicate comparison, lower this so
15674     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15675     // lowering is done pre-legalize, because the legalizer lowers the predicate
15676     // compare down to code that is difficult to reassemble.
15677     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15678     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15679 
15680     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15681     // value. If so, pass-through the AND to get to the intrinsic.
15682     if (LHS.getOpcode() == ISD::AND &&
15683         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15684         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15685           Intrinsic::loop_decrement &&
15686         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15687         !isNullConstant(LHS.getOperand(1)))
15688       LHS = LHS.getOperand(0);
15689 
15690     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15691         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15692           Intrinsic::loop_decrement &&
15693         isa<ConstantSDNode>(RHS)) {
15694       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15695              "Counter decrement comparison is not EQ or NE");
15696 
15697       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15698       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15699                     (CC == ISD::SETNE && !Val);
15700 
15701       // We now need to make the intrinsic dead (it cannot be instruction
15702       // selected).
15703       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15704       assert(LHS.getNode()->hasOneUse() &&
15705              "Counter decrement has more than one use");
15706 
15707       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15708                          N->getOperand(0), N->getOperand(4));
15709     }
15710 
15711     int CompareOpc;
15712     bool isDot;
15713 
15714     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15715         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15716         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15717       assert(isDot && "Can't compare against a vector result!");
15718 
15719       // If this is a comparison against something other than 0/1, then we know
15720       // that the condition is never/always true.
15721       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15722       if (Val != 0 && Val != 1) {
15723         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15724           return N->getOperand(0);
15725         // Always !=, turn it into an unconditional branch.
15726         return DAG.getNode(ISD::BR, dl, MVT::Other,
15727                            N->getOperand(0), N->getOperand(4));
15728       }
15729 
15730       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15731 
15732       // Create the PPCISD altivec 'dot' comparison node.
15733       SDValue Ops[] = {
15734         LHS.getOperand(2),  // LHS of compare
15735         LHS.getOperand(3),  // RHS of compare
15736         DAG.getConstant(CompareOpc, dl, MVT::i32)
15737       };
15738       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15739       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15740 
15741       // Unpack the result based on how the target uses it.
15742       PPC::Predicate CompOpc;
15743       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15744       default:  // Can't happen, don't crash on invalid number though.
15745       case 0:   // Branch on the value of the EQ bit of CR6.
15746         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15747         break;
15748       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15749         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15750         break;
15751       case 2:   // Branch on the value of the LT bit of CR6.
15752         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15753         break;
15754       case 3:   // Branch on the inverted value of the LT bit of CR6.
15755         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15756         break;
15757       }
15758 
15759       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15760                          DAG.getConstant(CompOpc, dl, MVT::i32),
15761                          DAG.getRegister(PPC::CR6, MVT::i32),
15762                          N->getOperand(4), CompNode.getValue(1));
15763     }
15764     break;
15765   }
15766   case ISD::BUILD_VECTOR:
15767     return DAGCombineBuildVector(N, DCI);
15768   case ISD::ABS:
15769     return combineABS(N, DCI);
15770   case ISD::VSELECT:
15771     return combineVSelect(N, DCI);
15772   }
15773 
15774   return SDValue();
15775 }
15776 
15777 SDValue
15778 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15779                                  SelectionDAG &DAG,
15780                                  SmallVectorImpl<SDNode *> &Created) const {
15781   // fold (sdiv X, pow2)
15782   EVT VT = N->getValueType(0);
15783   if (VT == MVT::i64 && !Subtarget.isPPC64())
15784     return SDValue();
15785   if ((VT != MVT::i32 && VT != MVT::i64) ||
15786       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15787     return SDValue();
15788 
15789   SDLoc DL(N);
15790   SDValue N0 = N->getOperand(0);
15791 
15792   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15793   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15794   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15795 
15796   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15797   Created.push_back(Op.getNode());
15798 
15799   if (IsNegPow2) {
15800     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15801     Created.push_back(Op.getNode());
15802   }
15803 
15804   return Op;
15805 }
15806 
15807 //===----------------------------------------------------------------------===//
15808 // Inline Assembly Support
15809 //===----------------------------------------------------------------------===//
15810 
15811 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15812                                                       KnownBits &Known,
15813                                                       const APInt &DemandedElts,
15814                                                       const SelectionDAG &DAG,
15815                                                       unsigned Depth) const {
15816   Known.resetAll();
15817   switch (Op.getOpcode()) {
15818   default: break;
15819   case PPCISD::LBRX: {
15820     // lhbrx is known to have the top bits cleared out.
15821     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15822       Known.Zero = 0xFFFF0000;
15823     break;
15824   }
15825   case ISD::INTRINSIC_WO_CHAIN: {
15826     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15827     default: break;
15828     case Intrinsic::ppc_altivec_vcmpbfp_p:
15829     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15830     case Intrinsic::ppc_altivec_vcmpequb_p:
15831     case Intrinsic::ppc_altivec_vcmpequh_p:
15832     case Intrinsic::ppc_altivec_vcmpequw_p:
15833     case Intrinsic::ppc_altivec_vcmpequd_p:
15834     case Intrinsic::ppc_altivec_vcmpequq_p:
15835     case Intrinsic::ppc_altivec_vcmpgefp_p:
15836     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15837     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15838     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15839     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15840     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15841     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15842     case Intrinsic::ppc_altivec_vcmpgtub_p:
15843     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15844     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15845     case Intrinsic::ppc_altivec_vcmpgtud_p:
15846     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15847       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15848       break;
15849     }
15850     break;
15851   }
15852   case ISD::INTRINSIC_W_CHAIN: {
15853     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15854     default:
15855       break;
15856     case Intrinsic::ppc_load2r:
15857       // Top bits are cleared for load2r (which is the same as lhbrx).
15858       Known.Zero = 0xFFFF0000;
15859       break;
15860     }
15861     break;
15862   }
15863   }
15864 }
15865 
15866 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15867   switch (Subtarget.getCPUDirective()) {
15868   default: break;
15869   case PPC::DIR_970:
15870   case PPC::DIR_PWR4:
15871   case PPC::DIR_PWR5:
15872   case PPC::DIR_PWR5X:
15873   case PPC::DIR_PWR6:
15874   case PPC::DIR_PWR6X:
15875   case PPC::DIR_PWR7:
15876   case PPC::DIR_PWR8:
15877   case PPC::DIR_PWR9:
15878   case PPC::DIR_PWR10:
15879   case PPC::DIR_PWR_FUTURE: {
15880     if (!ML)
15881       break;
15882 
15883     if (!DisableInnermostLoopAlign32) {
15884       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15885       // so that we can decrease cache misses and branch-prediction misses.
15886       // Actual alignment of the loop will depend on the hotness check and other
15887       // logic in alignBlocks.
15888       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15889         return Align(32);
15890     }
15891 
15892     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15893 
15894     // For small loops (between 5 and 8 instructions), align to a 32-byte
15895     // boundary so that the entire loop fits in one instruction-cache line.
15896     uint64_t LoopSize = 0;
15897     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15898       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15899         LoopSize += TII->getInstSizeInBytes(*J);
15900         if (LoopSize > 32)
15901           break;
15902       }
15903 
15904     if (LoopSize > 16 && LoopSize <= 32)
15905       return Align(32);
15906 
15907     break;
15908   }
15909   }
15910 
15911   return TargetLowering::getPrefLoopAlignment(ML);
15912 }
15913 
15914 /// getConstraintType - Given a constraint, return the type of
15915 /// constraint it is for this target.
15916 PPCTargetLowering::ConstraintType
15917 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15918   if (Constraint.size() == 1) {
15919     switch (Constraint[0]) {
15920     default: break;
15921     case 'b':
15922     case 'r':
15923     case 'f':
15924     case 'd':
15925     case 'v':
15926     case 'y':
15927       return C_RegisterClass;
15928     case 'Z':
15929       // FIXME: While Z does indicate a memory constraint, it specifically
15930       // indicates an r+r address (used in conjunction with the 'y' modifier
15931       // in the replacement string). Currently, we're forcing the base
15932       // register to be r0 in the asm printer (which is interpreted as zero)
15933       // and forming the complete address in the second register. This is
15934       // suboptimal.
15935       return C_Memory;
15936     }
15937   } else if (Constraint == "wc") { // individual CR bits.
15938     return C_RegisterClass;
15939   } else if (Constraint == "wa" || Constraint == "wd" ||
15940              Constraint == "wf" || Constraint == "ws" ||
15941              Constraint == "wi" || Constraint == "ww") {
15942     return C_RegisterClass; // VSX registers.
15943   }
15944   return TargetLowering::getConstraintType(Constraint);
15945 }
15946 
15947 /// Examine constraint type and operand type and determine a weight value.
15948 /// This object must already have been set up with the operand type
15949 /// and the current alternative constraint selected.
15950 TargetLowering::ConstraintWeight
15951 PPCTargetLowering::getSingleConstraintMatchWeight(
15952     AsmOperandInfo &info, const char *constraint) const {
15953   ConstraintWeight weight = CW_Invalid;
15954   Value *CallOperandVal = info.CallOperandVal;
15955     // If we don't have a value, we can't do a match,
15956     // but allow it at the lowest weight.
15957   if (!CallOperandVal)
15958     return CW_Default;
15959   Type *type = CallOperandVal->getType();
15960 
15961   // Look at the constraint type.
15962   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15963     return CW_Register; // an individual CR bit.
15964   else if ((StringRef(constraint) == "wa" ||
15965             StringRef(constraint) == "wd" ||
15966             StringRef(constraint) == "wf") &&
15967            type->isVectorTy())
15968     return CW_Register;
15969   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15970     return CW_Register; // just hold 64-bit integers data.
15971   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15972     return CW_Register;
15973   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15974     return CW_Register;
15975 
15976   switch (*constraint) {
15977   default:
15978     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15979     break;
15980   case 'b':
15981     if (type->isIntegerTy())
15982       weight = CW_Register;
15983     break;
15984   case 'f':
15985     if (type->isFloatTy())
15986       weight = CW_Register;
15987     break;
15988   case 'd':
15989     if (type->isDoubleTy())
15990       weight = CW_Register;
15991     break;
15992   case 'v':
15993     if (type->isVectorTy())
15994       weight = CW_Register;
15995     break;
15996   case 'y':
15997     weight = CW_Register;
15998     break;
15999   case 'Z':
16000     weight = CW_Memory;
16001     break;
16002   }
16003   return weight;
16004 }
16005 
16006 std::pair<unsigned, const TargetRegisterClass *>
16007 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
16008                                                 StringRef Constraint,
16009                                                 MVT VT) const {
16010   if (Constraint.size() == 1) {
16011     // GCC RS6000 Constraint Letters
16012     switch (Constraint[0]) {
16013     case 'b':   // R1-R31
16014       if (VT == MVT::i64 && Subtarget.isPPC64())
16015         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
16016       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
16017     case 'r':   // R0-R31
16018       if (VT == MVT::i64 && Subtarget.isPPC64())
16019         return std::make_pair(0U, &PPC::G8RCRegClass);
16020       return std::make_pair(0U, &PPC::GPRCRegClass);
16021     // 'd' and 'f' constraints are both defined to be "the floating point
16022     // registers", where one is for 32-bit and the other for 64-bit. We don't
16023     // really care overly much here so just give them all the same reg classes.
16024     case 'd':
16025     case 'f':
16026       if (Subtarget.hasSPE()) {
16027         if (VT == MVT::f32 || VT == MVT::i32)
16028           return std::make_pair(0U, &PPC::GPRCRegClass);
16029         if (VT == MVT::f64 || VT == MVT::i64)
16030           return std::make_pair(0U, &PPC::SPERCRegClass);
16031       } else {
16032         if (VT == MVT::f32 || VT == MVT::i32)
16033           return std::make_pair(0U, &PPC::F4RCRegClass);
16034         if (VT == MVT::f64 || VT == MVT::i64)
16035           return std::make_pair(0U, &PPC::F8RCRegClass);
16036       }
16037       break;
16038     case 'v':
16039       if (Subtarget.hasAltivec() && VT.isVector())
16040         return std::make_pair(0U, &PPC::VRRCRegClass);
16041       else if (Subtarget.hasVSX())
16042         // Scalars in Altivec registers only make sense with VSX.
16043         return std::make_pair(0U, &PPC::VFRCRegClass);
16044       break;
16045     case 'y':   // crrc
16046       return std::make_pair(0U, &PPC::CRRCRegClass);
16047     }
16048   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
16049     // An individual CR bit.
16050     return std::make_pair(0U, &PPC::CRBITRCRegClass);
16051   } else if ((Constraint == "wa" || Constraint == "wd" ||
16052              Constraint == "wf" || Constraint == "wi") &&
16053              Subtarget.hasVSX()) {
16054     // A VSX register for either a scalar (FP) or vector. There is no
16055     // support for single precision scalars on subtargets prior to Power8.
16056     if (VT.isVector())
16057       return std::make_pair(0U, &PPC::VSRCRegClass);
16058     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16059       return std::make_pair(0U, &PPC::VSSRCRegClass);
16060     return std::make_pair(0U, &PPC::VSFRCRegClass);
16061   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16062     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16063       return std::make_pair(0U, &PPC::VSSRCRegClass);
16064     else
16065       return std::make_pair(0U, &PPC::VSFRCRegClass);
16066   } else if (Constraint == "lr") {
16067     if (VT == MVT::i64)
16068       return std::make_pair(0U, &PPC::LR8RCRegClass);
16069     else
16070       return std::make_pair(0U, &PPC::LRRCRegClass);
16071   }
16072 
16073   // Handle special cases of physical registers that are not properly handled
16074   // by the base class.
16075   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16076     // If we name a VSX register, we can't defer to the base class because it
16077     // will not recognize the correct register (their names will be VSL{0-31}
16078     // and V{0-31} so they won't match). So we match them here.
16079     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16080       int VSNum = atoi(Constraint.data() + 3);
16081       assert(VSNum >= 0 && VSNum <= 63 &&
16082              "Attempted to access a vsr out of range");
16083       if (VSNum < 32)
16084         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16085       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16086     }
16087 
16088     // For float registers, we can't defer to the base class as it will match
16089     // the SPILLTOVSRRC class.
16090     if (Constraint.size() > 3 && Constraint[1] == 'f') {
16091       int RegNum = atoi(Constraint.data() + 2);
16092       if (RegNum > 31 || RegNum < 0)
16093         report_fatal_error("Invalid floating point register number");
16094       if (VT == MVT::f32 || VT == MVT::i32)
16095         return Subtarget.hasSPE()
16096                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16097                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16098       if (VT == MVT::f64 || VT == MVT::i64)
16099         return Subtarget.hasSPE()
16100                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16101                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16102     }
16103   }
16104 
16105   std::pair<unsigned, const TargetRegisterClass *> R =
16106       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16107 
16108   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16109   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16110   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16111   // register.
16112   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16113   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16114   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16115       PPC::GPRCRegClass.contains(R.first))
16116     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16117                             PPC::sub_32, &PPC::G8RCRegClass),
16118                           &PPC::G8RCRegClass);
16119 
16120   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16121   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16122     R.first = PPC::CR0;
16123     R.second = &PPC::CRRCRegClass;
16124   }
16125   // FIXME: This warning should ideally be emitted in the front end.
16126   const auto &TM = getTargetMachine();
16127   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16128     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16129          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16130         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16131       errs() << "warning: vector registers 20 to 32 are reserved in the "
16132                 "default AIX AltiVec ABI and cannot be used\n";
16133   }
16134 
16135   return R;
16136 }
16137 
16138 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16139 /// vector.  If it is invalid, don't add anything to Ops.
16140 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16141                                                      std::string &Constraint,
16142                                                      std::vector<SDValue>&Ops,
16143                                                      SelectionDAG &DAG) const {
16144   SDValue Result;
16145 
16146   // Only support length 1 constraints.
16147   if (Constraint.length() > 1) return;
16148 
16149   char Letter = Constraint[0];
16150   switch (Letter) {
16151   default: break;
16152   case 'I':
16153   case 'J':
16154   case 'K':
16155   case 'L':
16156   case 'M':
16157   case 'N':
16158   case 'O':
16159   case 'P': {
16160     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16161     if (!CST) return; // Must be an immediate to match.
16162     SDLoc dl(Op);
16163     int64_t Value = CST->getSExtValue();
16164     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16165                          // numbers are printed as such.
16166     switch (Letter) {
16167     default: llvm_unreachable("Unknown constraint letter!");
16168     case 'I':  // "I" is a signed 16-bit constant.
16169       if (isInt<16>(Value))
16170         Result = DAG.getTargetConstant(Value, dl, TCVT);
16171       break;
16172     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16173       if (isShiftedUInt<16, 16>(Value))
16174         Result = DAG.getTargetConstant(Value, dl, TCVT);
16175       break;
16176     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16177       if (isShiftedInt<16, 16>(Value))
16178         Result = DAG.getTargetConstant(Value, dl, TCVT);
16179       break;
16180     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16181       if (isUInt<16>(Value))
16182         Result = DAG.getTargetConstant(Value, dl, TCVT);
16183       break;
16184     case 'M':  // "M" is a constant that is greater than 31.
16185       if (Value > 31)
16186         Result = DAG.getTargetConstant(Value, dl, TCVT);
16187       break;
16188     case 'N':  // "N" is a positive constant that is an exact power of two.
16189       if (Value > 0 && isPowerOf2_64(Value))
16190         Result = DAG.getTargetConstant(Value, dl, TCVT);
16191       break;
16192     case 'O':  // "O" is the constant zero.
16193       if (Value == 0)
16194         Result = DAG.getTargetConstant(Value, dl, TCVT);
16195       break;
16196     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16197       if (isInt<16>(-Value))
16198         Result = DAG.getTargetConstant(Value, dl, TCVT);
16199       break;
16200     }
16201     break;
16202   }
16203   }
16204 
16205   if (Result.getNode()) {
16206     Ops.push_back(Result);
16207     return;
16208   }
16209 
16210   // Handle standard constraint letters.
16211   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16212 }
16213 
16214 // isLegalAddressingMode - Return true if the addressing mode represented
16215 // by AM is legal for this target, for a load/store of the specified type.
16216 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16217                                               const AddrMode &AM, Type *Ty,
16218                                               unsigned AS,
16219                                               Instruction *I) const {
16220   // Vector type r+i form is supported since power9 as DQ form. We don't check
16221   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16222   // imm form is preferred and the offset can be adjusted to use imm form later
16223   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16224   // max offset to check legal addressing mode, we should be a little aggressive
16225   // to contain other offsets for that LSRUse.
16226   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16227     return false;
16228 
16229   // PPC allows a sign-extended 16-bit immediate field.
16230   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16231     return false;
16232 
16233   // No global is ever allowed as a base.
16234   if (AM.BaseGV)
16235     return false;
16236 
16237   // PPC only support r+r,
16238   switch (AM.Scale) {
16239   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16240     break;
16241   case 1:
16242     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16243       return false;
16244     // Otherwise we have r+r or r+i.
16245     break;
16246   case 2:
16247     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16248       return false;
16249     // Allow 2*r as r+r.
16250     break;
16251   default:
16252     // No other scales are supported.
16253     return false;
16254   }
16255 
16256   return true;
16257 }
16258 
16259 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16260                                            SelectionDAG &DAG) const {
16261   MachineFunction &MF = DAG.getMachineFunction();
16262   MachineFrameInfo &MFI = MF.getFrameInfo();
16263   MFI.setReturnAddressIsTaken(true);
16264 
16265   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16266     return SDValue();
16267 
16268   SDLoc dl(Op);
16269   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16270 
16271   // Make sure the function does not optimize away the store of the RA to
16272   // the stack.
16273   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16274   FuncInfo->setLRStoreRequired();
16275   bool isPPC64 = Subtarget.isPPC64();
16276   auto PtrVT = getPointerTy(MF.getDataLayout());
16277 
16278   if (Depth > 0) {
16279     // The link register (return address) is saved in the caller's frame
16280     // not the callee's stack frame. So we must get the caller's frame
16281     // address and load the return address at the LR offset from there.
16282     SDValue FrameAddr =
16283         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16284                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16285     SDValue Offset =
16286         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16287                         isPPC64 ? MVT::i64 : MVT::i32);
16288     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16289                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16290                        MachinePointerInfo());
16291   }
16292 
16293   // Just load the return address off the stack.
16294   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16295   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16296                      MachinePointerInfo());
16297 }
16298 
16299 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16300                                           SelectionDAG &DAG) const {
16301   SDLoc dl(Op);
16302   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16303 
16304   MachineFunction &MF = DAG.getMachineFunction();
16305   MachineFrameInfo &MFI = MF.getFrameInfo();
16306   MFI.setFrameAddressIsTaken(true);
16307 
16308   EVT PtrVT = getPointerTy(MF.getDataLayout());
16309   bool isPPC64 = PtrVT == MVT::i64;
16310 
16311   // Naked functions never have a frame pointer, and so we use r1. For all
16312   // other functions, this decision must be delayed until during PEI.
16313   unsigned FrameReg;
16314   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16315     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16316   else
16317     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16318 
16319   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16320                                          PtrVT);
16321   while (Depth--)
16322     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16323                             FrameAddr, MachinePointerInfo());
16324   return FrameAddr;
16325 }
16326 
16327 // FIXME? Maybe this could be a TableGen attribute on some registers and
16328 // this table could be generated automatically from RegInfo.
16329 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16330                                               const MachineFunction &MF) const {
16331   bool isPPC64 = Subtarget.isPPC64();
16332 
16333   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16334   if (!is64Bit && VT != LLT::scalar(32))
16335     report_fatal_error("Invalid register global variable type");
16336 
16337   Register Reg = StringSwitch<Register>(RegName)
16338                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16339                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16340                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16341                      .Default(Register());
16342 
16343   if (Reg)
16344     return Reg;
16345   report_fatal_error("Invalid register name global variable");
16346 }
16347 
16348 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16349   // 32-bit SVR4 ABI access everything as got-indirect.
16350   if (Subtarget.is32BitELFABI())
16351     return true;
16352 
16353   // AIX accesses everything indirectly through the TOC, which is similar to
16354   // the GOT.
16355   if (Subtarget.isAIXABI())
16356     return true;
16357 
16358   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16359   // If it is small or large code model, module locals are accessed
16360   // indirectly by loading their address from .toc/.got.
16361   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16362     return true;
16363 
16364   // JumpTable and BlockAddress are accessed as got-indirect.
16365   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16366     return true;
16367 
16368   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16369     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16370 
16371   return false;
16372 }
16373 
16374 bool
16375 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16376   // The PowerPC target isn't yet aware of offsets.
16377   return false;
16378 }
16379 
16380 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16381                                            const CallInst &I,
16382                                            MachineFunction &MF,
16383                                            unsigned Intrinsic) const {
16384   switch (Intrinsic) {
16385   case Intrinsic::ppc_atomicrmw_xchg_i128:
16386   case Intrinsic::ppc_atomicrmw_add_i128:
16387   case Intrinsic::ppc_atomicrmw_sub_i128:
16388   case Intrinsic::ppc_atomicrmw_nand_i128:
16389   case Intrinsic::ppc_atomicrmw_and_i128:
16390   case Intrinsic::ppc_atomicrmw_or_i128:
16391   case Intrinsic::ppc_atomicrmw_xor_i128:
16392   case Intrinsic::ppc_cmpxchg_i128:
16393     Info.opc = ISD::INTRINSIC_W_CHAIN;
16394     Info.memVT = MVT::i128;
16395     Info.ptrVal = I.getArgOperand(0);
16396     Info.offset = 0;
16397     Info.align = Align(16);
16398     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16399                  MachineMemOperand::MOVolatile;
16400     return true;
16401   case Intrinsic::ppc_atomic_load_i128:
16402     Info.opc = ISD::INTRINSIC_W_CHAIN;
16403     Info.memVT = MVT::i128;
16404     Info.ptrVal = I.getArgOperand(0);
16405     Info.offset = 0;
16406     Info.align = Align(16);
16407     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16408     return true;
16409   case Intrinsic::ppc_atomic_store_i128:
16410     Info.opc = ISD::INTRINSIC_VOID;
16411     Info.memVT = MVT::i128;
16412     Info.ptrVal = I.getArgOperand(2);
16413     Info.offset = 0;
16414     Info.align = Align(16);
16415     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16416     return true;
16417   case Intrinsic::ppc_altivec_lvx:
16418   case Intrinsic::ppc_altivec_lvxl:
16419   case Intrinsic::ppc_altivec_lvebx:
16420   case Intrinsic::ppc_altivec_lvehx:
16421   case Intrinsic::ppc_altivec_lvewx:
16422   case Intrinsic::ppc_vsx_lxvd2x:
16423   case Intrinsic::ppc_vsx_lxvw4x:
16424   case Intrinsic::ppc_vsx_lxvd2x_be:
16425   case Intrinsic::ppc_vsx_lxvw4x_be:
16426   case Intrinsic::ppc_vsx_lxvl:
16427   case Intrinsic::ppc_vsx_lxvll: {
16428     EVT VT;
16429     switch (Intrinsic) {
16430     case Intrinsic::ppc_altivec_lvebx:
16431       VT = MVT::i8;
16432       break;
16433     case Intrinsic::ppc_altivec_lvehx:
16434       VT = MVT::i16;
16435       break;
16436     case Intrinsic::ppc_altivec_lvewx:
16437       VT = MVT::i32;
16438       break;
16439     case Intrinsic::ppc_vsx_lxvd2x:
16440     case Intrinsic::ppc_vsx_lxvd2x_be:
16441       VT = MVT::v2f64;
16442       break;
16443     default:
16444       VT = MVT::v4i32;
16445       break;
16446     }
16447 
16448     Info.opc = ISD::INTRINSIC_W_CHAIN;
16449     Info.memVT = VT;
16450     Info.ptrVal = I.getArgOperand(0);
16451     Info.offset = -VT.getStoreSize()+1;
16452     Info.size = 2*VT.getStoreSize()-1;
16453     Info.align = Align(1);
16454     Info.flags = MachineMemOperand::MOLoad;
16455     return true;
16456   }
16457   case Intrinsic::ppc_altivec_stvx:
16458   case Intrinsic::ppc_altivec_stvxl:
16459   case Intrinsic::ppc_altivec_stvebx:
16460   case Intrinsic::ppc_altivec_stvehx:
16461   case Intrinsic::ppc_altivec_stvewx:
16462   case Intrinsic::ppc_vsx_stxvd2x:
16463   case Intrinsic::ppc_vsx_stxvw4x:
16464   case Intrinsic::ppc_vsx_stxvd2x_be:
16465   case Intrinsic::ppc_vsx_stxvw4x_be:
16466   case Intrinsic::ppc_vsx_stxvl:
16467   case Intrinsic::ppc_vsx_stxvll: {
16468     EVT VT;
16469     switch (Intrinsic) {
16470     case Intrinsic::ppc_altivec_stvebx:
16471       VT = MVT::i8;
16472       break;
16473     case Intrinsic::ppc_altivec_stvehx:
16474       VT = MVT::i16;
16475       break;
16476     case Intrinsic::ppc_altivec_stvewx:
16477       VT = MVT::i32;
16478       break;
16479     case Intrinsic::ppc_vsx_stxvd2x:
16480     case Intrinsic::ppc_vsx_stxvd2x_be:
16481       VT = MVT::v2f64;
16482       break;
16483     default:
16484       VT = MVT::v4i32;
16485       break;
16486     }
16487 
16488     Info.opc = ISD::INTRINSIC_VOID;
16489     Info.memVT = VT;
16490     Info.ptrVal = I.getArgOperand(1);
16491     Info.offset = -VT.getStoreSize()+1;
16492     Info.size = 2*VT.getStoreSize()-1;
16493     Info.align = Align(1);
16494     Info.flags = MachineMemOperand::MOStore;
16495     return true;
16496   }
16497   default:
16498     break;
16499   }
16500 
16501   return false;
16502 }
16503 
16504 /// It returns EVT::Other if the type should be determined using generic
16505 /// target-independent logic.
16506 EVT PPCTargetLowering::getOptimalMemOpType(
16507     const MemOp &Op, const AttributeList &FuncAttributes) const {
16508   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16509     // We should use Altivec/VSX loads and stores when available. For unaligned
16510     // addresses, unaligned VSX loads are only fast starting with the P8.
16511     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16512         (Op.isAligned(Align(16)) ||
16513          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16514       return MVT::v4i32;
16515   }
16516 
16517   if (Subtarget.isPPC64()) {
16518     return MVT::i64;
16519   }
16520 
16521   return MVT::i32;
16522 }
16523 
16524 /// Returns true if it is beneficial to convert a load of a constant
16525 /// to just the constant itself.
16526 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16527                                                           Type *Ty) const {
16528   assert(Ty->isIntegerTy());
16529 
16530   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16531   return !(BitSize == 0 || BitSize > 64);
16532 }
16533 
16534 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16535   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16536     return false;
16537   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16538   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16539   return NumBits1 == 64 && NumBits2 == 32;
16540 }
16541 
16542 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16543   if (!VT1.isInteger() || !VT2.isInteger())
16544     return false;
16545   unsigned NumBits1 = VT1.getSizeInBits();
16546   unsigned NumBits2 = VT2.getSizeInBits();
16547   return NumBits1 == 64 && NumBits2 == 32;
16548 }
16549 
16550 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16551   // Generally speaking, zexts are not free, but they are free when they can be
16552   // folded with other operations.
16553   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16554     EVT MemVT = LD->getMemoryVT();
16555     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16556          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16557         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16558          LD->getExtensionType() == ISD::ZEXTLOAD))
16559       return true;
16560   }
16561 
16562   // FIXME: Add other cases...
16563   //  - 32-bit shifts with a zext to i64
16564   //  - zext after ctlz, bswap, etc.
16565   //  - zext after and by a constant mask
16566 
16567   return TargetLowering::isZExtFree(Val, VT2);
16568 }
16569 
16570 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16571   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16572          "invalid fpext types");
16573   // Extending to float128 is not free.
16574   if (DestVT == MVT::f128)
16575     return false;
16576   return true;
16577 }
16578 
16579 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16580   return isInt<16>(Imm) || isUInt<16>(Imm);
16581 }
16582 
16583 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16584   return isInt<16>(Imm) || isUInt<16>(Imm);
16585 }
16586 
16587 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16588                                                        MachineMemOperand::Flags,
16589                                                        bool *Fast) const {
16590   if (DisablePPCUnaligned)
16591     return false;
16592 
16593   // PowerPC supports unaligned memory access for simple non-vector types.
16594   // Although accessing unaligned addresses is not as efficient as accessing
16595   // aligned addresses, it is generally more efficient than manual expansion,
16596   // and generally only traps for software emulation when crossing page
16597   // boundaries.
16598 
16599   if (!VT.isSimple())
16600     return false;
16601 
16602   if (VT.isFloatingPoint() && !VT.isVector() &&
16603       !Subtarget.allowsUnalignedFPAccess())
16604     return false;
16605 
16606   if (VT.getSimpleVT().isVector()) {
16607     if (Subtarget.hasVSX()) {
16608       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16609           VT != MVT::v4f32 && VT != MVT::v4i32)
16610         return false;
16611     } else {
16612       return false;
16613     }
16614   }
16615 
16616   if (VT == MVT::ppcf128)
16617     return false;
16618 
16619   if (Fast)
16620     *Fast = true;
16621 
16622   return true;
16623 }
16624 
16625 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16626                                                SDValue C) const {
16627   // Check integral scalar types.
16628   if (!VT.isScalarInteger())
16629     return false;
16630   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16631     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16632       return false;
16633     // This transformation will generate >= 2 operations. But the following
16634     // cases will generate <= 2 instructions during ISEL. So exclude them.
16635     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16636     // HW instruction, ie. MULLI
16637     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16638     // instruction is needed than case 1, ie. MULLI and RLDICR
16639     int64_t Imm = ConstNode->getSExtValue();
16640     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16641     Imm >>= Shift;
16642     if (isInt<16>(Imm))
16643       return false;
16644     uint64_t UImm = static_cast<uint64_t>(Imm);
16645     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16646         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16647       return true;
16648   }
16649   return false;
16650 }
16651 
16652 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16653                                                    EVT VT) const {
16654   return isFMAFasterThanFMulAndFAdd(
16655       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16656 }
16657 
16658 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16659                                                    Type *Ty) const {
16660   switch (Ty->getScalarType()->getTypeID()) {
16661   case Type::FloatTyID:
16662   case Type::DoubleTyID:
16663     return true;
16664   case Type::FP128TyID:
16665     return Subtarget.hasP9Vector();
16666   default:
16667     return false;
16668   }
16669 }
16670 
16671 // FIXME: add more patterns which are not profitable to hoist.
16672 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16673   if (!I->hasOneUse())
16674     return true;
16675 
16676   Instruction *User = I->user_back();
16677   assert(User && "A single use instruction with no uses.");
16678 
16679   switch (I->getOpcode()) {
16680   case Instruction::FMul: {
16681     // Don't break FMA, PowerPC prefers FMA.
16682     if (User->getOpcode() != Instruction::FSub &&
16683         User->getOpcode() != Instruction::FAdd)
16684       return true;
16685 
16686     const TargetOptions &Options = getTargetMachine().Options;
16687     const Function *F = I->getFunction();
16688     const DataLayout &DL = F->getParent()->getDataLayout();
16689     Type *Ty = User->getOperand(0)->getType();
16690 
16691     return !(
16692         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16693         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16694         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16695   }
16696   case Instruction::Load: {
16697     // Don't break "store (load float*)" pattern, this pattern will be combined
16698     // to "store (load int32)" in later InstCombine pass. See function
16699     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16700     // cycles than loading a 32 bit integer.
16701     LoadInst *LI = cast<LoadInst>(I);
16702     // For the loads that combineLoadToOperationType does nothing, like
16703     // ordered load, it should be profitable to hoist them.
16704     // For swifterror load, it can only be used for pointer to pointer type, so
16705     // later type check should get rid of this case.
16706     if (!LI->isUnordered())
16707       return true;
16708 
16709     if (User->getOpcode() != Instruction::Store)
16710       return true;
16711 
16712     if (I->getType()->getTypeID() != Type::FloatTyID)
16713       return true;
16714 
16715     return false;
16716   }
16717   default:
16718     return true;
16719   }
16720   return true;
16721 }
16722 
16723 const MCPhysReg *
16724 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16725   // LR is a callee-save register, but we must treat it as clobbered by any call
16726   // site. Hence we include LR in the scratch registers, which are in turn added
16727   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16728   // to CTR, which is used by any indirect call.
16729   static const MCPhysReg ScratchRegs[] = {
16730     PPC::X12, PPC::LR8, PPC::CTR8, 0
16731   };
16732 
16733   return ScratchRegs;
16734 }
16735 
16736 Register PPCTargetLowering::getExceptionPointerRegister(
16737     const Constant *PersonalityFn) const {
16738   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16739 }
16740 
16741 Register PPCTargetLowering::getExceptionSelectorRegister(
16742     const Constant *PersonalityFn) const {
16743   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16744 }
16745 
16746 bool
16747 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16748                      EVT VT , unsigned DefinedValues) const {
16749   if (VT == MVT::v2i64)
16750     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16751 
16752   if (Subtarget.hasVSX())
16753     return true;
16754 
16755   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16756 }
16757 
16758 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16759   if (DisableILPPref || Subtarget.enableMachineScheduler())
16760     return TargetLowering::getSchedulingPreference(N);
16761 
16762   return Sched::ILP;
16763 }
16764 
16765 // Create a fast isel object.
16766 FastISel *
16767 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16768                                   const TargetLibraryInfo *LibInfo) const {
16769   return PPC::createFastISel(FuncInfo, LibInfo);
16770 }
16771 
16772 // 'Inverted' means the FMA opcode after negating one multiplicand.
16773 // For example, (fma -a b c) = (fnmsub a b c)
16774 static unsigned invertFMAOpcode(unsigned Opc) {
16775   switch (Opc) {
16776   default:
16777     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16778   case ISD::FMA:
16779     return PPCISD::FNMSUB;
16780   case PPCISD::FNMSUB:
16781     return ISD::FMA;
16782   }
16783 }
16784 
16785 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16786                                                 bool LegalOps, bool OptForSize,
16787                                                 NegatibleCost &Cost,
16788                                                 unsigned Depth) const {
16789   if (Depth > SelectionDAG::MaxRecursionDepth)
16790     return SDValue();
16791 
16792   unsigned Opc = Op.getOpcode();
16793   EVT VT = Op.getValueType();
16794   SDNodeFlags Flags = Op.getNode()->getFlags();
16795 
16796   switch (Opc) {
16797   case PPCISD::FNMSUB:
16798     if (!Op.hasOneUse() || !isTypeLegal(VT))
16799       break;
16800 
16801     const TargetOptions &Options = getTargetMachine().Options;
16802     SDValue N0 = Op.getOperand(0);
16803     SDValue N1 = Op.getOperand(1);
16804     SDValue N2 = Op.getOperand(2);
16805     SDLoc Loc(Op);
16806 
16807     NegatibleCost N2Cost = NegatibleCost::Expensive;
16808     SDValue NegN2 =
16809         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16810 
16811     if (!NegN2)
16812       return SDValue();
16813 
16814     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16815     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16816     // These transformations may change sign of zeroes. For example,
16817     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16818     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16819       // Try and choose the cheaper one to negate.
16820       NegatibleCost N0Cost = NegatibleCost::Expensive;
16821       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16822                                            N0Cost, Depth + 1);
16823 
16824       NegatibleCost N1Cost = NegatibleCost::Expensive;
16825       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16826                                            N1Cost, Depth + 1);
16827 
16828       if (NegN0 && N0Cost <= N1Cost) {
16829         Cost = std::min(N0Cost, N2Cost);
16830         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16831       } else if (NegN1) {
16832         Cost = std::min(N1Cost, N2Cost);
16833         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16834       }
16835     }
16836 
16837     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16838     if (isOperationLegal(ISD::FMA, VT)) {
16839       Cost = N2Cost;
16840       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16841     }
16842 
16843     break;
16844   }
16845 
16846   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16847                                               Cost, Depth);
16848 }
16849 
16850 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16851 bool PPCTargetLowering::useLoadStackGuardNode() const {
16852   if (!Subtarget.isTargetLinux())
16853     return TargetLowering::useLoadStackGuardNode();
16854   return true;
16855 }
16856 
16857 // Override to disable global variable loading on Linux and insert AIX canary
16858 // word declaration.
16859 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16860   if (Subtarget.isAIXABI()) {
16861     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16862                         Type::getInt8PtrTy(M.getContext()));
16863     return;
16864   }
16865   if (!Subtarget.isTargetLinux())
16866     return TargetLowering::insertSSPDeclarations(M);
16867 }
16868 
16869 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16870   if (Subtarget.isAIXABI())
16871     return M.getGlobalVariable(AIXSSPCanaryWordName);
16872   return TargetLowering::getSDagStackGuard(M);
16873 }
16874 
16875 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16876                                      bool ForCodeSize) const {
16877   if (!VT.isSimple() || !Subtarget.hasVSX())
16878     return false;
16879 
16880   switch(VT.getSimpleVT().SimpleTy) {
16881   default:
16882     // For FP types that are currently not supported by PPC backend, return
16883     // false. Examples: f16, f80.
16884     return false;
16885   case MVT::f32:
16886   case MVT::f64:
16887     if (Subtarget.hasPrefixInstrs()) {
16888       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16889       return true;
16890     }
16891     LLVM_FALLTHROUGH;
16892   case MVT::ppcf128:
16893     return Imm.isPosZero();
16894   }
16895 }
16896 
16897 // For vector shift operation op, fold
16898 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16899 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16900                                   SelectionDAG &DAG) {
16901   SDValue N0 = N->getOperand(0);
16902   SDValue N1 = N->getOperand(1);
16903   EVT VT = N0.getValueType();
16904   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16905   unsigned Opcode = N->getOpcode();
16906   unsigned TargetOpcode;
16907 
16908   switch (Opcode) {
16909   default:
16910     llvm_unreachable("Unexpected shift operation");
16911   case ISD::SHL:
16912     TargetOpcode = PPCISD::SHL;
16913     break;
16914   case ISD::SRL:
16915     TargetOpcode = PPCISD::SRL;
16916     break;
16917   case ISD::SRA:
16918     TargetOpcode = PPCISD::SRA;
16919     break;
16920   }
16921 
16922   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16923       N1->getOpcode() == ISD::AND)
16924     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16925       if (Mask->getZExtValue() == OpSizeInBits - 1)
16926         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16927 
16928   return SDValue();
16929 }
16930 
16931 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16932   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16933     return Value;
16934 
16935   SDValue N0 = N->getOperand(0);
16936   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16937   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16938       N0.getOpcode() != ISD::SIGN_EXTEND ||
16939       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16940       N->getValueType(0) != MVT::i64)
16941     return SDValue();
16942 
16943   // We can't save an operation here if the value is already extended, and
16944   // the existing shift is easier to combine.
16945   SDValue ExtsSrc = N0.getOperand(0);
16946   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16947       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16948     return SDValue();
16949 
16950   SDLoc DL(N0);
16951   SDValue ShiftBy = SDValue(CN1, 0);
16952   // We want the shift amount to be i32 on the extswli, but the shift could
16953   // have an i64.
16954   if (ShiftBy.getValueType() == MVT::i64)
16955     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16956 
16957   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16958                          ShiftBy);
16959 }
16960 
16961 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16962   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16963     return Value;
16964 
16965   return SDValue();
16966 }
16967 
16968 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16969   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16970     return Value;
16971 
16972   return SDValue();
16973 }
16974 
16975 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16976 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16977 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16978 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16979 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16980                                  const PPCSubtarget &Subtarget) {
16981   if (!Subtarget.isPPC64())
16982     return SDValue();
16983 
16984   SDValue LHS = N->getOperand(0);
16985   SDValue RHS = N->getOperand(1);
16986 
16987   auto isZextOfCompareWithConstant = [](SDValue Op) {
16988     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16989         Op.getValueType() != MVT::i64)
16990       return false;
16991 
16992     SDValue Cmp = Op.getOperand(0);
16993     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16994         Cmp.getOperand(0).getValueType() != MVT::i64)
16995       return false;
16996 
16997     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16998       int64_t NegConstant = 0 - Constant->getSExtValue();
16999       // Due to the limitations of the addi instruction,
17000       // -C is required to be [-32768, 32767].
17001       return isInt<16>(NegConstant);
17002     }
17003 
17004     return false;
17005   };
17006 
17007   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
17008   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
17009 
17010   // If there is a pattern, canonicalize a zext operand to the RHS.
17011   if (LHSHasPattern && !RHSHasPattern)
17012     std::swap(LHS, RHS);
17013   else if (!LHSHasPattern && !RHSHasPattern)
17014     return SDValue();
17015 
17016   SDLoc DL(N);
17017   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
17018   SDValue Cmp = RHS.getOperand(0);
17019   SDValue Z = Cmp.getOperand(0);
17020   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
17021   int64_t NegConstant = 0 - Constant->getSExtValue();
17022 
17023   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
17024   default: break;
17025   case ISD::SETNE: {
17026     //                                 when C == 0
17027     //                             --> addze X, (addic Z, -1).carry
17028     //                            /
17029     // add X, (zext(setne Z, C))--
17030     //                            \    when -32768 <= -C <= 32767 && C != 0
17031     //                             --> addze X, (addic (addi Z, -C), -1).carry
17032     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17033                               DAG.getConstant(NegConstant, DL, MVT::i64));
17034     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17035     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17036                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
17037     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17038                        SDValue(Addc.getNode(), 1));
17039     }
17040   case ISD::SETEQ: {
17041     //                                 when C == 0
17042     //                             --> addze X, (subfic Z, 0).carry
17043     //                            /
17044     // add X, (zext(sete  Z, C))--
17045     //                            \    when -32768 <= -C <= 32767 && C != 0
17046     //                             --> addze X, (subfic (addi Z, -C), 0).carry
17047     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17048                               DAG.getConstant(NegConstant, DL, MVT::i64));
17049     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17050     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17051                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
17052     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17053                        SDValue(Subc.getNode(), 1));
17054     }
17055   }
17056 
17057   return SDValue();
17058 }
17059 
17060 // Transform
17061 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17062 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17063 // In this case both C1 and C2 must be known constants.
17064 // C1+C2 must fit into a 34 bit signed integer.
17065 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17066                                           const PPCSubtarget &Subtarget) {
17067   if (!Subtarget.isUsingPCRelativeCalls())
17068     return SDValue();
17069 
17070   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17071   // If we find that node try to cast the Global Address and the Constant.
17072   SDValue LHS = N->getOperand(0);
17073   SDValue RHS = N->getOperand(1);
17074 
17075   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17076     std::swap(LHS, RHS);
17077 
17078   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17079     return SDValue();
17080 
17081   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17082   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17083   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17084 
17085   // Check that both casts succeeded.
17086   if (!GSDN || !ConstNode)
17087     return SDValue();
17088 
17089   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17090   SDLoc DL(GSDN);
17091 
17092   // The signed int offset needs to fit in 34 bits.
17093   if (!isInt<34>(NewOffset))
17094     return SDValue();
17095 
17096   // The new global address is a copy of the old global address except
17097   // that it has the updated Offset.
17098   SDValue GA =
17099       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17100                                  NewOffset, GSDN->getTargetFlags());
17101   SDValue MatPCRel =
17102       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17103   return MatPCRel;
17104 }
17105 
17106 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17107   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17108     return Value;
17109 
17110   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17111     return Value;
17112 
17113   return SDValue();
17114 }
17115 
17116 // Detect TRUNCATE operations on bitcasts of float128 values.
17117 // What we are looking for here is the situtation where we extract a subset
17118 // of bits from a 128 bit float.
17119 // This can be of two forms:
17120 // 1) BITCAST of f128 feeding TRUNCATE
17121 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17122 // The reason this is required is because we do not have a legal i128 type
17123 // and so we want to prevent having to store the f128 and then reload part
17124 // of it.
17125 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17126                                            DAGCombinerInfo &DCI) const {
17127   // If we are using CRBits then try that first.
17128   if (Subtarget.useCRBits()) {
17129     // Check if CRBits did anything and return that if it did.
17130     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17131       return CRTruncValue;
17132   }
17133 
17134   SDLoc dl(N);
17135   SDValue Op0 = N->getOperand(0);
17136 
17137   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17138   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17139     EVT VT = N->getValueType(0);
17140     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17141       return SDValue();
17142     SDValue Sub = Op0.getOperand(0);
17143     if (Sub.getOpcode() == ISD::SUB) {
17144       SDValue SubOp0 = Sub.getOperand(0);
17145       SDValue SubOp1 = Sub.getOperand(1);
17146       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17147           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17148         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17149                                SubOp1.getOperand(0),
17150                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17151       }
17152     }
17153   }
17154 
17155   // Looking for a truncate of i128 to i64.
17156   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17157     return SDValue();
17158 
17159   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17160 
17161   // SRL feeding TRUNCATE.
17162   if (Op0.getOpcode() == ISD::SRL) {
17163     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17164     // The right shift has to be by 64 bits.
17165     if (!ConstNode || ConstNode->getZExtValue() != 64)
17166       return SDValue();
17167 
17168     // Switch the element number to extract.
17169     EltToExtract = EltToExtract ? 0 : 1;
17170     // Update Op0 past the SRL.
17171     Op0 = Op0.getOperand(0);
17172   }
17173 
17174   // BITCAST feeding a TRUNCATE possibly via SRL.
17175   if (Op0.getOpcode() == ISD::BITCAST &&
17176       Op0.getValueType() == MVT::i128 &&
17177       Op0.getOperand(0).getValueType() == MVT::f128) {
17178     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17179     return DCI.DAG.getNode(
17180         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17181         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17182   }
17183   return SDValue();
17184 }
17185 
17186 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17187   SelectionDAG &DAG = DCI.DAG;
17188 
17189   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17190   if (!ConstOpOrElement)
17191     return SDValue();
17192 
17193   // An imul is usually smaller than the alternative sequence for legal type.
17194   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17195       isOperationLegal(ISD::MUL, N->getValueType(0)))
17196     return SDValue();
17197 
17198   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17199     switch (this->Subtarget.getCPUDirective()) {
17200     default:
17201       // TODO: enhance the condition for subtarget before pwr8
17202       return false;
17203     case PPC::DIR_PWR8:
17204       //  type        mul     add    shl
17205       // scalar        4       1      1
17206       // vector        7       2      2
17207       return true;
17208     case PPC::DIR_PWR9:
17209     case PPC::DIR_PWR10:
17210     case PPC::DIR_PWR_FUTURE:
17211       //  type        mul     add    shl
17212       // scalar        5       2      2
17213       // vector        7       2      2
17214 
17215       // The cycle RATIO of related operations are showed as a table above.
17216       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17217       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17218       // are 4, it is always profitable; but for 3 instrs patterns
17219       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17220       // So we should only do it for vector type.
17221       return IsAddOne && IsNeg ? VT.isVector() : true;
17222     }
17223   };
17224 
17225   EVT VT = N->getValueType(0);
17226   SDLoc DL(N);
17227 
17228   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17229   bool IsNeg = MulAmt.isNegative();
17230   APInt MulAmtAbs = MulAmt.abs();
17231 
17232   if ((MulAmtAbs - 1).isPowerOf2()) {
17233     // (mul x, 2^N + 1) => (add (shl x, N), x)
17234     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17235 
17236     if (!IsProfitable(IsNeg, true, VT))
17237       return SDValue();
17238 
17239     SDValue Op0 = N->getOperand(0);
17240     SDValue Op1 =
17241         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17242                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17243     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17244 
17245     if (!IsNeg)
17246       return Res;
17247 
17248     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17249   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17250     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17251     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17252 
17253     if (!IsProfitable(IsNeg, false, VT))
17254       return SDValue();
17255 
17256     SDValue Op0 = N->getOperand(0);
17257     SDValue Op1 =
17258         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17259                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17260 
17261     if (!IsNeg)
17262       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17263     else
17264       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17265 
17266   } else {
17267     return SDValue();
17268   }
17269 }
17270 
17271 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17272 // in combiner since we need to check SD flags and other subtarget features.
17273 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17274                                           DAGCombinerInfo &DCI) const {
17275   SDValue N0 = N->getOperand(0);
17276   SDValue N1 = N->getOperand(1);
17277   SDValue N2 = N->getOperand(2);
17278   SDNodeFlags Flags = N->getFlags();
17279   EVT VT = N->getValueType(0);
17280   SelectionDAG &DAG = DCI.DAG;
17281   const TargetOptions &Options = getTargetMachine().Options;
17282   unsigned Opc = N->getOpcode();
17283   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17284   bool LegalOps = !DCI.isBeforeLegalizeOps();
17285   SDLoc Loc(N);
17286 
17287   if (!isOperationLegal(ISD::FMA, VT))
17288     return SDValue();
17289 
17290   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17291   // since (fnmsub a b c)=-0 while c-ab=+0.
17292   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17293     return SDValue();
17294 
17295   // (fma (fneg a) b c) => (fnmsub a b c)
17296   // (fnmsub (fneg a) b c) => (fma a b c)
17297   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17298     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17299 
17300   // (fma a (fneg b) c) => (fnmsub a b c)
17301   // (fnmsub a (fneg b) c) => (fma a b c)
17302   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17303     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17304 
17305   return SDValue();
17306 }
17307 
17308 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17309   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17310   if (!Subtarget.is64BitELFABI())
17311     return false;
17312 
17313   // If not a tail call then no need to proceed.
17314   if (!CI->isTailCall())
17315     return false;
17316 
17317   // If sibling calls have been disabled and tail-calls aren't guaranteed
17318   // there is no reason to duplicate.
17319   auto &TM = getTargetMachine();
17320   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17321     return false;
17322 
17323   // Can't tail call a function called indirectly, or if it has variadic args.
17324   const Function *Callee = CI->getCalledFunction();
17325   if (!Callee || Callee->isVarArg())
17326     return false;
17327 
17328   // Make sure the callee and caller calling conventions are eligible for tco.
17329   const Function *Caller = CI->getParent()->getParent();
17330   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17331                                            CI->getCallingConv()))
17332       return false;
17333 
17334   // If the function is local then we have a good chance at tail-calling it
17335   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17336 }
17337 
17338 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17339   if (!Subtarget.hasVSX())
17340     return false;
17341   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17342     return true;
17343   return VT == MVT::f32 || VT == MVT::f64 ||
17344     VT == MVT::v4f32 || VT == MVT::v2f64;
17345 }
17346 
17347 bool PPCTargetLowering::
17348 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17349   const Value *Mask = AndI.getOperand(1);
17350   // If the mask is suitable for andi. or andis. we should sink the and.
17351   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17352     // Can't handle constants wider than 64-bits.
17353     if (CI->getBitWidth() > 64)
17354       return false;
17355     int64_t ConstVal = CI->getZExtValue();
17356     return isUInt<16>(ConstVal) ||
17357       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17358   }
17359 
17360   // For non-constant masks, we can always use the record-form and.
17361   return true;
17362 }
17363 
17364 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17365 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17366 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17367 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17368 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17369 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17370   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17371   assert(Subtarget.hasP9Altivec() &&
17372          "Only combine this when P9 altivec supported!");
17373   EVT VT = N->getValueType(0);
17374   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17375     return SDValue();
17376 
17377   SelectionDAG &DAG = DCI.DAG;
17378   SDLoc dl(N);
17379   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17380     // Even for signed integers, if it's known to be positive (as signed
17381     // integer) due to zero-extended inputs.
17382     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17383     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17384     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17385          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17386         (SubOpcd1 == ISD::ZERO_EXTEND ||
17387          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17388       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17389                          N->getOperand(0)->getOperand(0),
17390                          N->getOperand(0)->getOperand(1),
17391                          DAG.getTargetConstant(0, dl, MVT::i32));
17392     }
17393 
17394     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17395     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17396         N->getOperand(0).hasOneUse()) {
17397       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17398                          N->getOperand(0)->getOperand(0),
17399                          N->getOperand(0)->getOperand(1),
17400                          DAG.getTargetConstant(1, dl, MVT::i32));
17401     }
17402   }
17403 
17404   return SDValue();
17405 }
17406 
17407 // For type v4i32/v8ii16/v16i8, transform
17408 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17409 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17410 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17411 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17412 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17413                                           DAGCombinerInfo &DCI) const {
17414   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17415   assert(Subtarget.hasP9Altivec() &&
17416          "Only combine this when P9 altivec supported!");
17417 
17418   SelectionDAG &DAG = DCI.DAG;
17419   SDLoc dl(N);
17420   SDValue Cond = N->getOperand(0);
17421   SDValue TrueOpnd = N->getOperand(1);
17422   SDValue FalseOpnd = N->getOperand(2);
17423   EVT VT = N->getOperand(1).getValueType();
17424 
17425   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17426       FalseOpnd.getOpcode() != ISD::SUB)
17427     return SDValue();
17428 
17429   // ABSD only available for type v4i32/v8i16/v16i8
17430   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17431     return SDValue();
17432 
17433   // At least to save one more dependent computation
17434   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17435     return SDValue();
17436 
17437   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17438 
17439   // Can only handle unsigned comparison here
17440   switch (CC) {
17441   default:
17442     return SDValue();
17443   case ISD::SETUGT:
17444   case ISD::SETUGE:
17445     break;
17446   case ISD::SETULT:
17447   case ISD::SETULE:
17448     std::swap(TrueOpnd, FalseOpnd);
17449     break;
17450   }
17451 
17452   SDValue CmpOpnd1 = Cond.getOperand(0);
17453   SDValue CmpOpnd2 = Cond.getOperand(1);
17454 
17455   // SETCC CmpOpnd1 CmpOpnd2 cond
17456   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17457   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17458   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17459       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17460       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17461       FalseOpnd.getOperand(1) == CmpOpnd1) {
17462     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17463                        CmpOpnd1, CmpOpnd2,
17464                        DAG.getTargetConstant(0, dl, MVT::i32));
17465   }
17466 
17467   return SDValue();
17468 }
17469 
17470 /// getAddrModeForFlags - Based on the set of address flags, select the most
17471 /// optimal instruction format to match by.
17472 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17473   // This is not a node we should be handling here.
17474   if (Flags == PPC::MOF_None)
17475     return PPC::AM_None;
17476   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17477   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17478     if ((Flags & FlagSet) == FlagSet)
17479       return PPC::AM_DForm;
17480   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17481     if ((Flags & FlagSet) == FlagSet)
17482       return PPC::AM_DSForm;
17483   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17484     if ((Flags & FlagSet) == FlagSet)
17485       return PPC::AM_DQForm;
17486   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17487     if ((Flags & FlagSet) == FlagSet)
17488       return PPC::AM_PrefixDForm;
17489   // If no other forms are selected, return an X-Form as it is the most
17490   // general addressing mode.
17491   return PPC::AM_XForm;
17492 }
17493 
17494 /// Set alignment flags based on whether or not the Frame Index is aligned.
17495 /// Utilized when computing flags for address computation when selecting
17496 /// load and store instructions.
17497 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17498                                SelectionDAG &DAG) {
17499   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17500   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17501   if (!FI)
17502     return;
17503   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17504   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17505   // If this is (add $FI, $S16Imm), the alignment flags are already set
17506   // based on the immediate. We just need to clear the alignment flags
17507   // if the FI alignment is weaker.
17508   if ((FrameIndexAlign % 4) != 0)
17509     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17510   if ((FrameIndexAlign % 16) != 0)
17511     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17512   // If the address is a plain FrameIndex, set alignment flags based on
17513   // FI alignment.
17514   if (!IsAdd) {
17515     if ((FrameIndexAlign % 4) == 0)
17516       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17517     if ((FrameIndexAlign % 16) == 0)
17518       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17519   }
17520 }
17521 
17522 /// Given a node, compute flags that are used for address computation when
17523 /// selecting load and store instructions. The flags computed are stored in
17524 /// FlagSet. This function takes into account whether the node is a constant,
17525 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17526 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17527                                               SelectionDAG &DAG) {
17528   // Set the alignment flags for the node depending on if the node is
17529   // 4-byte or 16-byte aligned.
17530   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17531     if ((Imm & 0x3) == 0)
17532       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17533     if ((Imm & 0xf) == 0)
17534       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17535   };
17536 
17537   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17538     // All 32-bit constants can be computed as LIS + Disp.
17539     const APInt &ConstImm = CN->getAPIntValue();
17540     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17541       FlagSet |= PPC::MOF_AddrIsSImm32;
17542       SetAlignFlagsForImm(ConstImm.getZExtValue());
17543       setAlignFlagsForFI(N, FlagSet, DAG);
17544     }
17545     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17546       FlagSet |= PPC::MOF_RPlusSImm34;
17547     else // Let constant materialization handle large constants.
17548       FlagSet |= PPC::MOF_NotAddNorCst;
17549   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17550     // This address can be represented as an addition of:
17551     // - Register + Imm16 (possibly a multiple of 4/16)
17552     // - Register + Imm34
17553     // - Register + PPCISD::Lo
17554     // - Register + Register
17555     // In any case, we won't have to match this as Base + Zero.
17556     SDValue RHS = N.getOperand(1);
17557     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17558       const APInt &ConstImm = CN->getAPIntValue();
17559       if (ConstImm.isSignedIntN(16)) {
17560         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17561         SetAlignFlagsForImm(ConstImm.getZExtValue());
17562         setAlignFlagsForFI(N, FlagSet, DAG);
17563       }
17564       if (ConstImm.isSignedIntN(34))
17565         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17566       else
17567         FlagSet |= PPC::MOF_RPlusR; // Register.
17568     } else if (RHS.getOpcode() == PPCISD::Lo &&
17569                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17570       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17571     else
17572       FlagSet |= PPC::MOF_RPlusR;
17573   } else { // The address computation is not a constant or an addition.
17574     setAlignFlagsForFI(N, FlagSet, DAG);
17575     FlagSet |= PPC::MOF_NotAddNorCst;
17576   }
17577 }
17578 
17579 static bool isPCRelNode(SDValue N) {
17580   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17581       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17582       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17583       isValidPCRelNode<JumpTableSDNode>(N) ||
17584       isValidPCRelNode<BlockAddressSDNode>(N));
17585 }
17586 
17587 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17588 /// the address flags of the load/store instruction that is to be matched.
17589 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17590                                            SelectionDAG &DAG) const {
17591   unsigned FlagSet = PPC::MOF_None;
17592 
17593   // Compute subtarget flags.
17594   if (!Subtarget.hasP9Vector())
17595     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17596   else {
17597     FlagSet |= PPC::MOF_SubtargetP9;
17598     if (Subtarget.hasPrefixInstrs())
17599       FlagSet |= PPC::MOF_SubtargetP10;
17600   }
17601   if (Subtarget.hasSPE())
17602     FlagSet |= PPC::MOF_SubtargetSPE;
17603 
17604   // Check if we have a PCRel node and return early.
17605   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17606     return FlagSet;
17607 
17608   // If the node is the paired load/store intrinsics, compute flags for
17609   // address computation and return early.
17610   unsigned ParentOp = Parent->getOpcode();
17611   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17612                                (ParentOp == ISD::INTRINSIC_VOID))) {
17613     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17614     if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
17615       SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
17616                              ? Parent->getOperand(2)
17617                              : Parent->getOperand(3);
17618       computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17619       FlagSet |= PPC::MOF_Vector;
17620       return FlagSet;
17621     }
17622   }
17623 
17624   // Mark this as something we don't want to handle here if it is atomic
17625   // or pre-increment instruction.
17626   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17627     if (LSB->isIndexed())
17628       return PPC::MOF_None;
17629 
17630   // Compute in-memory type flags. This is based on if there are scalars,
17631   // floats or vectors.
17632   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17633   assert(MN && "Parent should be a MemSDNode!");
17634   EVT MemVT = MN->getMemoryVT();
17635   unsigned Size = MemVT.getSizeInBits();
17636   if (MemVT.isScalarInteger()) {
17637     assert(Size <= 128 &&
17638            "Not expecting scalar integers larger than 16 bytes!");
17639     if (Size < 32)
17640       FlagSet |= PPC::MOF_SubWordInt;
17641     else if (Size == 32)
17642       FlagSet |= PPC::MOF_WordInt;
17643     else
17644       FlagSet |= PPC::MOF_DoubleWordInt;
17645   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17646     if (Size == 128)
17647       FlagSet |= PPC::MOF_Vector;
17648     else if (Size == 256) {
17649       assert(Subtarget.pairedVectorMemops() &&
17650              "256-bit vectors are only available when paired vector memops is "
17651              "enabled!");
17652       FlagSet |= PPC::MOF_Vector;
17653     } else
17654       llvm_unreachable("Not expecting illegal vectors!");
17655   } else { // Floating point type: can be scalar, f128 or vector types.
17656     if (Size == 32 || Size == 64)
17657       FlagSet |= PPC::MOF_ScalarFloat;
17658     else if (MemVT == MVT::f128 || MemVT.isVector())
17659       FlagSet |= PPC::MOF_Vector;
17660     else
17661       llvm_unreachable("Not expecting illegal scalar floats!");
17662   }
17663 
17664   // Compute flags for address computation.
17665   computeFlagsForAddressComputation(N, FlagSet, DAG);
17666 
17667   // Compute type extension flags.
17668   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17669     switch (LN->getExtensionType()) {
17670     case ISD::SEXTLOAD:
17671       FlagSet |= PPC::MOF_SExt;
17672       break;
17673     case ISD::EXTLOAD:
17674     case ISD::ZEXTLOAD:
17675       FlagSet |= PPC::MOF_ZExt;
17676       break;
17677     case ISD::NON_EXTLOAD:
17678       FlagSet |= PPC::MOF_NoExt;
17679       break;
17680     }
17681   } else
17682     FlagSet |= PPC::MOF_NoExt;
17683 
17684   // For integers, no extension is the same as zero extension.
17685   // We set the extension mode to zero extension so we don't have
17686   // to add separate entries in AddrModesMap for loads and stores.
17687   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17688     FlagSet |= PPC::MOF_ZExt;
17689     FlagSet &= ~PPC::MOF_NoExt;
17690   }
17691 
17692   // If we don't have prefixed instructions, 34-bit constants should be
17693   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17694   bool IsNonP1034BitConst =
17695       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17696        FlagSet) == PPC::MOF_RPlusSImm34;
17697   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17698       IsNonP1034BitConst)
17699     FlagSet |= PPC::MOF_NotAddNorCst;
17700 
17701   return FlagSet;
17702 }
17703 
17704 /// SelectForceXFormMode - Given the specified address, force it to be
17705 /// represented as an indexed [r+r] operation (an XForm instruction).
17706 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17707                                                       SDValue &Base,
17708                                                       SelectionDAG &DAG) const {
17709 
17710   PPC::AddrMode Mode = PPC::AM_XForm;
17711   int16_t ForceXFormImm = 0;
17712   if (provablyDisjointOr(DAG, N) &&
17713       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17714     Disp = N.getOperand(0);
17715     Base = N.getOperand(1);
17716     return Mode;
17717   }
17718 
17719   // If the address is the result of an add, we will utilize the fact that the
17720   // address calculation includes an implicit add.  However, we can reduce
17721   // register pressure if we do not materialize a constant just for use as the
17722   // index register.  We only get rid of the add if it is not an add of a
17723   // value and a 16-bit signed constant and both have a single use.
17724   if (N.getOpcode() == ISD::ADD &&
17725       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17726        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17727     Disp = N.getOperand(0);
17728     Base = N.getOperand(1);
17729     return Mode;
17730   }
17731 
17732   // Otherwise, use R0 as the base register.
17733   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17734                          N.getValueType());
17735   Base = N;
17736 
17737   return Mode;
17738 }
17739 
17740 bool PPCTargetLowering::splitValueIntoRegisterParts(
17741     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
17742     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
17743   EVT ValVT = Val.getValueType();
17744   // If we are splitting a scalar integer into f64 parts (i.e. so they
17745   // can be placed into VFRC registers), we need to zero extend and
17746   // bitcast the values. This will ensure the value is placed into a
17747   // VSR using direct moves or stack operations as needed.
17748   if (PartVT == MVT::f64 &&
17749       (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
17750     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
17751     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
17752     Parts[0] = Val;
17753     return true;
17754   }
17755   return false;
17756 }
17757 
17758 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
17759                                           SelectionDAG &DAG) const {
17760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17761   TargetLowering::CallLoweringInfo CLI(DAG);
17762   EVT RetVT = Op.getValueType();
17763   SDValue Callee =
17764       DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
17765   bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
17766   TargetLowering::ArgListTy Args;
17767   TargetLowering::ArgListEntry Entry;
17768   for (const SDValue &N : Op->op_values()) {
17769     EVT ArgVT = N.getValueType();
17770     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17771     Entry.Node = N;
17772     Entry.Ty = ArgTy;
17773     Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
17774     Entry.IsZExt = !Entry.IsSExt;
17775     Args.push_back(Entry);
17776   }
17777   CLI.setDebugLoc(SDLoc(Op))
17778       .setChain(DAG.getEntryNode())
17779       .setLibCallee(CallingConv::C, RetVT.getTypeForEVT(*DAG.getContext()),
17780                     Callee, std::move(Args))
17781       .setTailCall(true)
17782       .setSExtResult(SignExtend)
17783       .setZExtResult(!SignExtend)
17784       .setIsPostTypeLegalization(true);
17785   return TLI.LowerCallTo(CLI).first;
17786 }
17787 
17788 SDValue PPCTargetLowering::lowerLibCallBasedOnType(
17789     const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
17790     SelectionDAG &DAG) const {
17791   if (Op.getValueType() == MVT::f32)
17792     return lowerToLibCall(LibCallFloatName, Op, DAG);
17793 
17794   if (Op.getValueType() == MVT::f64)
17795     return lowerToLibCall(LibCallDoubleName, Op, DAG);
17796 
17797   return SDValue();
17798 }
17799 
17800 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
17801   SDNodeFlags Flags = Op.getNode()->getFlags();
17802   return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
17803          Flags.hasNoNaNs() && Flags.hasNoInfs();
17804 }
17805 
17806 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
17807   return Op.getNode()->getFlags().hasApproximateFuncs();
17808 }
17809 
17810 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
17811                                             const char *LibCallFloatName,
17812                                             const char *LibCallDoubleNameFinite,
17813                                             const char *LibCallFloatNameFinite,
17814                                             SDValue Op,
17815                                             SelectionDAG &DAG) const {
17816   if (!isLowringToMASSSafe(Op))
17817     return SDValue();
17818 
17819   if (!isLowringToMASSFiniteSafe(Op))
17820     return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
17821                                    DAG);
17822 
17823   return lowerLibCallBasedOnType(LibCallFloatNameFinite,
17824                                  LibCallDoubleNameFinite, Op, DAG);
17825 }
17826 
17827 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
17828   return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
17829                           "__xl_powf_finite", Op, DAG);
17830 }
17831 
17832 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
17833   return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
17834                           "__xl_sinf_finite", Op, DAG);
17835 }
17836 
17837 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
17838   return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
17839                           "__xl_cosf_finite", Op, DAG);
17840 }
17841 
17842 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
17843   return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
17844                           "__xl_logf_finite", Op, DAG);
17845 }
17846 
17847 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
17848   return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
17849                           "__xl_log10f_finite", Op, DAG);
17850 }
17851 
17852 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
17853   return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
17854                           "__xl_expf_finite", Op, DAG);
17855 }
17856 
17857 // If we happen to match to an aligned D-Form, check if the Frame Index is
17858 // adequately aligned. If it is not, reset the mode to match to X-Form.
17859 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17860                                    PPC::AddrMode &Mode) {
17861   if (!isa<FrameIndexSDNode>(N))
17862     return;
17863   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17864       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17865     Mode = PPC::AM_XForm;
17866 }
17867 
17868 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17869 /// compute the address flags of the node, get the optimal address mode based
17870 /// on the flags, and set the Base and Disp based on the address mode.
17871 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17872                                                        SDValue N, SDValue &Disp,
17873                                                        SDValue &Base,
17874                                                        SelectionDAG &DAG,
17875                                                        MaybeAlign Align) const {
17876   SDLoc DL(Parent);
17877 
17878   // Compute the address flags.
17879   unsigned Flags = computeMOFlags(Parent, N, DAG);
17880 
17881   // Get the optimal address mode based on the Flags.
17882   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17883 
17884   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17885   // Select an X-Form load if it is not.
17886   setXFormForUnalignedFI(N, Flags, Mode);
17887 
17888   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17889   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17890     assert(Subtarget.isUsingPCRelativeCalls() &&
17891            "Must be using PC-Relative calls when a valid PC-Relative node is "
17892            "present!");
17893     Mode = PPC::AM_PCRel;
17894   }
17895 
17896   // Set Base and Disp accordingly depending on the address mode.
17897   switch (Mode) {
17898   case PPC::AM_DForm:
17899   case PPC::AM_DSForm:
17900   case PPC::AM_DQForm: {
17901     // This is a register plus a 16-bit immediate. The base will be the
17902     // register and the displacement will be the immediate unless it
17903     // isn't sufficiently aligned.
17904     if (Flags & PPC::MOF_RPlusSImm16) {
17905       SDValue Op0 = N.getOperand(0);
17906       SDValue Op1 = N.getOperand(1);
17907       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17908       if (!Align || isAligned(*Align, Imm)) {
17909         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17910         Base = Op0;
17911         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17912           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17913           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17914         }
17915         break;
17916       }
17917     }
17918     // This is a register plus the @lo relocation. The base is the register
17919     // and the displacement is the global address.
17920     else if (Flags & PPC::MOF_RPlusLo) {
17921       Disp = N.getOperand(1).getOperand(0); // The global address.
17922       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17923              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17924              Disp.getOpcode() == ISD::TargetConstantPool ||
17925              Disp.getOpcode() == ISD::TargetJumpTable);
17926       Base = N.getOperand(0);
17927       break;
17928     }
17929     // This is a constant address at most 32 bits. The base will be
17930     // zero or load-immediate-shifted and the displacement will be
17931     // the low 16 bits of the address.
17932     else if (Flags & PPC::MOF_AddrIsSImm32) {
17933       auto *CN = cast<ConstantSDNode>(N);
17934       EVT CNType = CN->getValueType(0);
17935       uint64_t CNImm = CN->getZExtValue();
17936       // If this address fits entirely in a 16-bit sext immediate field, codegen
17937       // this as "d, 0".
17938       int16_t Imm;
17939       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17940         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17941         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17942                                CNType);
17943         break;
17944       }
17945       // Handle 32-bit sext immediate with LIS + Addr mode.
17946       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17947           (!Align || isAligned(*Align, CNImm))) {
17948         int32_t Addr = (int32_t)CNImm;
17949         // Otherwise, break this down into LIS + Disp.
17950         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17951         Base =
17952             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17953         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17954         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17955         break;
17956       }
17957     }
17958     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17959     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17960     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17961       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17962       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17963     } else
17964       Base = N;
17965     break;
17966   }
17967   case PPC::AM_PrefixDForm: {
17968     int64_t Imm34 = 0;
17969     unsigned Opcode = N.getOpcode();
17970     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17971         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17972       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17973       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17974       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17975         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17976       else
17977         Base = N.getOperand(0);
17978     } else if (isIntS34Immediate(N, Imm34)) {
17979       // The address is a 34-bit signed immediate.
17980       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17981       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
17982     }
17983     break;
17984   }
17985   case PPC::AM_PCRel: {
17986     // When selecting PC-Relative instructions, "Base" is not utilized as
17987     // we select the address as [PC+imm].
17988     Disp = N;
17989     break;
17990   }
17991   case PPC::AM_None:
17992     break;
17993   default: { // By default, X-Form is always available to be selected.
17994     // When a frame index is not aligned, we also match by XForm.
17995     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
17996     Base = FI ? N : N.getOperand(1);
17997     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17998                                 N.getValueType())
17999               : N.getOperand(0);
18000     break;
18001   }
18002   }
18003   return Mode;
18004 }
18005 
18006 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
18007                                                  bool Return,
18008                                                  bool IsVarArg) const {
18009   switch (CC) {
18010   case CallingConv::Cold:
18011     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
18012   default:
18013     return CC_PPC64_ELF_FIS;
18014   }
18015 }
18016 
18017 TargetLowering::AtomicExpansionKind
18018 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18019   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18020   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18021     return AtomicExpansionKind::MaskedIntrinsic;
18022   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
18023 }
18024 
18025 TargetLowering::AtomicExpansionKind
18026 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18027   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
18028   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18029     return AtomicExpansionKind::MaskedIntrinsic;
18030   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
18031 }
18032 
18033 static Intrinsic::ID
18034 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
18035   switch (BinOp) {
18036   default:
18037     llvm_unreachable("Unexpected AtomicRMW BinOp");
18038   case AtomicRMWInst::Xchg:
18039     return Intrinsic::ppc_atomicrmw_xchg_i128;
18040   case AtomicRMWInst::Add:
18041     return Intrinsic::ppc_atomicrmw_add_i128;
18042   case AtomicRMWInst::Sub:
18043     return Intrinsic::ppc_atomicrmw_sub_i128;
18044   case AtomicRMWInst::And:
18045     return Intrinsic::ppc_atomicrmw_and_i128;
18046   case AtomicRMWInst::Or:
18047     return Intrinsic::ppc_atomicrmw_or_i128;
18048   case AtomicRMWInst::Xor:
18049     return Intrinsic::ppc_atomicrmw_xor_i128;
18050   case AtomicRMWInst::Nand:
18051     return Intrinsic::ppc_atomicrmw_nand_i128;
18052   }
18053 }
18054 
18055 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
18056     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
18057     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
18058   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18059          "Only support quadword now");
18060   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18061   Type *ValTy = Incr->getType();
18062   assert(ValTy->getPrimitiveSizeInBits() == 128);
18063   Function *RMW = Intrinsic::getDeclaration(
18064       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
18065   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18066   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
18067   Value *IncrHi =
18068       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
18069   Value *Addr =
18070       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18071   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
18072   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18073   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18074   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18075   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18076   return Builder.CreateOr(
18077       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18078 }
18079 
18080 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
18081     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
18082     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
18083   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18084          "Only support quadword now");
18085   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18086   Type *ValTy = CmpVal->getType();
18087   assert(ValTy->getPrimitiveSizeInBits() == 128);
18088   Function *IntCmpXchg =
18089       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
18090   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18091   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
18092   Value *CmpHi =
18093       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
18094   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
18095   Value *NewHi =
18096       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
18097   Value *Addr =
18098       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18099   emitLeadingFence(Builder, CI, Ord);
18100   Value *LoHi =
18101       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
18102   emitTrailingFence(Builder, CI, Ord);
18103   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18104   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18105   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18106   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18107   return Builder.CreateOr(
18108       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18109 }
18110