1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> EnableQuadwordAtomics(
125     "ppc-quadword-atomics",
126     cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127     cl::Hidden);
128 
129 static cl::opt<bool>
130     DisablePerfectShuffle("ppc-disable-perfect-shuffle",
131                           cl::desc("disable vector permute decomposition"),
132                           cl::init(true), cl::Hidden);
133 
134 STATISTIC(NumTailCalls, "Number of tail calls");
135 STATISTIC(NumSiblingCalls, "Number of sibling calls");
136 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
137 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
138 
139 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
140 
141 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
142 
143 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
144 
145 // FIXME: Remove this once the bug has been fixed!
146 extern cl::opt<bool> ANDIGlueBug;
147 
148 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
149                                      const PPCSubtarget &STI)
150     : TargetLowering(TM), Subtarget(STI) {
151   // Initialize map that relates the PPC addressing modes to the computed flags
152   // of a load/store instruction. The map is used to determine the optimal
153   // addressing mode when selecting load and stores.
154   initializeAddrModeMap();
155   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
156   // arguments are at least 4/8 bytes aligned.
157   bool isPPC64 = Subtarget.isPPC64();
158   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
159 
160   // Set up the register classes.
161   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
162   if (!useSoftFloat()) {
163     if (hasSPE()) {
164       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
165       // EFPU2 APU only supports f32
166       if (!Subtarget.hasEFPU2())
167         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
168     } else {
169       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
170       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
171     }
172   }
173 
174   // Match BITREVERSE to customized fast code sequence in the td file.
175   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
176   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
177 
178   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
179   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
180 
181   // Custom lower inline assembly to check for special registers.
182   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
183   setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
184 
185   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
186   for (MVT VT : MVT::integer_valuetypes()) {
187     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
188     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
189   }
190 
191   if (Subtarget.isISA3_0()) {
192     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
193     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
194     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
195     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
196   } else {
197     // No extending loads from f16 or HW conversions back and forth.
198     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
199     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
200     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
201     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
202     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
203     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
204     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
205     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
206   }
207 
208   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
209 
210   // PowerPC has pre-inc load and store's.
211   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
212   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
213   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
214   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
215   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
216   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
217   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
218   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
219   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
220   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
221   if (!Subtarget.hasSPE()) {
222     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
223     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
224     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
225     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
226   }
227 
228   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
229   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
230   for (MVT VT : ScalarIntVTs) {
231     setOperationAction(ISD::ADDC, VT, Legal);
232     setOperationAction(ISD::ADDE, VT, Legal);
233     setOperationAction(ISD::SUBC, VT, Legal);
234     setOperationAction(ISD::SUBE, VT, Legal);
235   }
236 
237   if (Subtarget.useCRBits()) {
238     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
239 
240     if (isPPC64 || Subtarget.hasFPCVT()) {
241       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
242       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
243                         isPPC64 ? MVT::i64 : MVT::i32);
244       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
245       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
246                         isPPC64 ? MVT::i64 : MVT::i32);
247 
248       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
249       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
250                          isPPC64 ? MVT::i64 : MVT::i32);
251       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
252       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
253                         isPPC64 ? MVT::i64 : MVT::i32);
254 
255       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
256       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
257                         isPPC64 ? MVT::i64 : MVT::i32);
258       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
259       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
260                         isPPC64 ? MVT::i64 : MVT::i32);
261 
262       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
263       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
264                         isPPC64 ? MVT::i64 : MVT::i32);
265       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
266       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
267                         isPPC64 ? MVT::i64 : MVT::i32);
268     } else {
269       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
270       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
271       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
272       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
273     }
274 
275     // PowerPC does not support direct load/store of condition registers.
276     setOperationAction(ISD::LOAD, MVT::i1, Custom);
277     setOperationAction(ISD::STORE, MVT::i1, Custom);
278 
279     // FIXME: Remove this once the ANDI glue bug is fixed:
280     if (ANDIGlueBug)
281       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
282 
283     for (MVT VT : MVT::integer_valuetypes()) {
284       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
285       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
286       setTruncStoreAction(VT, MVT::i1, Expand);
287     }
288 
289     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
290   }
291 
292   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
293   // PPC (the libcall is not available).
294   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
295   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
296   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
297   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
298 
299   // We do not currently implement these libm ops for PowerPC.
300   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
301   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
302   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
303   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
304   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
305   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
306 
307   // PowerPC has no SREM/UREM instructions unless we are on P9
308   // On P9 we may use a hardware instruction to compute the remainder.
309   // When the result of both the remainder and the division is required it is
310   // more efficient to compute the remainder from the result of the division
311   // rather than use the remainder instruction. The instructions are legalized
312   // directly because the DivRemPairsPass performs the transformation at the IR
313   // level.
314   if (Subtarget.isISA3_0()) {
315     setOperationAction(ISD::SREM, MVT::i32, Legal);
316     setOperationAction(ISD::UREM, MVT::i32, Legal);
317     setOperationAction(ISD::SREM, MVT::i64, Legal);
318     setOperationAction(ISD::UREM, MVT::i64, Legal);
319   } else {
320     setOperationAction(ISD::SREM, MVT::i32, Expand);
321     setOperationAction(ISD::UREM, MVT::i32, Expand);
322     setOperationAction(ISD::SREM, MVT::i64, Expand);
323     setOperationAction(ISD::UREM, MVT::i64, Expand);
324   }
325 
326   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
327   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
328   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
329   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
330   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
331   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
332   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
333   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
334   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
335 
336   // Handle constrained floating-point operations of scalar.
337   // TODO: Handle SPE specific operation.
338   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
339   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
340   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
341   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
342   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
343 
344   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
345   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
346   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
347   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
348 
349   if (!Subtarget.hasSPE()) {
350     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
352   }
353 
354   if (Subtarget.hasVSX()) {
355     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
357   }
358 
359   if (Subtarget.hasFSQRT()) {
360     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
361     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
362   }
363 
364   if (Subtarget.hasFPRND()) {
365     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
366     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
367     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
368     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
369 
370     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
371     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
372     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
373     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
374   }
375 
376   // We don't support sin/cos/sqrt/fmod/pow
377   setOperationAction(ISD::FSIN , MVT::f64, Expand);
378   setOperationAction(ISD::FCOS , MVT::f64, Expand);
379   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
380   setOperationAction(ISD::FREM , MVT::f64, Expand);
381   setOperationAction(ISD::FPOW , MVT::f64, Expand);
382   setOperationAction(ISD::FSIN , MVT::f32, Expand);
383   setOperationAction(ISD::FCOS , MVT::f32, Expand);
384   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
385   setOperationAction(ISD::FREM , MVT::f32, Expand);
386   setOperationAction(ISD::FPOW , MVT::f32, Expand);
387 
388   // MASS transformation for LLVM intrinsics with replicating fast-math flag
389   // to be consistent to PPCGenScalarMASSEntries pass
390   if (TM.getOptLevel() == CodeGenOpt::Aggressive &&
391       TM.Options.PPCGenScalarMASSEntries) {
392     setOperationAction(ISD::FSIN , MVT::f64, Custom);
393     setOperationAction(ISD::FCOS , MVT::f64, Custom);
394     setOperationAction(ISD::FPOW , MVT::f64, Custom);
395     setOperationAction(ISD::FLOG, MVT::f64, Custom);
396     setOperationAction(ISD::FLOG10, MVT::f64, Custom);
397     setOperationAction(ISD::FEXP, MVT::f64, Custom);
398     setOperationAction(ISD::FSIN , MVT::f32, Custom);
399     setOperationAction(ISD::FCOS , MVT::f32, Custom);
400     setOperationAction(ISD::FPOW , MVT::f32, Custom);
401     setOperationAction(ISD::FLOG, MVT::f32, Custom);
402     setOperationAction(ISD::FLOG10, MVT::f32, Custom);
403     setOperationAction(ISD::FEXP, MVT::f32, Custom);
404   }
405 
406   if (Subtarget.hasSPE()) {
407     setOperationAction(ISD::FMA  , MVT::f64, Expand);
408     setOperationAction(ISD::FMA  , MVT::f32, Expand);
409   } else {
410     setOperationAction(ISD::FMA  , MVT::f64, Legal);
411     setOperationAction(ISD::FMA  , MVT::f32, Legal);
412   }
413 
414   if (Subtarget.hasSPE())
415     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
416 
417   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
418 
419   // If we're enabling GP optimizations, use hardware square root
420   if (!Subtarget.hasFSQRT() &&
421       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
422         Subtarget.hasFRE()))
423     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
424 
425   if (!Subtarget.hasFSQRT() &&
426       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
427         Subtarget.hasFRES()))
428     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
429 
430   if (Subtarget.hasFCPSGN()) {
431     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
432     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
433   } else {
434     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
435     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
436   }
437 
438   if (Subtarget.hasFPRND()) {
439     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
440     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
441     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
442     setOperationAction(ISD::FROUND, MVT::f64, Legal);
443 
444     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
445     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
446     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
447     setOperationAction(ISD::FROUND, MVT::f32, Legal);
448   }
449 
450   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
451   // to speed up scalar BSWAP64.
452   // CTPOP or CTTZ were introduced in P8/P9 respectively
453   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
454   if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
455     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
456   else
457     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
458   if (Subtarget.isISA3_0()) {
459     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
460     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
461   } else {
462     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
463     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
464   }
465 
466   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
467     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
468     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
469   } else {
470     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
471     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
472   }
473 
474   // PowerPC does not have ROTR
475   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
476   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
477 
478   if (!Subtarget.useCRBits()) {
479     // PowerPC does not have Select
480     setOperationAction(ISD::SELECT, MVT::i32, Expand);
481     setOperationAction(ISD::SELECT, MVT::i64, Expand);
482     setOperationAction(ISD::SELECT, MVT::f32, Expand);
483     setOperationAction(ISD::SELECT, MVT::f64, Expand);
484   }
485 
486   // PowerPC wants to turn select_cc of FP into fsel when possible.
487   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
488   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
489 
490   // PowerPC wants to optimize integer setcc a bit
491   if (!Subtarget.useCRBits())
492     setOperationAction(ISD::SETCC, MVT::i32, Custom);
493 
494   if (Subtarget.hasFPU()) {
495     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
496     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
497     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
498 
499     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
500     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
501     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
502   }
503 
504   // PowerPC does not have BRCOND which requires SetCC
505   if (!Subtarget.useCRBits())
506     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
507 
508   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
509 
510   if (Subtarget.hasSPE()) {
511     // SPE has built-in conversions
512     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
513     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
514     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
515     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
516     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
517     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
518 
519     // SPE supports signaling compare of f32/f64.
520     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
521     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
522   } else {
523     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
524     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
525     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
526 
527     // PowerPC does not have [U|S]INT_TO_FP
528     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
529     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
530     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
531     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
532   }
533 
534   if (Subtarget.hasDirectMove() && isPPC64) {
535     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
536     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
537     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
538     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
539     if (TM.Options.UnsafeFPMath) {
540       setOperationAction(ISD::LRINT, MVT::f64, Legal);
541       setOperationAction(ISD::LRINT, MVT::f32, Legal);
542       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
543       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
544       setOperationAction(ISD::LROUND, MVT::f64, Legal);
545       setOperationAction(ISD::LROUND, MVT::f32, Legal);
546       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
547       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
548     }
549   } else {
550     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
551     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
552     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
553     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
554   }
555 
556   // We cannot sextinreg(i1).  Expand to shifts.
557   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
558 
559   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
560   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
561   // support continuation, user-level threading, and etc.. As a result, no
562   // other SjLj exception interfaces are implemented and please don't build
563   // your own exception handling based on them.
564   // LLVM/Clang supports zero-cost DWARF exception handling.
565   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
566   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
567 
568   // We want to legalize GlobalAddress and ConstantPool nodes into the
569   // appropriate instructions to materialize the address.
570   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
571   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
572   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
573   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
574   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
575   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
576   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
578   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
579   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
580 
581   // TRAP is legal.
582   setOperationAction(ISD::TRAP, MVT::Other, Legal);
583 
584   // TRAMPOLINE is custom lowered.
585   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
586   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
587 
588   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
589   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
590 
591   if (Subtarget.is64BitELFABI()) {
592     // VAARG always uses double-word chunks, so promote anything smaller.
593     setOperationAction(ISD::VAARG, MVT::i1, Promote);
594     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
595     setOperationAction(ISD::VAARG, MVT::i8, Promote);
596     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
597     setOperationAction(ISD::VAARG, MVT::i16, Promote);
598     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
599     setOperationAction(ISD::VAARG, MVT::i32, Promote);
600     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
601     setOperationAction(ISD::VAARG, MVT::Other, Expand);
602   } else if (Subtarget.is32BitELFABI()) {
603     // VAARG is custom lowered with the 32-bit SVR4 ABI.
604     setOperationAction(ISD::VAARG, MVT::Other, Custom);
605     setOperationAction(ISD::VAARG, MVT::i64, Custom);
606   } else
607     setOperationAction(ISD::VAARG, MVT::Other, Expand);
608 
609   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
610   if (Subtarget.is32BitELFABI())
611     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
612   else
613     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
614 
615   // Use the default implementation.
616   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
617   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
618   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
619   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
620   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
621   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
622   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
623   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
624   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
625 
626   // We want to custom lower some of our intrinsics.
627   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
628   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
629   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
630   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
631   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
632 
633   // To handle counter-based loop conditions.
634   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
635 
636   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
637   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
638   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
639   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
640 
641   // Comparisons that require checking two conditions.
642   if (Subtarget.hasSPE()) {
643     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
644     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
645     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
646     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
647   }
648   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
649   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
650   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
651   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
652   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
653   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
654   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
655   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
656   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
657   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
658   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
659   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
660 
661   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
662   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
663 
664   if (Subtarget.has64BitSupport()) {
665     // They also have instructions for converting between i64 and fp.
666     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
667     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
668     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
669     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
670     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
671     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
672     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
673     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
674     // This is just the low 32 bits of a (signed) fp->i64 conversion.
675     // We cannot do this with Promote because i64 is not a legal type.
676     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
677     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
678 
679     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
680       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
681       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
682     }
683   } else {
684     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
685     if (Subtarget.hasSPE()) {
686       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
687       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
688     } else {
689       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
690       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
691     }
692   }
693 
694   // With the instructions enabled under FPCVT, we can do everything.
695   if (Subtarget.hasFPCVT()) {
696     if (Subtarget.has64BitSupport()) {
697       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
698       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
699       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
700       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
701       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
702       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
703       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
704       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
705     }
706 
707     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
708     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
709     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
710     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
711     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
712     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
713     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
714     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
715   }
716 
717   if (Subtarget.use64BitRegs()) {
718     // 64-bit PowerPC implementations can support i64 types directly
719     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
720     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
721     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
722     // 64-bit PowerPC wants to expand i128 shifts itself.
723     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
724     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
725     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
726   } else {
727     // 32-bit PowerPC wants to expand i64 shifts itself.
728     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
729     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
730     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
731   }
732 
733   // PowerPC has better expansions for funnel shifts than the generic
734   // TargetLowering::expandFunnelShift.
735   if (Subtarget.has64BitSupport()) {
736     setOperationAction(ISD::FSHL, MVT::i64, Custom);
737     setOperationAction(ISD::FSHR, MVT::i64, Custom);
738   }
739   setOperationAction(ISD::FSHL, MVT::i32, Custom);
740   setOperationAction(ISD::FSHR, MVT::i32, Custom);
741 
742   if (Subtarget.hasVSX()) {
743     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
744     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
745     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
746     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
747   }
748 
749   if (Subtarget.hasAltivec()) {
750     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
751       setOperationAction(ISD::SADDSAT, VT, Legal);
752       setOperationAction(ISD::SSUBSAT, VT, Legal);
753       setOperationAction(ISD::UADDSAT, VT, Legal);
754       setOperationAction(ISD::USUBSAT, VT, Legal);
755     }
756     // First set operation action for all vector types to expand. Then we
757     // will selectively turn on ones that can be effectively codegen'd.
758     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
759       // add/sub are legal for all supported vector VT's.
760       setOperationAction(ISD::ADD, VT, Legal);
761       setOperationAction(ISD::SUB, VT, Legal);
762 
763       // For v2i64, these are only valid with P8Vector. This is corrected after
764       // the loop.
765       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
766         setOperationAction(ISD::SMAX, VT, Legal);
767         setOperationAction(ISD::SMIN, VT, Legal);
768         setOperationAction(ISD::UMAX, VT, Legal);
769         setOperationAction(ISD::UMIN, VT, Legal);
770       }
771       else {
772         setOperationAction(ISD::SMAX, VT, Expand);
773         setOperationAction(ISD::SMIN, VT, Expand);
774         setOperationAction(ISD::UMAX, VT, Expand);
775         setOperationAction(ISD::UMIN, VT, Expand);
776       }
777 
778       if (Subtarget.hasVSX()) {
779         setOperationAction(ISD::FMAXNUM, VT, Legal);
780         setOperationAction(ISD::FMINNUM, VT, Legal);
781       }
782 
783       // Vector instructions introduced in P8
784       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
785         setOperationAction(ISD::CTPOP, VT, Legal);
786         setOperationAction(ISD::CTLZ, VT, Legal);
787       }
788       else {
789         setOperationAction(ISD::CTPOP, VT, Expand);
790         setOperationAction(ISD::CTLZ, VT, Expand);
791       }
792 
793       // Vector instructions introduced in P9
794       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
795         setOperationAction(ISD::CTTZ, VT, Legal);
796       else
797         setOperationAction(ISD::CTTZ, VT, Expand);
798 
799       // We promote all shuffles to v16i8.
800       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
801       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
802 
803       // We promote all non-typed operations to v4i32.
804       setOperationAction(ISD::AND   , VT, Promote);
805       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
806       setOperationAction(ISD::OR    , VT, Promote);
807       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
808       setOperationAction(ISD::XOR   , VT, Promote);
809       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
810       setOperationAction(ISD::LOAD  , VT, Promote);
811       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
812       setOperationAction(ISD::SELECT, VT, Promote);
813       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
814       setOperationAction(ISD::VSELECT, VT, Legal);
815       setOperationAction(ISD::SELECT_CC, VT, Promote);
816       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
817       setOperationAction(ISD::STORE, VT, Promote);
818       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
819 
820       // No other operations are legal.
821       setOperationAction(ISD::MUL , VT, Expand);
822       setOperationAction(ISD::SDIV, VT, Expand);
823       setOperationAction(ISD::SREM, VT, Expand);
824       setOperationAction(ISD::UDIV, VT, Expand);
825       setOperationAction(ISD::UREM, VT, Expand);
826       setOperationAction(ISD::FDIV, VT, Expand);
827       setOperationAction(ISD::FREM, VT, Expand);
828       setOperationAction(ISD::FNEG, VT, Expand);
829       setOperationAction(ISD::FSQRT, VT, Expand);
830       setOperationAction(ISD::FLOG, VT, Expand);
831       setOperationAction(ISD::FLOG10, VT, Expand);
832       setOperationAction(ISD::FLOG2, VT, Expand);
833       setOperationAction(ISD::FEXP, VT, Expand);
834       setOperationAction(ISD::FEXP2, VT, Expand);
835       setOperationAction(ISD::FSIN, VT, Expand);
836       setOperationAction(ISD::FCOS, VT, Expand);
837       setOperationAction(ISD::FABS, VT, Expand);
838       setOperationAction(ISD::FFLOOR, VT, Expand);
839       setOperationAction(ISD::FCEIL,  VT, Expand);
840       setOperationAction(ISD::FTRUNC, VT, Expand);
841       setOperationAction(ISD::FRINT,  VT, Expand);
842       setOperationAction(ISD::FNEARBYINT, VT, Expand);
843       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
844       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
845       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
846       setOperationAction(ISD::MULHU, VT, Expand);
847       setOperationAction(ISD::MULHS, VT, Expand);
848       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
849       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
850       setOperationAction(ISD::UDIVREM, VT, Expand);
851       setOperationAction(ISD::SDIVREM, VT, Expand);
852       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
853       setOperationAction(ISD::FPOW, VT, Expand);
854       setOperationAction(ISD::BSWAP, VT, Expand);
855       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
856       setOperationAction(ISD::ROTL, VT, Expand);
857       setOperationAction(ISD::ROTR, VT, Expand);
858 
859       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
860         setTruncStoreAction(VT, InnerVT, Expand);
861         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
862         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
863         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
864       }
865     }
866     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
867     if (!Subtarget.hasP8Vector()) {
868       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
869       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
870       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
871       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
872     }
873 
874     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
875     // with merges, splats, etc.
876     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
877 
878     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
879     // are cheap, so handle them before they get expanded to scalar.
880     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
881     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
882     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
883     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
884     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
885 
886     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
887     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
888     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
889     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
890     setOperationAction(ISD::SELECT, MVT::v4i32,
891                        Subtarget.useCRBits() ? Legal : Expand);
892     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
893     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
894     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
895     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
896     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
897     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
898     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
899     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
900     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
901     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
902     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
903     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
904     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
905 
906     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
907     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
908     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
909     if (Subtarget.hasAltivec())
910       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
911         setOperationAction(ISD::ROTL, VT, Legal);
912     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
913     if (Subtarget.hasP8Altivec())
914       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
915 
916     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
917     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
918     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
919     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
920 
921     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
922     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
923 
924     if (Subtarget.hasVSX()) {
925       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
926       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
927       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
928     }
929 
930     if (Subtarget.hasP8Altivec())
931       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
932     else
933       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
934 
935     if (Subtarget.isISA3_1()) {
936       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
937       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
938       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
939       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
940       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
941       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
942       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
943       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
944       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
945       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
946       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
947       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
948       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
949       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
950       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
951       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
952       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
953       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
954     }
955 
956     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
957     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
958 
959     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
960     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
961 
962     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
963     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
964     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
965     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
966 
967     // Altivec does not contain unordered floating-point compare instructions
968     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
969     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
970     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
971     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
972 
973     if (Subtarget.hasVSX()) {
974       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
975       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
976       if (Subtarget.hasP8Vector()) {
977         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
978         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
979       }
980       if (Subtarget.hasDirectMove() && isPPC64) {
981         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
982         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
983         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
984         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
985         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
986         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
987         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
988         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
989       }
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
991 
992       // The nearbyint variants are not allowed to raise the inexact exception
993       // so we can only code-gen them with unsafe math.
994       if (TM.Options.UnsafeFPMath) {
995         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
996         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
997       }
998 
999       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1000       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1001       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1002       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1003       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1004       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1005       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1006       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1007 
1008       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1009       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1010       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1011       setOperationAction(ISD::FROUND, MVT::f32, Legal);
1012       setOperationAction(ISD::FRINT, MVT::f32, Legal);
1013 
1014       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1015       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1016 
1017       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1018       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1019 
1020       // Share the Altivec comparison restrictions.
1021       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1022       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1023       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
1024       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1025 
1026       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1027       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1028 
1029       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1030 
1031       if (Subtarget.hasP8Vector())
1032         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1033 
1034       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1035 
1036       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1037       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1038       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1039 
1040       if (Subtarget.hasP8Altivec()) {
1041         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1042         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1043         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1044 
1045         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1046         // SRL, but not for SRA because of the instructions available:
1047         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1048         // doing
1049         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1050         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1051         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1052 
1053         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1054       }
1055       else {
1056         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1057         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1058         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1059 
1060         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1061 
1062         // VSX v2i64 only supports non-arithmetic operations.
1063         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1064         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1065       }
1066 
1067       if (Subtarget.isISA3_1())
1068         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1069       else
1070         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1071 
1072       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1073       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1074       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1075       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1076 
1077       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1078 
1079       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1080       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1081       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1082       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1083       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1084       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1085       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1086       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1087 
1088       // Custom handling for partial vectors of integers converted to
1089       // floating point. We already have optimal handling for v2i32 through
1090       // the DAG combine, so those aren't necessary.
1091       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1092       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1093       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1094       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1095       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1096       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1097       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1098       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1099       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1100       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1101       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1102       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1103       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1104       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1105       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1106       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1107 
1108       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1109       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1110       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1111       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1112       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1113       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1114 
1115       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1116       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1117 
1118       // Handle constrained floating-point operations of vector.
1119       // The predictor is `hasVSX` because altivec instruction has
1120       // no exception but VSX vector instruction has.
1121       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1122       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1123       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1124       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1125       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1126       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1127       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1128       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1129       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1130       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1131       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1132       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1133       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1134 
1135       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1136       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1137       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1138       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1139       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1140       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1141       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1142       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1143       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1144       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1145       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1146       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1147       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1148 
1149       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1150       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1151 
1152       for (MVT FPT : MVT::fp_valuetypes())
1153         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1154 
1155       // Expand the SELECT to SELECT_CC
1156       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1157 
1158       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1159       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1160 
1161       // No implementation for these ops for PowerPC.
1162       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1163       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1164       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1165       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1166       setOperationAction(ISD::FREM, MVT::f128, Expand);
1167     }
1168 
1169     if (Subtarget.hasP8Altivec()) {
1170       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1171       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1172     }
1173 
1174     if (Subtarget.hasP9Vector()) {
1175       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1176       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1177 
1178       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1179       // SRL, but not for SRA because of the instructions available:
1180       // VS{RL} and VS{RL}O.
1181       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1182       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1183       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1184 
1185       setOperationAction(ISD::FADD, MVT::f128, Legal);
1186       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1187       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1188       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1189       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1190 
1191       setOperationAction(ISD::FMA, MVT::f128, Legal);
1192       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1193       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1194       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1195       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1196       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1197       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1198 
1199       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1200       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1201       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1202       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1203       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1204       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1205 
1206       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1207       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1208       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1209 
1210       // Handle constrained floating-point operations of fp128
1211       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1212       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1213       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1214       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1215       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1216       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1217       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1218       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1219       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1220       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1221       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1222       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1223       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1224       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1225       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1226       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1227       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1228       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1229       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1230       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1231     } else if (Subtarget.hasVSX()) {
1232       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1233       setOperationAction(ISD::STORE, MVT::f128, Promote);
1234 
1235       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1236       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1237 
1238       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1239       // fp_to_uint and int_to_fp.
1240       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1241       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1242 
1243       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1244       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1245       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1246       setOperationAction(ISD::FABS, MVT::f128, Expand);
1247       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1248       setOperationAction(ISD::FMA, MVT::f128, Expand);
1249       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1250 
1251       // Expand the fp_extend if the target type is fp128.
1252       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1253       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1254 
1255       // Expand the fp_round if the source type is fp128.
1256       for (MVT VT : {MVT::f32, MVT::f64}) {
1257         setOperationAction(ISD::FP_ROUND, VT, Custom);
1258         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1259       }
1260 
1261       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1262       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1263       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1264       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1265 
1266       // Lower following f128 select_cc pattern:
1267       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1268       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1269 
1270       // We need to handle f128 SELECT_CC with integer result type.
1271       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1272       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1273     }
1274 
1275     if (Subtarget.hasP9Altivec()) {
1276       if (Subtarget.isISA3_1()) {
1277         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
1278         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
1279         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
1280         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
1281       } else {
1282         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1283         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1284       }
1285       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1286       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1287       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1288       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1289       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1290       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1291       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1292     }
1293 
1294     if (Subtarget.hasP10Vector()) {
1295       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1296     }
1297   }
1298 
1299   if (Subtarget.pairedVectorMemops()) {
1300     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1301     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1302     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1303   }
1304   if (Subtarget.hasMMA()) {
1305     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1306     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1307     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1308     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1309   }
1310 
1311   if (Subtarget.has64BitSupport())
1312     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1313 
1314   if (Subtarget.isISA3_1())
1315     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1316 
1317   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1318 
1319   if (!isPPC64) {
1320     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1321     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1322   }
1323 
1324   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1325     setMaxAtomicSizeInBitsSupported(128);
1326     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1327     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1328     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1329   }
1330 
1331   setBooleanContents(ZeroOrOneBooleanContent);
1332 
1333   if (Subtarget.hasAltivec()) {
1334     // Altivec instructions set fields to all zeros or all ones.
1335     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1336   }
1337 
1338   setLibcallName(RTLIB::MULO_I128, nullptr);
1339   if (!isPPC64) {
1340     // These libcalls are not available in 32-bit.
1341     setLibcallName(RTLIB::SHL_I128, nullptr);
1342     setLibcallName(RTLIB::SRL_I128, nullptr);
1343     setLibcallName(RTLIB::SRA_I128, nullptr);
1344     setLibcallName(RTLIB::MUL_I128, nullptr);
1345     setLibcallName(RTLIB::MULO_I64, nullptr);
1346   }
1347 
1348   if (!isPPC64)
1349     setMaxAtomicSizeInBitsSupported(32);
1350 
1351   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1352 
1353   // We have target-specific dag combine patterns for the following nodes:
1354   setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL,
1355                        ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR});
1356   if (Subtarget.hasFPCVT())
1357     setTargetDAGCombine(ISD::UINT_TO_FP);
1358   setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC});
1359   if (Subtarget.useCRBits())
1360     setTargetDAGCombine(ISD::BRCOND);
1361   setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN,
1362                        ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID});
1363 
1364   setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND});
1365 
1366   setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE});
1367 
1368   if (Subtarget.useCRBits()) {
1369     setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC});
1370   }
1371 
1372   if (Subtarget.hasP9Altivec()) {
1373     setTargetDAGCombine({ISD::ABS, ISD::VSELECT});
1374   }
1375 
1376   setLibcallName(RTLIB::LOG_F128, "logf128");
1377   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1378   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1379   setLibcallName(RTLIB::EXP_F128, "expf128");
1380   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1381   setLibcallName(RTLIB::SIN_F128, "sinf128");
1382   setLibcallName(RTLIB::COS_F128, "cosf128");
1383   setLibcallName(RTLIB::POW_F128, "powf128");
1384   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1385   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1386   setLibcallName(RTLIB::REM_F128, "fmodf128");
1387   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1388   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1389   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1390   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1391   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1392   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1393   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1394   setLibcallName(RTLIB::RINT_F128, "rintf128");
1395   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1396   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1397   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1398   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1399 
1400   // With 32 condition bits, we don't need to sink (and duplicate) compares
1401   // aggressively in CodeGenPrep.
1402   if (Subtarget.useCRBits()) {
1403     setHasMultipleConditionRegisters();
1404     setJumpIsExpensive();
1405   }
1406 
1407   setMinFunctionAlignment(Align(4));
1408 
1409   switch (Subtarget.getCPUDirective()) {
1410   default: break;
1411   case PPC::DIR_970:
1412   case PPC::DIR_A2:
1413   case PPC::DIR_E500:
1414   case PPC::DIR_E500mc:
1415   case PPC::DIR_E5500:
1416   case PPC::DIR_PWR4:
1417   case PPC::DIR_PWR5:
1418   case PPC::DIR_PWR5X:
1419   case PPC::DIR_PWR6:
1420   case PPC::DIR_PWR6X:
1421   case PPC::DIR_PWR7:
1422   case PPC::DIR_PWR8:
1423   case PPC::DIR_PWR9:
1424   case PPC::DIR_PWR10:
1425   case PPC::DIR_PWR_FUTURE:
1426     setPrefLoopAlignment(Align(16));
1427     setPrefFunctionAlignment(Align(16));
1428     break;
1429   }
1430 
1431   if (Subtarget.enableMachineScheduler())
1432     setSchedulingPreference(Sched::Source);
1433   else
1434     setSchedulingPreference(Sched::Hybrid);
1435 
1436   computeRegisterProperties(STI.getRegisterInfo());
1437 
1438   // The Freescale cores do better with aggressive inlining of memcpy and
1439   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1440   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1441       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1442     MaxStoresPerMemset = 32;
1443     MaxStoresPerMemsetOptSize = 16;
1444     MaxStoresPerMemcpy = 32;
1445     MaxStoresPerMemcpyOptSize = 8;
1446     MaxStoresPerMemmove = 32;
1447     MaxStoresPerMemmoveOptSize = 8;
1448   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1449     // The A2 also benefits from (very) aggressive inlining of memcpy and
1450     // friends. The overhead of a the function call, even when warm, can be
1451     // over one hundred cycles.
1452     MaxStoresPerMemset = 128;
1453     MaxStoresPerMemcpy = 128;
1454     MaxStoresPerMemmove = 128;
1455     MaxLoadsPerMemcmp = 128;
1456   } else {
1457     MaxLoadsPerMemcmp = 8;
1458     MaxLoadsPerMemcmpOptSize = 4;
1459   }
1460 
1461   IsStrictFPEnabled = true;
1462 
1463   // Let the subtarget (CPU) decide if a predictable select is more expensive
1464   // than the corresponding branch. This information is used in CGP to decide
1465   // when to convert selects into branches.
1466   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1467 }
1468 
1469 // *********************************** NOTE ************************************
1470 // For selecting load and store instructions, the addressing modes are defined
1471 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1472 // patterns to match the load the store instructions.
1473 //
1474 // The TD definitions for the addressing modes correspond to their respective
1475 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1476 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1477 // address mode flags of a particular node. Afterwards, the computed address
1478 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1479 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1480 // accordingly, based on the preferred addressing mode.
1481 //
1482 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1483 // MemOpFlags contains all the possible flags that can be used to compute the
1484 // optimal addressing mode for load and store instructions.
1485 // AddrMode contains all the possible load and store addressing modes available
1486 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1487 //
1488 // When adding new load and store instructions, it is possible that new address
1489 // flags may need to be added into MemOpFlags, and a new addressing mode will
1490 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1491 // of the minimal and main distinguishing address flags for the new load/store
1492 // instructions) will need to be added into initializeAddrModeMap() below.
1493 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1494 // need to be updated to account for selecting the optimal addressing mode.
1495 // *****************************************************************************
1496 /// Initialize the map that relates the different addressing modes of the load
1497 /// and store instructions to a set of flags. This ensures the load/store
1498 /// instruction is correctly matched during instruction selection.
1499 void PPCTargetLowering::initializeAddrModeMap() {
1500   AddrModesMap[PPC::AM_DForm] = {
1501       // LWZ, STW
1502       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1503       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1504       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1505       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1506       // LBZ, LHZ, STB, STH
1507       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1508       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1509       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1510       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1511       // LHA
1512       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1513       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1514       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1515       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1516       // LFS, LFD, STFS, STFD
1517       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1518       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1519       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1520       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1521   };
1522   AddrModesMap[PPC::AM_DSForm] = {
1523       // LWA
1524       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1525       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1526       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1527       // LD, STD
1528       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1529       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1530       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1531       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1532       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1533       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1534       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1535   };
1536   AddrModesMap[PPC::AM_DQForm] = {
1537       // LXV, STXV
1538       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1539       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1540       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1541   };
1542   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1543                                        PPC::MOF_SubtargetP10};
1544   // TODO: Add mapping for quadword load/store.
1545 }
1546 
1547 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1548 /// the desired ByVal argument alignment.
1549 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1550   if (MaxAlign == MaxMaxAlign)
1551     return;
1552   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1553     if (MaxMaxAlign >= 32 &&
1554         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1555       MaxAlign = Align(32);
1556     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1557              MaxAlign < 16)
1558       MaxAlign = Align(16);
1559   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1560     Align EltAlign;
1561     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1562     if (EltAlign > MaxAlign)
1563       MaxAlign = EltAlign;
1564   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1565     for (auto *EltTy : STy->elements()) {
1566       Align EltAlign;
1567       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1568       if (EltAlign > MaxAlign)
1569         MaxAlign = EltAlign;
1570       if (MaxAlign == MaxMaxAlign)
1571         break;
1572     }
1573   }
1574 }
1575 
1576 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1577 /// function arguments in the caller parameter area.
1578 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1579                                                   const DataLayout &DL) const {
1580   // 16byte and wider vectors are passed on 16byte boundary.
1581   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1582   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1583   if (Subtarget.hasAltivec())
1584     getMaxByValAlign(Ty, Alignment, Align(16));
1585   return Alignment.value();
1586 }
1587 
1588 bool PPCTargetLowering::useSoftFloat() const {
1589   return Subtarget.useSoftFloat();
1590 }
1591 
1592 bool PPCTargetLowering::hasSPE() const {
1593   return Subtarget.hasSPE();
1594 }
1595 
1596 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1597   return VT.isScalarInteger();
1598 }
1599 
1600 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1601   switch ((PPCISD::NodeType)Opcode) {
1602   case PPCISD::FIRST_NUMBER:    break;
1603   case PPCISD::FSEL:            return "PPCISD::FSEL";
1604   case PPCISD::XSMAXC:          return "PPCISD::XSMAXC";
1605   case PPCISD::XSMINC:          return "PPCISD::XSMINC";
1606   case PPCISD::FCFID:           return "PPCISD::FCFID";
1607   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1608   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1609   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1610   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1611   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1612   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1613   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1614   case PPCISD::FP_TO_UINT_IN_VSR:
1615                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1616   case PPCISD::FP_TO_SINT_IN_VSR:
1617                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1618   case PPCISD::FRE:             return "PPCISD::FRE";
1619   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1620   case PPCISD::FTSQRT:
1621     return "PPCISD::FTSQRT";
1622   case PPCISD::FSQRT:
1623     return "PPCISD::FSQRT";
1624   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1625   case PPCISD::VPERM:           return "PPCISD::VPERM";
1626   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1627   case PPCISD::XXSPLTI_SP_TO_DP:
1628     return "PPCISD::XXSPLTI_SP_TO_DP";
1629   case PPCISD::XXSPLTI32DX:
1630     return "PPCISD::XXSPLTI32DX";
1631   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1632   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1633   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1634   case PPCISD::CMPB:            return "PPCISD::CMPB";
1635   case PPCISD::Hi:              return "PPCISD::Hi";
1636   case PPCISD::Lo:              return "PPCISD::Lo";
1637   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1638   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1639   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1640   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1641   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1642   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1643   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1644   case PPCISD::SRL:             return "PPCISD::SRL";
1645   case PPCISD::SRA:             return "PPCISD::SRA";
1646   case PPCISD::SHL:             return "PPCISD::SHL";
1647   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1648   case PPCISD::CALL:            return "PPCISD::CALL";
1649   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1650   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1651   case PPCISD::CALL_RM:
1652     return "PPCISD::CALL_RM";
1653   case PPCISD::CALL_NOP_RM:
1654     return "PPCISD::CALL_NOP_RM";
1655   case PPCISD::CALL_NOTOC_RM:
1656     return "PPCISD::CALL_NOTOC_RM";
1657   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1658   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1659   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1660   case PPCISD::BCTRL_RM:
1661     return "PPCISD::BCTRL_RM";
1662   case PPCISD::BCTRL_LOAD_TOC_RM:
1663     return "PPCISD::BCTRL_LOAD_TOC_RM";
1664   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1665   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1666   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1667   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1668   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1669   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1670   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1671   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1672   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1673   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1674   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1675     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1676   case PPCISD::ANDI_rec_1_EQ_BIT:
1677     return "PPCISD::ANDI_rec_1_EQ_BIT";
1678   case PPCISD::ANDI_rec_1_GT_BIT:
1679     return "PPCISD::ANDI_rec_1_GT_BIT";
1680   case PPCISD::VCMP:            return "PPCISD::VCMP";
1681   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1682   case PPCISD::LBRX:            return "PPCISD::LBRX";
1683   case PPCISD::STBRX:           return "PPCISD::STBRX";
1684   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1685   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1686   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1687   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1688   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1689   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1690   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1691   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1692   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1693   case PPCISD::ST_VSR_SCAL_INT:
1694                                 return "PPCISD::ST_VSR_SCAL_INT";
1695   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1696   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1697   case PPCISD::BDZ:             return "PPCISD::BDZ";
1698   case PPCISD::MFFS:            return "PPCISD::MFFS";
1699   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1700   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1701   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1702   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1703   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1704   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1705   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1706   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1707   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1708   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1709   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1710   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1711   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1712   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1713   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1714   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1715   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1716   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1717   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1718   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1719   case PPCISD::PADDI_DTPREL:
1720     return "PPCISD::PADDI_DTPREL";
1721   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1722   case PPCISD::SC:              return "PPCISD::SC";
1723   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1724   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1725   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1726   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1727   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1728   case PPCISD::VABSD:           return "PPCISD::VABSD";
1729   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1730   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1731   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1732   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1733   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1734   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1735   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1736   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1737     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1738   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1739     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1740   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1741   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1742   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1743   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1744   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1745   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1746   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1747   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1748   case PPCISD::STRICT_FADDRTZ:
1749     return "PPCISD::STRICT_FADDRTZ";
1750   case PPCISD::STRICT_FCTIDZ:
1751     return "PPCISD::STRICT_FCTIDZ";
1752   case PPCISD::STRICT_FCTIWZ:
1753     return "PPCISD::STRICT_FCTIWZ";
1754   case PPCISD::STRICT_FCTIDUZ:
1755     return "PPCISD::STRICT_FCTIDUZ";
1756   case PPCISD::STRICT_FCTIWUZ:
1757     return "PPCISD::STRICT_FCTIWUZ";
1758   case PPCISD::STRICT_FCFID:
1759     return "PPCISD::STRICT_FCFID";
1760   case PPCISD::STRICT_FCFIDU:
1761     return "PPCISD::STRICT_FCFIDU";
1762   case PPCISD::STRICT_FCFIDS:
1763     return "PPCISD::STRICT_FCFIDS";
1764   case PPCISD::STRICT_FCFIDUS:
1765     return "PPCISD::STRICT_FCFIDUS";
1766   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1767   }
1768   return nullptr;
1769 }
1770 
1771 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1772                                           EVT VT) const {
1773   if (!VT.isVector())
1774     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1775 
1776   return VT.changeVectorElementTypeToInteger();
1777 }
1778 
1779 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1780   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1781   return true;
1782 }
1783 
1784 //===----------------------------------------------------------------------===//
1785 // Node matching predicates, for use by the tblgen matching code.
1786 //===----------------------------------------------------------------------===//
1787 
1788 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1789 static bool isFloatingPointZero(SDValue Op) {
1790   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1791     return CFP->getValueAPF().isZero();
1792   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1793     // Maybe this has already been legalized into the constant pool?
1794     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1795       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1796         return CFP->getValueAPF().isZero();
1797   }
1798   return false;
1799 }
1800 
1801 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1802 /// true if Op is undef or if it matches the specified value.
1803 static bool isConstantOrUndef(int Op, int Val) {
1804   return Op < 0 || Op == Val;
1805 }
1806 
1807 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1808 /// VPKUHUM instruction.
1809 /// The ShuffleKind distinguishes between big-endian operations with
1810 /// two different inputs (0), either-endian operations with two identical
1811 /// inputs (1), and little-endian operations with two different inputs (2).
1812 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1813 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1814                                SelectionDAG &DAG) {
1815   bool IsLE = DAG.getDataLayout().isLittleEndian();
1816   if (ShuffleKind == 0) {
1817     if (IsLE)
1818       return false;
1819     for (unsigned i = 0; i != 16; ++i)
1820       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1821         return false;
1822   } else if (ShuffleKind == 2) {
1823     if (!IsLE)
1824       return false;
1825     for (unsigned i = 0; i != 16; ++i)
1826       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1827         return false;
1828   } else if (ShuffleKind == 1) {
1829     unsigned j = IsLE ? 0 : 1;
1830     for (unsigned i = 0; i != 8; ++i)
1831       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1832           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1833         return false;
1834   }
1835   return true;
1836 }
1837 
1838 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1839 /// VPKUWUM instruction.
1840 /// The ShuffleKind distinguishes between big-endian operations with
1841 /// two different inputs (0), either-endian operations with two identical
1842 /// inputs (1), and little-endian operations with two different inputs (2).
1843 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1844 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1845                                SelectionDAG &DAG) {
1846   bool IsLE = DAG.getDataLayout().isLittleEndian();
1847   if (ShuffleKind == 0) {
1848     if (IsLE)
1849       return false;
1850     for (unsigned i = 0; i != 16; i += 2)
1851       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1852           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1853         return false;
1854   } else if (ShuffleKind == 2) {
1855     if (!IsLE)
1856       return false;
1857     for (unsigned i = 0; i != 16; i += 2)
1858       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1859           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1860         return false;
1861   } else if (ShuffleKind == 1) {
1862     unsigned j = IsLE ? 0 : 2;
1863     for (unsigned i = 0; i != 8; i += 2)
1864       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1865           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1866           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1867           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1868         return false;
1869   }
1870   return true;
1871 }
1872 
1873 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1874 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1875 /// current subtarget.
1876 ///
1877 /// The ShuffleKind distinguishes between big-endian operations with
1878 /// two different inputs (0), either-endian operations with two identical
1879 /// inputs (1), and little-endian operations with two different inputs (2).
1880 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1881 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1882                                SelectionDAG &DAG) {
1883   const PPCSubtarget& Subtarget =
1884       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1885   if (!Subtarget.hasP8Vector())
1886     return false;
1887 
1888   bool IsLE = DAG.getDataLayout().isLittleEndian();
1889   if (ShuffleKind == 0) {
1890     if (IsLE)
1891       return false;
1892     for (unsigned i = 0; i != 16; i += 4)
1893       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1894           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1895           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1896           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1897         return false;
1898   } else if (ShuffleKind == 2) {
1899     if (!IsLE)
1900       return false;
1901     for (unsigned i = 0; i != 16; i += 4)
1902       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1903           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1904           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1905           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1906         return false;
1907   } else if (ShuffleKind == 1) {
1908     unsigned j = IsLE ? 0 : 4;
1909     for (unsigned i = 0; i != 8; i += 4)
1910       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1911           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1912           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1913           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1914           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1915           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1916           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1917           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1918         return false;
1919   }
1920   return true;
1921 }
1922 
1923 /// isVMerge - Common function, used to match vmrg* shuffles.
1924 ///
1925 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1926                      unsigned LHSStart, unsigned RHSStart) {
1927   if (N->getValueType(0) != MVT::v16i8)
1928     return false;
1929   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1930          "Unsupported merge size!");
1931 
1932   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1933     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1934       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1935                              LHSStart+j+i*UnitSize) ||
1936           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1937                              RHSStart+j+i*UnitSize))
1938         return false;
1939     }
1940   return true;
1941 }
1942 
1943 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1944 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1945 /// The ShuffleKind distinguishes between big-endian merges with two
1946 /// different inputs (0), either-endian merges with two identical inputs (1),
1947 /// and little-endian merges with two different inputs (2).  For the latter,
1948 /// the input operands are swapped (see PPCInstrAltivec.td).
1949 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1950                              unsigned ShuffleKind, SelectionDAG &DAG) {
1951   if (DAG.getDataLayout().isLittleEndian()) {
1952     if (ShuffleKind == 1) // unary
1953       return isVMerge(N, UnitSize, 0, 0);
1954     else if (ShuffleKind == 2) // swapped
1955       return isVMerge(N, UnitSize, 0, 16);
1956     else
1957       return false;
1958   } else {
1959     if (ShuffleKind == 1) // unary
1960       return isVMerge(N, UnitSize, 8, 8);
1961     else if (ShuffleKind == 0) // normal
1962       return isVMerge(N, UnitSize, 8, 24);
1963     else
1964       return false;
1965   }
1966 }
1967 
1968 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1969 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1970 /// The ShuffleKind distinguishes between big-endian merges with two
1971 /// different inputs (0), either-endian merges with two identical inputs (1),
1972 /// and little-endian merges with two different inputs (2).  For the latter,
1973 /// the input operands are swapped (see PPCInstrAltivec.td).
1974 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1975                              unsigned ShuffleKind, SelectionDAG &DAG) {
1976   if (DAG.getDataLayout().isLittleEndian()) {
1977     if (ShuffleKind == 1) // unary
1978       return isVMerge(N, UnitSize, 8, 8);
1979     else if (ShuffleKind == 2) // swapped
1980       return isVMerge(N, UnitSize, 8, 24);
1981     else
1982       return false;
1983   } else {
1984     if (ShuffleKind == 1) // unary
1985       return isVMerge(N, UnitSize, 0, 0);
1986     else if (ShuffleKind == 0) // normal
1987       return isVMerge(N, UnitSize, 0, 16);
1988     else
1989       return false;
1990   }
1991 }
1992 
1993 /**
1994  * Common function used to match vmrgew and vmrgow shuffles
1995  *
1996  * The indexOffset determines whether to look for even or odd words in
1997  * the shuffle mask. This is based on the of the endianness of the target
1998  * machine.
1999  *   - Little Endian:
2000  *     - Use offset of 0 to check for odd elements
2001  *     - Use offset of 4 to check for even elements
2002  *   - Big Endian:
2003  *     - Use offset of 0 to check for even elements
2004  *     - Use offset of 4 to check for odd elements
2005  * A detailed description of the vector element ordering for little endian and
2006  * big endian can be found at
2007  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2008  * Targeting your applications - what little endian and big endian IBM XL C/C++
2009  * compiler differences mean to you
2010  *
2011  * The mask to the shuffle vector instruction specifies the indices of the
2012  * elements from the two input vectors to place in the result. The elements are
2013  * numbered in array-access order, starting with the first vector. These vectors
2014  * are always of type v16i8, thus each vector will contain 16 elements of size
2015  * 8. More info on the shuffle vector can be found in the
2016  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2017  * Language Reference.
2018  *
2019  * The RHSStartValue indicates whether the same input vectors are used (unary)
2020  * or two different input vectors are used, based on the following:
2021  *   - If the instruction uses the same vector for both inputs, the range of the
2022  *     indices will be 0 to 15. In this case, the RHSStart value passed should
2023  *     be 0.
2024  *   - If the instruction has two different vectors then the range of the
2025  *     indices will be 0 to 31. In this case, the RHSStart value passed should
2026  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
2027  *     to 31 specify elements in the second vector).
2028  *
2029  * \param[in] N The shuffle vector SD Node to analyze
2030  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2031  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2032  * vector to the shuffle_vector instruction
2033  * \return true iff this shuffle vector represents an even or odd word merge
2034  */
2035 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2036                      unsigned RHSStartValue) {
2037   if (N->getValueType(0) != MVT::v16i8)
2038     return false;
2039 
2040   for (unsigned i = 0; i < 2; ++i)
2041     for (unsigned j = 0; j < 4; ++j)
2042       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2043                              i*RHSStartValue+j+IndexOffset) ||
2044           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2045                              i*RHSStartValue+j+IndexOffset+8))
2046         return false;
2047   return true;
2048 }
2049 
2050 /**
2051  * Determine if the specified shuffle mask is suitable for the vmrgew or
2052  * vmrgow instructions.
2053  *
2054  * \param[in] N The shuffle vector SD Node to analyze
2055  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2056  * \param[in] ShuffleKind Identify the type of merge:
2057  *   - 0 = big-endian merge with two different inputs;
2058  *   - 1 = either-endian merge with two identical inputs;
2059  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2060  *     little-endian merges).
2061  * \param[in] DAG The current SelectionDAG
2062  * \return true iff this shuffle mask
2063  */
2064 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2065                               unsigned ShuffleKind, SelectionDAG &DAG) {
2066   if (DAG.getDataLayout().isLittleEndian()) {
2067     unsigned indexOffset = CheckEven ? 4 : 0;
2068     if (ShuffleKind == 1) // Unary
2069       return isVMerge(N, indexOffset, 0);
2070     else if (ShuffleKind == 2) // swapped
2071       return isVMerge(N, indexOffset, 16);
2072     else
2073       return false;
2074   }
2075   else {
2076     unsigned indexOffset = CheckEven ? 0 : 4;
2077     if (ShuffleKind == 1) // Unary
2078       return isVMerge(N, indexOffset, 0);
2079     else if (ShuffleKind == 0) // Normal
2080       return isVMerge(N, indexOffset, 16);
2081     else
2082       return false;
2083   }
2084   return false;
2085 }
2086 
2087 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2088 /// amount, otherwise return -1.
2089 /// The ShuffleKind distinguishes between big-endian operations with two
2090 /// different inputs (0), either-endian operations with two identical inputs
2091 /// (1), and little-endian operations with two different inputs (2).  For the
2092 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2093 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2094                              SelectionDAG &DAG) {
2095   if (N->getValueType(0) != MVT::v16i8)
2096     return -1;
2097 
2098   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2099 
2100   // Find the first non-undef value in the shuffle mask.
2101   unsigned i;
2102   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2103     /*search*/;
2104 
2105   if (i == 16) return -1;  // all undef.
2106 
2107   // Otherwise, check to see if the rest of the elements are consecutively
2108   // numbered from this value.
2109   unsigned ShiftAmt = SVOp->getMaskElt(i);
2110   if (ShiftAmt < i) return -1;
2111 
2112   ShiftAmt -= i;
2113   bool isLE = DAG.getDataLayout().isLittleEndian();
2114 
2115   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2116     // Check the rest of the elements to see if they are consecutive.
2117     for (++i; i != 16; ++i)
2118       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2119         return -1;
2120   } else if (ShuffleKind == 1) {
2121     // Check the rest of the elements to see if they are consecutive.
2122     for (++i; i != 16; ++i)
2123       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2124         return -1;
2125   } else
2126     return -1;
2127 
2128   if (isLE)
2129     ShiftAmt = 16 - ShiftAmt;
2130 
2131   return ShiftAmt;
2132 }
2133 
2134 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2135 /// specifies a splat of a single element that is suitable for input to
2136 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2137 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2138   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2139          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2140 
2141   // The consecutive indices need to specify an element, not part of two
2142   // different elements.  So abandon ship early if this isn't the case.
2143   if (N->getMaskElt(0) % EltSize != 0)
2144     return false;
2145 
2146   // This is a splat operation if each element of the permute is the same, and
2147   // if the value doesn't reference the second vector.
2148   unsigned ElementBase = N->getMaskElt(0);
2149 
2150   // FIXME: Handle UNDEF elements too!
2151   if (ElementBase >= 16)
2152     return false;
2153 
2154   // Check that the indices are consecutive, in the case of a multi-byte element
2155   // splatted with a v16i8 mask.
2156   for (unsigned i = 1; i != EltSize; ++i)
2157     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2158       return false;
2159 
2160   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2161     if (N->getMaskElt(i) < 0) continue;
2162     for (unsigned j = 0; j != EltSize; ++j)
2163       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2164         return false;
2165   }
2166   return true;
2167 }
2168 
2169 /// Check that the mask is shuffling N byte elements. Within each N byte
2170 /// element of the mask, the indices could be either in increasing or
2171 /// decreasing order as long as they are consecutive.
2172 /// \param[in] N the shuffle vector SD Node to analyze
2173 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2174 /// Word/DoubleWord/QuadWord).
2175 /// \param[in] StepLen the delta indices number among the N byte element, if
2176 /// the mask is in increasing/decreasing order then it is 1/-1.
2177 /// \return true iff the mask is shuffling N byte elements.
2178 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2179                                    int StepLen) {
2180   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2181          "Unexpected element width.");
2182   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2183 
2184   unsigned NumOfElem = 16 / Width;
2185   unsigned MaskVal[16]; //  Width is never greater than 16
2186   for (unsigned i = 0; i < NumOfElem; ++i) {
2187     MaskVal[0] = N->getMaskElt(i * Width);
2188     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2189       return false;
2190     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2191       return false;
2192     }
2193 
2194     for (unsigned int j = 1; j < Width; ++j) {
2195       MaskVal[j] = N->getMaskElt(i * Width + j);
2196       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2197         return false;
2198       }
2199     }
2200   }
2201 
2202   return true;
2203 }
2204 
2205 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2206                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2207   if (!isNByteElemShuffleMask(N, 4, 1))
2208     return false;
2209 
2210   // Now we look at mask elements 0,4,8,12
2211   unsigned M0 = N->getMaskElt(0) / 4;
2212   unsigned M1 = N->getMaskElt(4) / 4;
2213   unsigned M2 = N->getMaskElt(8) / 4;
2214   unsigned M3 = N->getMaskElt(12) / 4;
2215   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2216   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2217 
2218   // Below, let H and L be arbitrary elements of the shuffle mask
2219   // where H is in the range [4,7] and L is in the range [0,3].
2220   // H, 1, 2, 3 or L, 5, 6, 7
2221   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2222       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2223     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2224     InsertAtByte = IsLE ? 12 : 0;
2225     Swap = M0 < 4;
2226     return true;
2227   }
2228   // 0, H, 2, 3 or 4, L, 6, 7
2229   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2230       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2231     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2232     InsertAtByte = IsLE ? 8 : 4;
2233     Swap = M1 < 4;
2234     return true;
2235   }
2236   // 0, 1, H, 3 or 4, 5, L, 7
2237   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2238       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2239     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2240     InsertAtByte = IsLE ? 4 : 8;
2241     Swap = M2 < 4;
2242     return true;
2243   }
2244   // 0, 1, 2, H or 4, 5, 6, L
2245   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2246       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2247     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2248     InsertAtByte = IsLE ? 0 : 12;
2249     Swap = M3 < 4;
2250     return true;
2251   }
2252 
2253   // If both vector operands for the shuffle are the same vector, the mask will
2254   // contain only elements from the first one and the second one will be undef.
2255   if (N->getOperand(1).isUndef()) {
2256     ShiftElts = 0;
2257     Swap = true;
2258     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2259     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2260       InsertAtByte = IsLE ? 12 : 0;
2261       return true;
2262     }
2263     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2264       InsertAtByte = IsLE ? 8 : 4;
2265       return true;
2266     }
2267     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2268       InsertAtByte = IsLE ? 4 : 8;
2269       return true;
2270     }
2271     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2272       InsertAtByte = IsLE ? 0 : 12;
2273       return true;
2274     }
2275   }
2276 
2277   return false;
2278 }
2279 
2280 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2281                                bool &Swap, bool IsLE) {
2282   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2283   // Ensure each byte index of the word is consecutive.
2284   if (!isNByteElemShuffleMask(N, 4, 1))
2285     return false;
2286 
2287   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2288   unsigned M0 = N->getMaskElt(0) / 4;
2289   unsigned M1 = N->getMaskElt(4) / 4;
2290   unsigned M2 = N->getMaskElt(8) / 4;
2291   unsigned M3 = N->getMaskElt(12) / 4;
2292 
2293   // If both vector operands for the shuffle are the same vector, the mask will
2294   // contain only elements from the first one and the second one will be undef.
2295   if (N->getOperand(1).isUndef()) {
2296     assert(M0 < 4 && "Indexing into an undef vector?");
2297     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2298       return false;
2299 
2300     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2301     Swap = false;
2302     return true;
2303   }
2304 
2305   // Ensure each word index of the ShuffleVector Mask is consecutive.
2306   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2307     return false;
2308 
2309   if (IsLE) {
2310     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2311       // Input vectors don't need to be swapped if the leading element
2312       // of the result is one of the 3 left elements of the second vector
2313       // (or if there is no shift to be done at all).
2314       Swap = false;
2315       ShiftElts = (8 - M0) % 8;
2316     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2317       // Input vectors need to be swapped if the leading element
2318       // of the result is one of the 3 left elements of the first vector
2319       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2320       Swap = true;
2321       ShiftElts = (4 - M0) % 4;
2322     }
2323 
2324     return true;
2325   } else {                                          // BE
2326     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2327       // Input vectors don't need to be swapped if the leading element
2328       // of the result is one of the 4 elements of the first vector.
2329       Swap = false;
2330       ShiftElts = M0;
2331     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2332       // Input vectors need to be swapped if the leading element
2333       // of the result is one of the 4 elements of the right vector.
2334       Swap = true;
2335       ShiftElts = M0 - 4;
2336     }
2337 
2338     return true;
2339   }
2340 }
2341 
2342 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2343   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2344 
2345   if (!isNByteElemShuffleMask(N, Width, -1))
2346     return false;
2347 
2348   for (int i = 0; i < 16; i += Width)
2349     if (N->getMaskElt(i) != i + Width - 1)
2350       return false;
2351 
2352   return true;
2353 }
2354 
2355 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2356   return isXXBRShuffleMaskHelper(N, 2);
2357 }
2358 
2359 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2360   return isXXBRShuffleMaskHelper(N, 4);
2361 }
2362 
2363 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2364   return isXXBRShuffleMaskHelper(N, 8);
2365 }
2366 
2367 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2368   return isXXBRShuffleMaskHelper(N, 16);
2369 }
2370 
2371 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2372 /// if the inputs to the instruction should be swapped and set \p DM to the
2373 /// value for the immediate.
2374 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2375 /// AND element 0 of the result comes from the first input (LE) or second input
2376 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2377 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2378 /// mask.
2379 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2380                                bool &Swap, bool IsLE) {
2381   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2382 
2383   // Ensure each byte index of the double word is consecutive.
2384   if (!isNByteElemShuffleMask(N, 8, 1))
2385     return false;
2386 
2387   unsigned M0 = N->getMaskElt(0) / 8;
2388   unsigned M1 = N->getMaskElt(8) / 8;
2389   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2390 
2391   // If both vector operands for the shuffle are the same vector, the mask will
2392   // contain only elements from the first one and the second one will be undef.
2393   if (N->getOperand(1).isUndef()) {
2394     if ((M0 | M1) < 2) {
2395       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2396       Swap = false;
2397       return true;
2398     } else
2399       return false;
2400   }
2401 
2402   if (IsLE) {
2403     if (M0 > 1 && M1 < 2) {
2404       Swap = false;
2405     } else if (M0 < 2 && M1 > 1) {
2406       M0 = (M0 + 2) % 4;
2407       M1 = (M1 + 2) % 4;
2408       Swap = true;
2409     } else
2410       return false;
2411 
2412     // Note: if control flow comes here that means Swap is already set above
2413     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2414     return true;
2415   } else { // BE
2416     if (M0 < 2 && M1 > 1) {
2417       Swap = false;
2418     } else if (M0 > 1 && M1 < 2) {
2419       M0 = (M0 + 2) % 4;
2420       M1 = (M1 + 2) % 4;
2421       Swap = true;
2422     } else
2423       return false;
2424 
2425     // Note: if control flow comes here that means Swap is already set above
2426     DM = (M0 << 1) + (M1 & 1);
2427     return true;
2428   }
2429 }
2430 
2431 
2432 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2433 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2434 /// elements are counted from the left of the vector register).
2435 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2436                                          SelectionDAG &DAG) {
2437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2438   assert(isSplatShuffleMask(SVOp, EltSize));
2439   if (DAG.getDataLayout().isLittleEndian())
2440     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2441   else
2442     return SVOp->getMaskElt(0) / EltSize;
2443 }
2444 
2445 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2446 /// by using a vspltis[bhw] instruction of the specified element size, return
2447 /// the constant being splatted.  The ByteSize field indicates the number of
2448 /// bytes of each element [124] -> [bhw].
2449 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2450   SDValue OpVal;
2451 
2452   // If ByteSize of the splat is bigger than the element size of the
2453   // build_vector, then we have a case where we are checking for a splat where
2454   // multiple elements of the buildvector are folded together into a single
2455   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2456   unsigned EltSize = 16/N->getNumOperands();
2457   if (EltSize < ByteSize) {
2458     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2459     SDValue UniquedVals[4];
2460     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2461 
2462     // See if all of the elements in the buildvector agree across.
2463     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2464       if (N->getOperand(i).isUndef()) continue;
2465       // If the element isn't a constant, bail fully out.
2466       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2467 
2468       if (!UniquedVals[i&(Multiple-1)].getNode())
2469         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2470       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2471         return SDValue();  // no match.
2472     }
2473 
2474     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2475     // either constant or undef values that are identical for each chunk.  See
2476     // if these chunks can form into a larger vspltis*.
2477 
2478     // Check to see if all of the leading entries are either 0 or -1.  If
2479     // neither, then this won't fit into the immediate field.
2480     bool LeadingZero = true;
2481     bool LeadingOnes = true;
2482     for (unsigned i = 0; i != Multiple-1; ++i) {
2483       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2484 
2485       LeadingZero &= isNullConstant(UniquedVals[i]);
2486       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2487     }
2488     // Finally, check the least significant entry.
2489     if (LeadingZero) {
2490       if (!UniquedVals[Multiple-1].getNode())
2491         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2492       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2493       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2494         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2495     }
2496     if (LeadingOnes) {
2497       if (!UniquedVals[Multiple-1].getNode())
2498         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2499       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2500       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2501         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2502     }
2503 
2504     return SDValue();
2505   }
2506 
2507   // Check to see if this buildvec has a single non-undef value in its elements.
2508   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2509     if (N->getOperand(i).isUndef()) continue;
2510     if (!OpVal.getNode())
2511       OpVal = N->getOperand(i);
2512     else if (OpVal != N->getOperand(i))
2513       return SDValue();
2514   }
2515 
2516   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2517 
2518   unsigned ValSizeInBytes = EltSize;
2519   uint64_t Value = 0;
2520   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2521     Value = CN->getZExtValue();
2522   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2523     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2524     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2525   }
2526 
2527   // If the splat value is larger than the element value, then we can never do
2528   // this splat.  The only case that we could fit the replicated bits into our
2529   // immediate field for would be zero, and we prefer to use vxor for it.
2530   if (ValSizeInBytes < ByteSize) return SDValue();
2531 
2532   // If the element value is larger than the splat value, check if it consists
2533   // of a repeated bit pattern of size ByteSize.
2534   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2535     return SDValue();
2536 
2537   // Properly sign extend the value.
2538   int MaskVal = SignExtend32(Value, ByteSize * 8);
2539 
2540   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2541   if (MaskVal == 0) return SDValue();
2542 
2543   // Finally, if this value fits in a 5 bit sext field, return it
2544   if (SignExtend32<5>(MaskVal) == MaskVal)
2545     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2546   return SDValue();
2547 }
2548 
2549 //===----------------------------------------------------------------------===//
2550 //  Addressing Mode Selection
2551 //===----------------------------------------------------------------------===//
2552 
2553 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2554 /// or 64-bit immediate, and if the value can be accurately represented as a
2555 /// sign extension from a 16-bit value.  If so, this returns true and the
2556 /// immediate.
2557 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2558   if (!isa<ConstantSDNode>(N))
2559     return false;
2560 
2561   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2562   if (N->getValueType(0) == MVT::i32)
2563     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2564   else
2565     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2566 }
2567 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2568   return isIntS16Immediate(Op.getNode(), Imm);
2569 }
2570 
2571 /// Used when computing address flags for selecting loads and stores.
2572 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2573 /// An OR of two provably disjoint values is equivalent to an ADD.
2574 /// Most PPC load/store instructions compute the effective address as a sum,
2575 /// so doing this conversion is useful.
2576 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2577   if (N.getOpcode() != ISD::OR)
2578     return false;
2579   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2580   if (!LHSKnown.Zero.getBoolValue())
2581     return false;
2582   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2583   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2584 }
2585 
2586 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2587 /// be represented as an indexed [r+r] operation.
2588 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2589                                                SDValue &Index,
2590                                                SelectionDAG &DAG) const {
2591   for (SDNode *U : N->uses()) {
2592     if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2593       if (Memop->getMemoryVT() == MVT::f64) {
2594           Base = N.getOperand(0);
2595           Index = N.getOperand(1);
2596           return true;
2597       }
2598     }
2599   }
2600   return false;
2601 }
2602 
2603 /// isIntS34Immediate - This method tests if value of node given can be
2604 /// accurately represented as a sign extension from a 34-bit value.  If so,
2605 /// this returns true and the immediate.
2606 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2607   if (!isa<ConstantSDNode>(N))
2608     return false;
2609 
2610   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2611   return isInt<34>(Imm);
2612 }
2613 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2614   return isIntS34Immediate(Op.getNode(), Imm);
2615 }
2616 
2617 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2618 /// can be represented as an indexed [r+r] operation.  Returns false if it
2619 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2620 /// non-zero and N can be represented by a base register plus a signed 16-bit
2621 /// displacement, make a more precise judgement by checking (displacement % \p
2622 /// EncodingAlignment).
2623 bool PPCTargetLowering::SelectAddressRegReg(
2624     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2625     MaybeAlign EncodingAlignment) const {
2626   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2627   // a [pc+imm].
2628   if (SelectAddressPCRel(N, Base))
2629     return false;
2630 
2631   int16_t Imm = 0;
2632   if (N.getOpcode() == ISD::ADD) {
2633     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2634     // SPE load/store can only handle 8-bit offsets.
2635     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2636         return true;
2637     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2638         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2639       return false; // r+i
2640     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2641       return false;    // r+i
2642 
2643     Base = N.getOperand(0);
2644     Index = N.getOperand(1);
2645     return true;
2646   } else if (N.getOpcode() == ISD::OR) {
2647     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2648         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2649       return false; // r+i can fold it if we can.
2650 
2651     // If this is an or of disjoint bitfields, we can codegen this as an add
2652     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2653     // disjoint.
2654     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2655 
2656     if (LHSKnown.Zero.getBoolValue()) {
2657       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2658       // If all of the bits are known zero on the LHS or RHS, the add won't
2659       // carry.
2660       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2661         Base = N.getOperand(0);
2662         Index = N.getOperand(1);
2663         return true;
2664       }
2665     }
2666   }
2667 
2668   return false;
2669 }
2670 
2671 // If we happen to be doing an i64 load or store into a stack slot that has
2672 // less than a 4-byte alignment, then the frame-index elimination may need to
2673 // use an indexed load or store instruction (because the offset may not be a
2674 // multiple of 4). The extra register needed to hold the offset comes from the
2675 // register scavenger, and it is possible that the scavenger will need to use
2676 // an emergency spill slot. As a result, we need to make sure that a spill slot
2677 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2678 // stack slot.
2679 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2680   // FIXME: This does not handle the LWA case.
2681   if (VT != MVT::i64)
2682     return;
2683 
2684   // NOTE: We'll exclude negative FIs here, which come from argument
2685   // lowering, because there are no known test cases triggering this problem
2686   // using packed structures (or similar). We can remove this exclusion if
2687   // we find such a test case. The reason why this is so test-case driven is
2688   // because this entire 'fixup' is only to prevent crashes (from the
2689   // register scavenger) on not-really-valid inputs. For example, if we have:
2690   //   %a = alloca i1
2691   //   %b = bitcast i1* %a to i64*
2692   //   store i64* a, i64 b
2693   // then the store should really be marked as 'align 1', but is not. If it
2694   // were marked as 'align 1' then the indexed form would have been
2695   // instruction-selected initially, and the problem this 'fixup' is preventing
2696   // won't happen regardless.
2697   if (FrameIdx < 0)
2698     return;
2699 
2700   MachineFunction &MF = DAG.getMachineFunction();
2701   MachineFrameInfo &MFI = MF.getFrameInfo();
2702 
2703   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2704     return;
2705 
2706   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2707   FuncInfo->setHasNonRISpills();
2708 }
2709 
2710 /// Returns true if the address N can be represented by a base register plus
2711 /// a signed 16-bit displacement [r+imm], and if it is not better
2712 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2713 /// displacements that are multiples of that value.
2714 bool PPCTargetLowering::SelectAddressRegImm(
2715     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2716     MaybeAlign EncodingAlignment) const {
2717   // FIXME dl should come from parent load or store, not from address
2718   SDLoc dl(N);
2719 
2720   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2721   // a [pc+imm].
2722   if (SelectAddressPCRel(N, Base))
2723     return false;
2724 
2725   // If this can be more profitably realized as r+r, fail.
2726   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2727     return false;
2728 
2729   if (N.getOpcode() == ISD::ADD) {
2730     int16_t imm = 0;
2731     if (isIntS16Immediate(N.getOperand(1), imm) &&
2732         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2733       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2734       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2735         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2736         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2737       } else {
2738         Base = N.getOperand(0);
2739       }
2740       return true; // [r+i]
2741     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2742       // Match LOAD (ADD (X, Lo(G))).
2743       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2744              && "Cannot handle constant offsets yet!");
2745       Disp = N.getOperand(1).getOperand(0);  // The global address.
2746       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2747              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2748              Disp.getOpcode() == ISD::TargetConstantPool ||
2749              Disp.getOpcode() == ISD::TargetJumpTable);
2750       Base = N.getOperand(0);
2751       return true;  // [&g+r]
2752     }
2753   } else if (N.getOpcode() == ISD::OR) {
2754     int16_t imm = 0;
2755     if (isIntS16Immediate(N.getOperand(1), imm) &&
2756         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2757       // If this is an or of disjoint bitfields, we can codegen this as an add
2758       // (for better address arithmetic) if the LHS and RHS of the OR are
2759       // provably disjoint.
2760       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2761 
2762       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2763         // If all of the bits are known zero on the LHS or RHS, the add won't
2764         // carry.
2765         if (FrameIndexSDNode *FI =
2766               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2767           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2768           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2769         } else {
2770           Base = N.getOperand(0);
2771         }
2772         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2773         return true;
2774       }
2775     }
2776   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2777     // Loading from a constant address.
2778 
2779     // If this address fits entirely in a 16-bit sext immediate field, codegen
2780     // this as "d, 0"
2781     int16_t Imm;
2782     if (isIntS16Immediate(CN, Imm) &&
2783         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2784       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2785       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2786                              CN->getValueType(0));
2787       return true;
2788     }
2789 
2790     // Handle 32-bit sext immediates with LIS + addr mode.
2791     if ((CN->getValueType(0) == MVT::i32 ||
2792          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2793         (!EncodingAlignment ||
2794          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2795       int Addr = (int)CN->getZExtValue();
2796 
2797       // Otherwise, break this down into an LIS + disp.
2798       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2799 
2800       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2801                                    MVT::i32);
2802       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2803       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2804       return true;
2805     }
2806   }
2807 
2808   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2809   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2810     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2811     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2812   } else
2813     Base = N;
2814   return true;      // [r+0]
2815 }
2816 
2817 /// Similar to the 16-bit case but for instructions that take a 34-bit
2818 /// displacement field (prefixed loads/stores).
2819 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2820                                               SDValue &Base,
2821                                               SelectionDAG &DAG) const {
2822   // Only on 64-bit targets.
2823   if (N.getValueType() != MVT::i64)
2824     return false;
2825 
2826   SDLoc dl(N);
2827   int64_t Imm = 0;
2828 
2829   if (N.getOpcode() == ISD::ADD) {
2830     if (!isIntS34Immediate(N.getOperand(1), Imm))
2831       return false;
2832     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2833     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2834       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2835     else
2836       Base = N.getOperand(0);
2837     return true;
2838   }
2839 
2840   if (N.getOpcode() == ISD::OR) {
2841     if (!isIntS34Immediate(N.getOperand(1), Imm))
2842       return false;
2843     // If this is an or of disjoint bitfields, we can codegen this as an add
2844     // (for better address arithmetic) if the LHS and RHS of the OR are
2845     // provably disjoint.
2846     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2847     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2848       return false;
2849     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2850       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2851     else
2852       Base = N.getOperand(0);
2853     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2854     return true;
2855   }
2856 
2857   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2858     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2859     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2860     return true;
2861   }
2862 
2863   return false;
2864 }
2865 
2866 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2867 /// represented as an indexed [r+r] operation.
2868 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2869                                                 SDValue &Index,
2870                                                 SelectionDAG &DAG) const {
2871   // Check to see if we can easily represent this as an [r+r] address.  This
2872   // will fail if it thinks that the address is more profitably represented as
2873   // reg+imm, e.g. where imm = 0.
2874   if (SelectAddressRegReg(N, Base, Index, DAG))
2875     return true;
2876 
2877   // If the address is the result of an add, we will utilize the fact that the
2878   // address calculation includes an implicit add.  However, we can reduce
2879   // register pressure if we do not materialize a constant just for use as the
2880   // index register.  We only get rid of the add if it is not an add of a
2881   // value and a 16-bit signed constant and both have a single use.
2882   int16_t imm = 0;
2883   if (N.getOpcode() == ISD::ADD &&
2884       (!isIntS16Immediate(N.getOperand(1), imm) ||
2885        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2886     Base = N.getOperand(0);
2887     Index = N.getOperand(1);
2888     return true;
2889   }
2890 
2891   // Otherwise, do it the hard way, using R0 as the base register.
2892   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2893                          N.getValueType());
2894   Index = N;
2895   return true;
2896 }
2897 
2898 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2899   Ty *PCRelCand = dyn_cast<Ty>(N);
2900   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2901 }
2902 
2903 /// Returns true if this address is a PC Relative address.
2904 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2905 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2906 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2907   // This is a materialize PC Relative node. Always select this as PC Relative.
2908   Base = N;
2909   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2910     return true;
2911   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2912       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2913       isValidPCRelNode<JumpTableSDNode>(N) ||
2914       isValidPCRelNode<BlockAddressSDNode>(N))
2915     return true;
2916   return false;
2917 }
2918 
2919 /// Returns true if we should use a direct load into vector instruction
2920 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2921 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2922 
2923   // If there are any other uses other than scalar to vector, then we should
2924   // keep it as a scalar load -> direct move pattern to prevent multiple
2925   // loads.
2926   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2927   if (!LD)
2928     return false;
2929 
2930   EVT MemVT = LD->getMemoryVT();
2931   if (!MemVT.isSimple())
2932     return false;
2933   switch(MemVT.getSimpleVT().SimpleTy) {
2934   case MVT::i64:
2935     break;
2936   case MVT::i32:
2937     if (!ST.hasP8Vector())
2938       return false;
2939     break;
2940   case MVT::i16:
2941   case MVT::i8:
2942     if (!ST.hasP9Vector())
2943       return false;
2944     break;
2945   default:
2946     return false;
2947   }
2948 
2949   SDValue LoadedVal(N, 0);
2950   if (!LoadedVal.hasOneUse())
2951     return false;
2952 
2953   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2954        UI != UE; ++UI)
2955     if (UI.getUse().get().getResNo() == 0 &&
2956         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2957         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2958       return false;
2959 
2960   return true;
2961 }
2962 
2963 /// getPreIndexedAddressParts - returns true by value, base pointer and
2964 /// offset pointer and addressing mode by reference if the node's address
2965 /// can be legally represented as pre-indexed load / store address.
2966 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2967                                                   SDValue &Offset,
2968                                                   ISD::MemIndexedMode &AM,
2969                                                   SelectionDAG &DAG) const {
2970   if (DisablePPCPreinc) return false;
2971 
2972   bool isLoad = true;
2973   SDValue Ptr;
2974   EVT VT;
2975   unsigned Alignment;
2976   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2977     Ptr = LD->getBasePtr();
2978     VT = LD->getMemoryVT();
2979     Alignment = LD->getAlignment();
2980   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2981     Ptr = ST->getBasePtr();
2982     VT  = ST->getMemoryVT();
2983     Alignment = ST->getAlignment();
2984     isLoad = false;
2985   } else
2986     return false;
2987 
2988   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2989   // instructions because we can fold these into a more efficient instruction
2990   // instead, (such as LXSD).
2991   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2992     return false;
2993   }
2994 
2995   // PowerPC doesn't have preinc load/store instructions for vectors
2996   if (VT.isVector())
2997     return false;
2998 
2999   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3000     // Common code will reject creating a pre-inc form if the base pointer
3001     // is a frame index, or if N is a store and the base pointer is either
3002     // the same as or a predecessor of the value being stored.  Check for
3003     // those situations here, and try with swapped Base/Offset instead.
3004     bool Swap = false;
3005 
3006     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3007       Swap = true;
3008     else if (!isLoad) {
3009       SDValue Val = cast<StoreSDNode>(N)->getValue();
3010       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3011         Swap = true;
3012     }
3013 
3014     if (Swap)
3015       std::swap(Base, Offset);
3016 
3017     AM = ISD::PRE_INC;
3018     return true;
3019   }
3020 
3021   // LDU/STU can only handle immediates that are a multiple of 4.
3022   if (VT != MVT::i64) {
3023     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
3024       return false;
3025   } else {
3026     // LDU/STU need an address with at least 4-byte alignment.
3027     if (Alignment < 4)
3028       return false;
3029 
3030     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3031       return false;
3032   }
3033 
3034   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3035     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3036     // sext i32 to i64 when addr mode is r+i.
3037     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3038         LD->getExtensionType() == ISD::SEXTLOAD &&
3039         isa<ConstantSDNode>(Offset))
3040       return false;
3041   }
3042 
3043   AM = ISD::PRE_INC;
3044   return true;
3045 }
3046 
3047 //===----------------------------------------------------------------------===//
3048 //  LowerOperation implementation
3049 //===----------------------------------------------------------------------===//
3050 
3051 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3052 /// and LoOpFlags to the target MO flags.
3053 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3054                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3055                                const GlobalValue *GV = nullptr) {
3056   HiOpFlags = PPCII::MO_HA;
3057   LoOpFlags = PPCII::MO_LO;
3058 
3059   // Don't use the pic base if not in PIC relocation model.
3060   if (IsPIC) {
3061     HiOpFlags |= PPCII::MO_PIC_FLAG;
3062     LoOpFlags |= PPCII::MO_PIC_FLAG;
3063   }
3064 }
3065 
3066 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3067                              SelectionDAG &DAG) {
3068   SDLoc DL(HiPart);
3069   EVT PtrVT = HiPart.getValueType();
3070   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3071 
3072   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3073   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3074 
3075   // With PIC, the first instruction is actually "GR+hi(&G)".
3076   if (isPIC)
3077     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3078                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3079 
3080   // Generate non-pic code that has direct accesses to the constant pool.
3081   // The address of the global is just (hi(&g)+lo(&g)).
3082   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3083 }
3084 
3085 static void setUsesTOCBasePtr(MachineFunction &MF) {
3086   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3087   FuncInfo->setUsesTOCBasePtr();
3088 }
3089 
3090 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3091   setUsesTOCBasePtr(DAG.getMachineFunction());
3092 }
3093 
3094 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3095                                        SDValue GA) const {
3096   const bool Is64Bit = Subtarget.isPPC64();
3097   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3098   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3099                         : Subtarget.isAIXABI()
3100                               ? DAG.getRegister(PPC::R2, VT)
3101                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3102   SDValue Ops[] = { GA, Reg };
3103   return DAG.getMemIntrinsicNode(
3104       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3105       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3106       MachineMemOperand::MOLoad);
3107 }
3108 
3109 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3110                                              SelectionDAG &DAG) const {
3111   EVT PtrVT = Op.getValueType();
3112   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3113   const Constant *C = CP->getConstVal();
3114 
3115   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3116   // The actual address of the GlobalValue is stored in the TOC.
3117   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3118     if (Subtarget.isUsingPCRelativeCalls()) {
3119       SDLoc DL(CP);
3120       EVT Ty = getPointerTy(DAG.getDataLayout());
3121       SDValue ConstPool = DAG.getTargetConstantPool(
3122           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3123       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3124     }
3125     setUsesTOCBasePtr(DAG);
3126     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3127     return getTOCEntry(DAG, SDLoc(CP), GA);
3128   }
3129 
3130   unsigned MOHiFlag, MOLoFlag;
3131   bool IsPIC = isPositionIndependent();
3132   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3133 
3134   if (IsPIC && Subtarget.isSVR4ABI()) {
3135     SDValue GA =
3136         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3137     return getTOCEntry(DAG, SDLoc(CP), GA);
3138   }
3139 
3140   SDValue CPIHi =
3141       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3142   SDValue CPILo =
3143       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3144   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3145 }
3146 
3147 // For 64-bit PowerPC, prefer the more compact relative encodings.
3148 // This trades 32 bits per jump table entry for one or two instructions
3149 // on the jump site.
3150 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3151   if (isJumpTableRelative())
3152     return MachineJumpTableInfo::EK_LabelDifference32;
3153 
3154   return TargetLowering::getJumpTableEncoding();
3155 }
3156 
3157 bool PPCTargetLowering::isJumpTableRelative() const {
3158   if (UseAbsoluteJumpTables)
3159     return false;
3160   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3161     return true;
3162   return TargetLowering::isJumpTableRelative();
3163 }
3164 
3165 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3166                                                     SelectionDAG &DAG) const {
3167   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3168     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3169 
3170   switch (getTargetMachine().getCodeModel()) {
3171   case CodeModel::Small:
3172   case CodeModel::Medium:
3173     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3174   default:
3175     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3176                        getPointerTy(DAG.getDataLayout()));
3177   }
3178 }
3179 
3180 const MCExpr *
3181 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3182                                                 unsigned JTI,
3183                                                 MCContext &Ctx) const {
3184   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3185     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3186 
3187   switch (getTargetMachine().getCodeModel()) {
3188   case CodeModel::Small:
3189   case CodeModel::Medium:
3190     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3191   default:
3192     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3193   }
3194 }
3195 
3196 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3197   EVT PtrVT = Op.getValueType();
3198   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3199 
3200   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3201   if (Subtarget.isUsingPCRelativeCalls()) {
3202     SDLoc DL(JT);
3203     EVT Ty = getPointerTy(DAG.getDataLayout());
3204     SDValue GA =
3205         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3206     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3207     return MatAddr;
3208   }
3209 
3210   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3211   // The actual address of the GlobalValue is stored in the TOC.
3212   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3213     setUsesTOCBasePtr(DAG);
3214     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3215     return getTOCEntry(DAG, SDLoc(JT), GA);
3216   }
3217 
3218   unsigned MOHiFlag, MOLoFlag;
3219   bool IsPIC = isPositionIndependent();
3220   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3221 
3222   if (IsPIC && Subtarget.isSVR4ABI()) {
3223     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3224                                         PPCII::MO_PIC_FLAG);
3225     return getTOCEntry(DAG, SDLoc(GA), GA);
3226   }
3227 
3228   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3229   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3230   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3231 }
3232 
3233 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3234                                              SelectionDAG &DAG) const {
3235   EVT PtrVT = Op.getValueType();
3236   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3237   const BlockAddress *BA = BASDN->getBlockAddress();
3238 
3239   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3240   if (Subtarget.isUsingPCRelativeCalls()) {
3241     SDLoc DL(BASDN);
3242     EVT Ty = getPointerTy(DAG.getDataLayout());
3243     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3244                                            PPCII::MO_PCREL_FLAG);
3245     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3246     return MatAddr;
3247   }
3248 
3249   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3250   // The actual BlockAddress is stored in the TOC.
3251   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3252     setUsesTOCBasePtr(DAG);
3253     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3254     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3255   }
3256 
3257   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3258   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3259     return getTOCEntry(
3260         DAG, SDLoc(BASDN),
3261         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3262 
3263   unsigned MOHiFlag, MOLoFlag;
3264   bool IsPIC = isPositionIndependent();
3265   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3266   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3267   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3268   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3269 }
3270 
3271 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3272                                               SelectionDAG &DAG) const {
3273   if (Subtarget.isAIXABI())
3274     return LowerGlobalTLSAddressAIX(Op, DAG);
3275 
3276   return LowerGlobalTLSAddressLinux(Op, DAG);
3277 }
3278 
3279 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3280                                                     SelectionDAG &DAG) const {
3281   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3282 
3283   if (DAG.getTarget().useEmulatedTLS())
3284     report_fatal_error("Emulated TLS is not yet supported on AIX");
3285 
3286   SDLoc dl(GA);
3287   const GlobalValue *GV = GA->getGlobal();
3288   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3289 
3290   // The general-dynamic model is the only access model supported for now, so
3291   // all the GlobalTLSAddress nodes are lowered with this model.
3292   // We need to generate two TOC entries, one for the variable offset, one for
3293   // the region handle. The global address for the TOC entry of the region
3294   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3295   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3296   SDValue VariableOffsetTGA =
3297       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3298   SDValue RegionHandleTGA =
3299       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3300   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3301   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3302   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3303                      RegionHandle);
3304 }
3305 
3306 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3307                                                       SelectionDAG &DAG) const {
3308   // FIXME: TLS addresses currently use medium model code sequences,
3309   // which is the most useful form.  Eventually support for small and
3310   // large models could be added if users need it, at the cost of
3311   // additional complexity.
3312   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3313   if (DAG.getTarget().useEmulatedTLS())
3314     return LowerToTLSEmulatedModel(GA, DAG);
3315 
3316   SDLoc dl(GA);
3317   const GlobalValue *GV = GA->getGlobal();
3318   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3319   bool is64bit = Subtarget.isPPC64();
3320   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3321   PICLevel::Level picLevel = M->getPICLevel();
3322 
3323   const TargetMachine &TM = getTargetMachine();
3324   TLSModel::Model Model = TM.getTLSModel(GV);
3325 
3326   if (Model == TLSModel::LocalExec) {
3327     if (Subtarget.isUsingPCRelativeCalls()) {
3328       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3329       SDValue TGA = DAG.getTargetGlobalAddress(
3330           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3331       SDValue MatAddr =
3332           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3333       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3334     }
3335 
3336     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3337                                                PPCII::MO_TPREL_HA);
3338     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3339                                                PPCII::MO_TPREL_LO);
3340     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3341                              : DAG.getRegister(PPC::R2, MVT::i32);
3342 
3343     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3344     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3345   }
3346 
3347   if (Model == TLSModel::InitialExec) {
3348     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3349     SDValue TGA = DAG.getTargetGlobalAddress(
3350         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3351     SDValue TGATLS = DAG.getTargetGlobalAddress(
3352         GV, dl, PtrVT, 0,
3353         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3354     SDValue TPOffset;
3355     if (IsPCRel) {
3356       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3357       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3358                              MachinePointerInfo());
3359     } else {
3360       SDValue GOTPtr;
3361       if (is64bit) {
3362         setUsesTOCBasePtr(DAG);
3363         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3364         GOTPtr =
3365             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3366       } else {
3367         if (!TM.isPositionIndependent())
3368           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3369         else if (picLevel == PICLevel::SmallPIC)
3370           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3371         else
3372           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3373       }
3374       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3375     }
3376     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3377   }
3378 
3379   if (Model == TLSModel::GeneralDynamic) {
3380     if (Subtarget.isUsingPCRelativeCalls()) {
3381       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3382                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3383       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3384     }
3385 
3386     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3387     SDValue GOTPtr;
3388     if (is64bit) {
3389       setUsesTOCBasePtr(DAG);
3390       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3391       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3392                                    GOTReg, TGA);
3393     } else {
3394       if (picLevel == PICLevel::SmallPIC)
3395         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3396       else
3397         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3398     }
3399     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3400                        GOTPtr, TGA, TGA);
3401   }
3402 
3403   if (Model == TLSModel::LocalDynamic) {
3404     if (Subtarget.isUsingPCRelativeCalls()) {
3405       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3406                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3407       SDValue MatPCRel =
3408           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3409       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3410     }
3411 
3412     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3413     SDValue GOTPtr;
3414     if (is64bit) {
3415       setUsesTOCBasePtr(DAG);
3416       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3417       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3418                            GOTReg, TGA);
3419     } else {
3420       if (picLevel == PICLevel::SmallPIC)
3421         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3422       else
3423         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3424     }
3425     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3426                                   PtrVT, GOTPtr, TGA, TGA);
3427     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3428                                       PtrVT, TLSAddr, TGA);
3429     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3430   }
3431 
3432   llvm_unreachable("Unknown TLS model!");
3433 }
3434 
3435 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3436                                               SelectionDAG &DAG) const {
3437   EVT PtrVT = Op.getValueType();
3438   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3439   SDLoc DL(GSDN);
3440   const GlobalValue *GV = GSDN->getGlobal();
3441 
3442   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3443   // The actual address of the GlobalValue is stored in the TOC.
3444   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3445     if (Subtarget.isUsingPCRelativeCalls()) {
3446       EVT Ty = getPointerTy(DAG.getDataLayout());
3447       if (isAccessedAsGotIndirect(Op)) {
3448         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3449                                                 PPCII::MO_PCREL_FLAG |
3450                                                     PPCII::MO_GOT_FLAG);
3451         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3452         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3453                                    MachinePointerInfo());
3454         return Load;
3455       } else {
3456         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3457                                                 PPCII::MO_PCREL_FLAG);
3458         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3459       }
3460     }
3461     setUsesTOCBasePtr(DAG);
3462     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3463     return getTOCEntry(DAG, DL, GA);
3464   }
3465 
3466   unsigned MOHiFlag, MOLoFlag;
3467   bool IsPIC = isPositionIndependent();
3468   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3469 
3470   if (IsPIC && Subtarget.isSVR4ABI()) {
3471     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3472                                             GSDN->getOffset(),
3473                                             PPCII::MO_PIC_FLAG);
3474     return getTOCEntry(DAG, DL, GA);
3475   }
3476 
3477   SDValue GAHi =
3478     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3479   SDValue GALo =
3480     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3481 
3482   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3483 }
3484 
3485 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3486   bool IsStrict = Op->isStrictFPOpcode();
3487   ISD::CondCode CC =
3488       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3489   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3490   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3491   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3492   EVT LHSVT = LHS.getValueType();
3493   SDLoc dl(Op);
3494 
3495   // Soften the setcc with libcall if it is fp128.
3496   if (LHSVT == MVT::f128) {
3497     assert(!Subtarget.hasP9Vector() &&
3498            "SETCC for f128 is already legal under Power9!");
3499     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3500                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3501     if (RHS.getNode())
3502       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3503                         DAG.getCondCode(CC));
3504     if (IsStrict)
3505       return DAG.getMergeValues({LHS, Chain}, dl);
3506     return LHS;
3507   }
3508 
3509   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3510 
3511   if (Op.getValueType() == MVT::v2i64) {
3512     // When the operands themselves are v2i64 values, we need to do something
3513     // special because VSX has no underlying comparison operations for these.
3514     if (LHS.getValueType() == MVT::v2i64) {
3515       // Equality can be handled by casting to the legal type for Altivec
3516       // comparisons, everything else needs to be expanded.
3517       if (CC != ISD::SETEQ && CC != ISD::SETNE)
3518         return SDValue();
3519       SDValue SetCC32 = DAG.getSetCC(
3520           dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3521           DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3522       int ShuffV[] = {1, 0, 3, 2};
3523       SDValue Shuff =
3524           DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3525       return DAG.getBitcast(MVT::v2i64,
3526                             DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3527                                         dl, MVT::v4i32, Shuff, SetCC32));
3528     }
3529 
3530     // We handle most of these in the usual way.
3531     return Op;
3532   }
3533 
3534   // If we're comparing for equality to zero, expose the fact that this is
3535   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3536   // fold the new nodes.
3537   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3538     return V;
3539 
3540   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3541     // Leave comparisons against 0 and -1 alone for now, since they're usually
3542     // optimized.  FIXME: revisit this when we can custom lower all setcc
3543     // optimizations.
3544     if (C->isAllOnes() || C->isZero())
3545       return SDValue();
3546   }
3547 
3548   // If we have an integer seteq/setne, turn it into a compare against zero
3549   // by xor'ing the rhs with the lhs, which is faster than setting a
3550   // condition register, reading it back out, and masking the correct bit.  The
3551   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3552   // the result to other bit-twiddling opportunities.
3553   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3554     EVT VT = Op.getValueType();
3555     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3556     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3557   }
3558   return SDValue();
3559 }
3560 
3561 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3562   SDNode *Node = Op.getNode();
3563   EVT VT = Node->getValueType(0);
3564   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3565   SDValue InChain = Node->getOperand(0);
3566   SDValue VAListPtr = Node->getOperand(1);
3567   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3568   SDLoc dl(Node);
3569 
3570   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3571 
3572   // gpr_index
3573   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3574                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3575   InChain = GprIndex.getValue(1);
3576 
3577   if (VT == MVT::i64) {
3578     // Check if GprIndex is even
3579     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3580                                  DAG.getConstant(1, dl, MVT::i32));
3581     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3582                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3583     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3584                                           DAG.getConstant(1, dl, MVT::i32));
3585     // Align GprIndex to be even if it isn't
3586     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3587                            GprIndex);
3588   }
3589 
3590   // fpr index is 1 byte after gpr
3591   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3592                                DAG.getConstant(1, dl, MVT::i32));
3593 
3594   // fpr
3595   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3596                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3597   InChain = FprIndex.getValue(1);
3598 
3599   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3600                                        DAG.getConstant(8, dl, MVT::i32));
3601 
3602   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3603                                         DAG.getConstant(4, dl, MVT::i32));
3604 
3605   // areas
3606   SDValue OverflowArea =
3607       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3608   InChain = OverflowArea.getValue(1);
3609 
3610   SDValue RegSaveArea =
3611       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3612   InChain = RegSaveArea.getValue(1);
3613 
3614   // select overflow_area if index > 8
3615   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3616                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3617 
3618   // adjustment constant gpr_index * 4/8
3619   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3620                                     VT.isInteger() ? GprIndex : FprIndex,
3621                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3622                                                     MVT::i32));
3623 
3624   // OurReg = RegSaveArea + RegConstant
3625   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3626                                RegConstant);
3627 
3628   // Floating types are 32 bytes into RegSaveArea
3629   if (VT.isFloatingPoint())
3630     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3631                          DAG.getConstant(32, dl, MVT::i32));
3632 
3633   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3634   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3635                                    VT.isInteger() ? GprIndex : FprIndex,
3636                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3637                                                    MVT::i32));
3638 
3639   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3640                               VT.isInteger() ? VAListPtr : FprPtr,
3641                               MachinePointerInfo(SV), MVT::i8);
3642 
3643   // determine if we should load from reg_save_area or overflow_area
3644   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3645 
3646   // increase overflow_area by 4/8 if gpr/fpr > 8
3647   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3648                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3649                                           dl, MVT::i32));
3650 
3651   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3652                              OverflowAreaPlusN);
3653 
3654   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3655                               MachinePointerInfo(), MVT::i32);
3656 
3657   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3658 }
3659 
3660 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3661   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3662 
3663   // We have to copy the entire va_list struct:
3664   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3665   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3666                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3667                        false, true, false, MachinePointerInfo(),
3668                        MachinePointerInfo());
3669 }
3670 
3671 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3672                                                   SelectionDAG &DAG) const {
3673   if (Subtarget.isAIXABI())
3674     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3675 
3676   return Op.getOperand(0);
3677 }
3678 
3679 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3680   MachineFunction &MF = DAG.getMachineFunction();
3681   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3682 
3683   assert((Op.getOpcode() == ISD::INLINEASM ||
3684           Op.getOpcode() == ISD::INLINEASM_BR) &&
3685          "Expecting Inline ASM node.");
3686 
3687   // If an LR store is already known to be required then there is not point in
3688   // checking this ASM as well.
3689   if (MFI.isLRStoreRequired())
3690     return Op;
3691 
3692   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3693   // type MVT::Glue. We want to ignore this last operand if that is the case.
3694   unsigned NumOps = Op.getNumOperands();
3695   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3696     --NumOps;
3697 
3698   // Check all operands that may contain the LR.
3699   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3700     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3701     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3702     ++i; // Skip the ID value.
3703 
3704     switch (InlineAsm::getKind(Flags)) {
3705     default:
3706       llvm_unreachable("Bad flags!");
3707     case InlineAsm::Kind_RegUse:
3708     case InlineAsm::Kind_Imm:
3709     case InlineAsm::Kind_Mem:
3710       i += NumVals;
3711       break;
3712     case InlineAsm::Kind_Clobber:
3713     case InlineAsm::Kind_RegDef:
3714     case InlineAsm::Kind_RegDefEarlyClobber: {
3715       for (; NumVals; --NumVals, ++i) {
3716         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3717         if (Reg != PPC::LR && Reg != PPC::LR8)
3718           continue;
3719         MFI.setLRStoreRequired();
3720         return Op;
3721       }
3722       break;
3723     }
3724     }
3725   }
3726 
3727   return Op;
3728 }
3729 
3730 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3731                                                 SelectionDAG &DAG) const {
3732   if (Subtarget.isAIXABI())
3733     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3734 
3735   SDValue Chain = Op.getOperand(0);
3736   SDValue Trmp = Op.getOperand(1); // trampoline
3737   SDValue FPtr = Op.getOperand(2); // nested function
3738   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3739   SDLoc dl(Op);
3740 
3741   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3742   bool isPPC64 = (PtrVT == MVT::i64);
3743   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3744 
3745   TargetLowering::ArgListTy Args;
3746   TargetLowering::ArgListEntry Entry;
3747 
3748   Entry.Ty = IntPtrTy;
3749   Entry.Node = Trmp; Args.push_back(Entry);
3750 
3751   // TrampSize == (isPPC64 ? 48 : 40);
3752   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3753                                isPPC64 ? MVT::i64 : MVT::i32);
3754   Args.push_back(Entry);
3755 
3756   Entry.Node = FPtr; Args.push_back(Entry);
3757   Entry.Node = Nest; Args.push_back(Entry);
3758 
3759   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3760   TargetLowering::CallLoweringInfo CLI(DAG);
3761   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3762       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3763       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3764 
3765   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3766   return CallResult.second;
3767 }
3768 
3769 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3770   MachineFunction &MF = DAG.getMachineFunction();
3771   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3772   EVT PtrVT = getPointerTy(MF.getDataLayout());
3773 
3774   SDLoc dl(Op);
3775 
3776   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3777     // vastart just stores the address of the VarArgsFrameIndex slot into the
3778     // memory location argument.
3779     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3780     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3781     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3782                         MachinePointerInfo(SV));
3783   }
3784 
3785   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3786   // We suppose the given va_list is already allocated.
3787   //
3788   // typedef struct {
3789   //  char gpr;     /* index into the array of 8 GPRs
3790   //                 * stored in the register save area
3791   //                 * gpr=0 corresponds to r3,
3792   //                 * gpr=1 to r4, etc.
3793   //                 */
3794   //  char fpr;     /* index into the array of 8 FPRs
3795   //                 * stored in the register save area
3796   //                 * fpr=0 corresponds to f1,
3797   //                 * fpr=1 to f2, etc.
3798   //                 */
3799   //  char *overflow_arg_area;
3800   //                /* location on stack that holds
3801   //                 * the next overflow argument
3802   //                 */
3803   //  char *reg_save_area;
3804   //               /* where r3:r10 and f1:f8 (if saved)
3805   //                * are stored
3806   //                */
3807   // } va_list[1];
3808 
3809   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3810   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3811   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3812                                             PtrVT);
3813   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3814                                  PtrVT);
3815 
3816   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3817   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3818 
3819   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3820   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3821 
3822   uint64_t FPROffset = 1;
3823   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3824 
3825   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3826 
3827   // Store first byte : number of int regs
3828   SDValue firstStore =
3829       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3830                         MachinePointerInfo(SV), MVT::i8);
3831   uint64_t nextOffset = FPROffset;
3832   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3833                                   ConstFPROffset);
3834 
3835   // Store second byte : number of float regs
3836   SDValue secondStore =
3837       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3838                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3839   nextOffset += StackOffset;
3840   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3841 
3842   // Store second word : arguments given on stack
3843   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3844                                     MachinePointerInfo(SV, nextOffset));
3845   nextOffset += FrameOffset;
3846   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3847 
3848   // Store third word : arguments given in registers
3849   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3850                       MachinePointerInfo(SV, nextOffset));
3851 }
3852 
3853 /// FPR - The set of FP registers that should be allocated for arguments
3854 /// on Darwin and AIX.
3855 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3856                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3857                                 PPC::F11, PPC::F12, PPC::F13};
3858 
3859 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3860 /// the stack.
3861 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3862                                        unsigned PtrByteSize) {
3863   unsigned ArgSize = ArgVT.getStoreSize();
3864   if (Flags.isByVal())
3865     ArgSize = Flags.getByValSize();
3866 
3867   // Round up to multiples of the pointer size, except for array members,
3868   // which are always packed.
3869   if (!Flags.isInConsecutiveRegs())
3870     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3871 
3872   return ArgSize;
3873 }
3874 
3875 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3876 /// on the stack.
3877 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3878                                          ISD::ArgFlagsTy Flags,
3879                                          unsigned PtrByteSize) {
3880   Align Alignment(PtrByteSize);
3881 
3882   // Altivec parameters are padded to a 16 byte boundary.
3883   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3884       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3885       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3886       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3887     Alignment = Align(16);
3888 
3889   // ByVal parameters are aligned as requested.
3890   if (Flags.isByVal()) {
3891     auto BVAlign = Flags.getNonZeroByValAlign();
3892     if (BVAlign > PtrByteSize) {
3893       if (BVAlign.value() % PtrByteSize != 0)
3894         llvm_unreachable(
3895             "ByVal alignment is not a multiple of the pointer size");
3896 
3897       Alignment = BVAlign;
3898     }
3899   }
3900 
3901   // Array members are always packed to their original alignment.
3902   if (Flags.isInConsecutiveRegs()) {
3903     // If the array member was split into multiple registers, the first
3904     // needs to be aligned to the size of the full type.  (Except for
3905     // ppcf128, which is only aligned as its f64 components.)
3906     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3907       Alignment = Align(OrigVT.getStoreSize());
3908     else
3909       Alignment = Align(ArgVT.getStoreSize());
3910   }
3911 
3912   return Alignment;
3913 }
3914 
3915 /// CalculateStackSlotUsed - Return whether this argument will use its
3916 /// stack slot (instead of being passed in registers).  ArgOffset,
3917 /// AvailableFPRs, and AvailableVRs must hold the current argument
3918 /// position, and will be updated to account for this argument.
3919 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3920                                    unsigned PtrByteSize, unsigned LinkageSize,
3921                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3922                                    unsigned &AvailableFPRs,
3923                                    unsigned &AvailableVRs) {
3924   bool UseMemory = false;
3925 
3926   // Respect alignment of argument on the stack.
3927   Align Alignment =
3928       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3929   ArgOffset = alignTo(ArgOffset, Alignment);
3930   // If there's no space left in the argument save area, we must
3931   // use memory (this check also catches zero-sized arguments).
3932   if (ArgOffset >= LinkageSize + ParamAreaSize)
3933     UseMemory = true;
3934 
3935   // Allocate argument on the stack.
3936   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3937   if (Flags.isInConsecutiveRegsLast())
3938     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3939   // If we overran the argument save area, we must use memory
3940   // (this check catches arguments passed partially in memory)
3941   if (ArgOffset > LinkageSize + ParamAreaSize)
3942     UseMemory = true;
3943 
3944   // However, if the argument is actually passed in an FPR or a VR,
3945   // we don't use memory after all.
3946   if (!Flags.isByVal()) {
3947     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3948       if (AvailableFPRs > 0) {
3949         --AvailableFPRs;
3950         return false;
3951       }
3952     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3953         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3954         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3955         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3956       if (AvailableVRs > 0) {
3957         --AvailableVRs;
3958         return false;
3959       }
3960   }
3961 
3962   return UseMemory;
3963 }
3964 
3965 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3966 /// ensure minimum alignment required for target.
3967 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3968                                      unsigned NumBytes) {
3969   return alignTo(NumBytes, Lowering->getStackAlign());
3970 }
3971 
3972 SDValue PPCTargetLowering::LowerFormalArguments(
3973     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3974     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3975     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3976   if (Subtarget.isAIXABI())
3977     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3978                                     InVals);
3979   if (Subtarget.is64BitELFABI())
3980     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3981                                        InVals);
3982   assert(Subtarget.is32BitELFABI());
3983   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3984                                      InVals);
3985 }
3986 
3987 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3988     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3989     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3990     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3991 
3992   // 32-bit SVR4 ABI Stack Frame Layout:
3993   //              +-----------------------------------+
3994   //        +-->  |            Back chain             |
3995   //        |     +-----------------------------------+
3996   //        |     | Floating-point register save area |
3997   //        |     +-----------------------------------+
3998   //        |     |    General register save area     |
3999   //        |     +-----------------------------------+
4000   //        |     |          CR save word             |
4001   //        |     +-----------------------------------+
4002   //        |     |         VRSAVE save word          |
4003   //        |     +-----------------------------------+
4004   //        |     |         Alignment padding         |
4005   //        |     +-----------------------------------+
4006   //        |     |     Vector register save area     |
4007   //        |     +-----------------------------------+
4008   //        |     |       Local variable space        |
4009   //        |     +-----------------------------------+
4010   //        |     |        Parameter list area        |
4011   //        |     +-----------------------------------+
4012   //        |     |           LR save word            |
4013   //        |     +-----------------------------------+
4014   // SP-->  +---  |            Back chain             |
4015   //              +-----------------------------------+
4016   //
4017   // Specifications:
4018   //   System V Application Binary Interface PowerPC Processor Supplement
4019   //   AltiVec Technology Programming Interface Manual
4020 
4021   MachineFunction &MF = DAG.getMachineFunction();
4022   MachineFrameInfo &MFI = MF.getFrameInfo();
4023   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4024 
4025   EVT PtrVT = getPointerTy(MF.getDataLayout());
4026   // Potential tail calls could cause overwriting of argument stack slots.
4027   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4028                        (CallConv == CallingConv::Fast));
4029   const Align PtrAlign(4);
4030 
4031   // Assign locations to all of the incoming arguments.
4032   SmallVector<CCValAssign, 16> ArgLocs;
4033   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4034                  *DAG.getContext());
4035 
4036   // Reserve space for the linkage area on the stack.
4037   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4038   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4039   if (useSoftFloat())
4040     CCInfo.PreAnalyzeFormalArguments(Ins);
4041 
4042   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4043   CCInfo.clearWasPPCF128();
4044 
4045   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4046     CCValAssign &VA = ArgLocs[i];
4047 
4048     // Arguments stored in registers.
4049     if (VA.isRegLoc()) {
4050       const TargetRegisterClass *RC;
4051       EVT ValVT = VA.getValVT();
4052 
4053       switch (ValVT.getSimpleVT().SimpleTy) {
4054         default:
4055           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4056         case MVT::i1:
4057         case MVT::i32:
4058           RC = &PPC::GPRCRegClass;
4059           break;
4060         case MVT::f32:
4061           if (Subtarget.hasP8Vector())
4062             RC = &PPC::VSSRCRegClass;
4063           else if (Subtarget.hasSPE())
4064             RC = &PPC::GPRCRegClass;
4065           else
4066             RC = &PPC::F4RCRegClass;
4067           break;
4068         case MVT::f64:
4069           if (Subtarget.hasVSX())
4070             RC = &PPC::VSFRCRegClass;
4071           else if (Subtarget.hasSPE())
4072             // SPE passes doubles in GPR pairs.
4073             RC = &PPC::GPRCRegClass;
4074           else
4075             RC = &PPC::F8RCRegClass;
4076           break;
4077         case MVT::v16i8:
4078         case MVT::v8i16:
4079         case MVT::v4i32:
4080           RC = &PPC::VRRCRegClass;
4081           break;
4082         case MVT::v4f32:
4083           RC = &PPC::VRRCRegClass;
4084           break;
4085         case MVT::v2f64:
4086         case MVT::v2i64:
4087           RC = &PPC::VRRCRegClass;
4088           break;
4089       }
4090 
4091       SDValue ArgValue;
4092       // Transform the arguments stored in physical registers into
4093       // virtual ones.
4094       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4095         assert(i + 1 < e && "No second half of double precision argument");
4096         Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4097         Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4098         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4099         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4100         if (!Subtarget.isLittleEndian())
4101           std::swap (ArgValueLo, ArgValueHi);
4102         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4103                                ArgValueHi);
4104       } else {
4105         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4106         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4107                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4108         if (ValVT == MVT::i1)
4109           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4110       }
4111 
4112       InVals.push_back(ArgValue);
4113     } else {
4114       // Argument stored in memory.
4115       assert(VA.isMemLoc());
4116 
4117       // Get the extended size of the argument type in stack
4118       unsigned ArgSize = VA.getLocVT().getStoreSize();
4119       // Get the actual size of the argument type
4120       unsigned ObjSize = VA.getValVT().getStoreSize();
4121       unsigned ArgOffset = VA.getLocMemOffset();
4122       // Stack objects in PPC32 are right justified.
4123       ArgOffset += ArgSize - ObjSize;
4124       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4125 
4126       // Create load nodes to retrieve arguments from the stack.
4127       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4128       InVals.push_back(
4129           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4130     }
4131   }
4132 
4133   // Assign locations to all of the incoming aggregate by value arguments.
4134   // Aggregates passed by value are stored in the local variable space of the
4135   // caller's stack frame, right above the parameter list area.
4136   SmallVector<CCValAssign, 16> ByValArgLocs;
4137   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4138                       ByValArgLocs, *DAG.getContext());
4139 
4140   // Reserve stack space for the allocations in CCInfo.
4141   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4142 
4143   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4144 
4145   // Area that is at least reserved in the caller of this function.
4146   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4147   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4148 
4149   // Set the size that is at least reserved in caller of this function.  Tail
4150   // call optimized function's reserved stack space needs to be aligned so that
4151   // taking the difference between two stack areas will result in an aligned
4152   // stack.
4153   MinReservedArea =
4154       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4155   FuncInfo->setMinReservedArea(MinReservedArea);
4156 
4157   SmallVector<SDValue, 8> MemOps;
4158 
4159   // If the function takes variable number of arguments, make a frame index for
4160   // the start of the first vararg value... for expansion of llvm.va_start.
4161   if (isVarArg) {
4162     static const MCPhysReg GPArgRegs[] = {
4163       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4164       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4165     };
4166     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4167 
4168     static const MCPhysReg FPArgRegs[] = {
4169       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4170       PPC::F8
4171     };
4172     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4173 
4174     if (useSoftFloat() || hasSPE())
4175        NumFPArgRegs = 0;
4176 
4177     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4178     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4179 
4180     // Make room for NumGPArgRegs and NumFPArgRegs.
4181     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4182                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4183 
4184     FuncInfo->setVarArgsStackOffset(
4185       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4186                             CCInfo.getNextStackOffset(), true));
4187 
4188     FuncInfo->setVarArgsFrameIndex(
4189         MFI.CreateStackObject(Depth, Align(8), false));
4190     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4191 
4192     // The fixed integer arguments of a variadic function are stored to the
4193     // VarArgsFrameIndex on the stack so that they may be loaded by
4194     // dereferencing the result of va_next.
4195     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4196       // Get an existing live-in vreg, or add a new one.
4197       Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4198       if (!VReg)
4199         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4200 
4201       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4202       SDValue Store =
4203           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4204       MemOps.push_back(Store);
4205       // Increment the address by four for the next argument to store
4206       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4207       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4208     }
4209 
4210     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4211     // is set.
4212     // The double arguments are stored to the VarArgsFrameIndex
4213     // on the stack.
4214     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4215       // Get an existing live-in vreg, or add a new one.
4216       Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4217       if (!VReg)
4218         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4219 
4220       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4221       SDValue Store =
4222           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4223       MemOps.push_back(Store);
4224       // Increment the address by eight for the next argument to store
4225       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4226                                          PtrVT);
4227       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4228     }
4229   }
4230 
4231   if (!MemOps.empty())
4232     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4233 
4234   return Chain;
4235 }
4236 
4237 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4238 // value to MVT::i64 and then truncate to the correct register size.
4239 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4240                                              EVT ObjectVT, SelectionDAG &DAG,
4241                                              SDValue ArgVal,
4242                                              const SDLoc &dl) const {
4243   if (Flags.isSExt())
4244     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4245                          DAG.getValueType(ObjectVT));
4246   else if (Flags.isZExt())
4247     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4248                          DAG.getValueType(ObjectVT));
4249 
4250   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4251 }
4252 
4253 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4254     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4255     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4256     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4257   // TODO: add description of PPC stack frame format, or at least some docs.
4258   //
4259   bool isELFv2ABI = Subtarget.isELFv2ABI();
4260   bool isLittleEndian = Subtarget.isLittleEndian();
4261   MachineFunction &MF = DAG.getMachineFunction();
4262   MachineFrameInfo &MFI = MF.getFrameInfo();
4263   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4264 
4265   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4266          "fastcc not supported on varargs functions");
4267 
4268   EVT PtrVT = getPointerTy(MF.getDataLayout());
4269   // Potential tail calls could cause overwriting of argument stack slots.
4270   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4271                        (CallConv == CallingConv::Fast));
4272   unsigned PtrByteSize = 8;
4273   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4274 
4275   static const MCPhysReg GPR[] = {
4276     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4277     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4278   };
4279   static const MCPhysReg VR[] = {
4280     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4281     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4282   };
4283 
4284   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4285   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4286   const unsigned Num_VR_Regs  = array_lengthof(VR);
4287 
4288   // Do a first pass over the arguments to determine whether the ABI
4289   // guarantees that our caller has allocated the parameter save area
4290   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4291   // in the ELFv2 ABI, it is true if this is a vararg function or if
4292   // any parameter is located in a stack slot.
4293 
4294   bool HasParameterArea = !isELFv2ABI || isVarArg;
4295   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4296   unsigned NumBytes = LinkageSize;
4297   unsigned AvailableFPRs = Num_FPR_Regs;
4298   unsigned AvailableVRs = Num_VR_Regs;
4299   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4300     if (Ins[i].Flags.isNest())
4301       continue;
4302 
4303     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4304                                PtrByteSize, LinkageSize, ParamAreaSize,
4305                                NumBytes, AvailableFPRs, AvailableVRs))
4306       HasParameterArea = true;
4307   }
4308 
4309   // Add DAG nodes to load the arguments or copy them out of registers.  On
4310   // entry to a function on PPC, the arguments start after the linkage area,
4311   // although the first ones are often in registers.
4312 
4313   unsigned ArgOffset = LinkageSize;
4314   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4315   SmallVector<SDValue, 8> MemOps;
4316   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4317   unsigned CurArgIdx = 0;
4318   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4319     SDValue ArgVal;
4320     bool needsLoad = false;
4321     EVT ObjectVT = Ins[ArgNo].VT;
4322     EVT OrigVT = Ins[ArgNo].ArgVT;
4323     unsigned ObjSize = ObjectVT.getStoreSize();
4324     unsigned ArgSize = ObjSize;
4325     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4326     if (Ins[ArgNo].isOrigArg()) {
4327       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4328       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4329     }
4330     // We re-align the argument offset for each argument, except when using the
4331     // fast calling convention, when we need to make sure we do that only when
4332     // we'll actually use a stack slot.
4333     unsigned CurArgOffset;
4334     Align Alignment;
4335     auto ComputeArgOffset = [&]() {
4336       /* Respect alignment of argument on the stack.  */
4337       Alignment =
4338           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4339       ArgOffset = alignTo(ArgOffset, Alignment);
4340       CurArgOffset = ArgOffset;
4341     };
4342 
4343     if (CallConv != CallingConv::Fast) {
4344       ComputeArgOffset();
4345 
4346       /* Compute GPR index associated with argument offset.  */
4347       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4348       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4349     }
4350 
4351     // FIXME the codegen can be much improved in some cases.
4352     // We do not have to keep everything in memory.
4353     if (Flags.isByVal()) {
4354       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4355 
4356       if (CallConv == CallingConv::Fast)
4357         ComputeArgOffset();
4358 
4359       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4360       ObjSize = Flags.getByValSize();
4361       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4362       // Empty aggregate parameters do not take up registers.  Examples:
4363       //   struct { } a;
4364       //   union  { } b;
4365       //   int c[0];
4366       // etc.  However, we have to provide a place-holder in InVals, so
4367       // pretend we have an 8-byte item at the current address for that
4368       // purpose.
4369       if (!ObjSize) {
4370         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4371         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4372         InVals.push_back(FIN);
4373         continue;
4374       }
4375 
4376       // Create a stack object covering all stack doublewords occupied
4377       // by the argument.  If the argument is (fully or partially) on
4378       // the stack, or if the argument is fully in registers but the
4379       // caller has allocated the parameter save anyway, we can refer
4380       // directly to the caller's stack frame.  Otherwise, create a
4381       // local copy in our own frame.
4382       int FI;
4383       if (HasParameterArea ||
4384           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4385         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4386       else
4387         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4388       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4389 
4390       // Handle aggregates smaller than 8 bytes.
4391       if (ObjSize < PtrByteSize) {
4392         // The value of the object is its address, which differs from the
4393         // address of the enclosing doubleword on big-endian systems.
4394         SDValue Arg = FIN;
4395         if (!isLittleEndian) {
4396           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4397           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4398         }
4399         InVals.push_back(Arg);
4400 
4401         if (GPR_idx != Num_GPR_Regs) {
4402           Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4403           FuncInfo->addLiveInAttr(VReg, Flags);
4404           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4405           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4406           SDValue Store =
4407               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4408                                 MachinePointerInfo(&*FuncArg), ObjType);
4409           MemOps.push_back(Store);
4410         }
4411         // Whether we copied from a register or not, advance the offset
4412         // into the parameter save area by a full doubleword.
4413         ArgOffset += PtrByteSize;
4414         continue;
4415       }
4416 
4417       // The value of the object is its address, which is the address of
4418       // its first stack doubleword.
4419       InVals.push_back(FIN);
4420 
4421       // Store whatever pieces of the object are in registers to memory.
4422       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4423         if (GPR_idx == Num_GPR_Regs)
4424           break;
4425 
4426         Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4427         FuncInfo->addLiveInAttr(VReg, Flags);
4428         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4429         SDValue Addr = FIN;
4430         if (j) {
4431           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4432           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4433         }
4434         unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4435         EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4436         SDValue Store =
4437             DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4438                               MachinePointerInfo(&*FuncArg, j), ObjType);
4439         MemOps.push_back(Store);
4440         ++GPR_idx;
4441       }
4442       ArgOffset += ArgSize;
4443       continue;
4444     }
4445 
4446     switch (ObjectVT.getSimpleVT().SimpleTy) {
4447     default: llvm_unreachable("Unhandled argument type!");
4448     case MVT::i1:
4449     case MVT::i32:
4450     case MVT::i64:
4451       if (Flags.isNest()) {
4452         // The 'nest' parameter, if any, is passed in R11.
4453         Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4454         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4455 
4456         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4457           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4458 
4459         break;
4460       }
4461 
4462       // These can be scalar arguments or elements of an integer array type
4463       // passed directly.  Clang may use those instead of "byval" aggregate
4464       // types to avoid forcing arguments to memory unnecessarily.
4465       if (GPR_idx != Num_GPR_Regs) {
4466         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4467         FuncInfo->addLiveInAttr(VReg, Flags);
4468         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4469 
4470         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4471           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4472           // value to MVT::i64 and then truncate to the correct register size.
4473           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4474       } else {
4475         if (CallConv == CallingConv::Fast)
4476           ComputeArgOffset();
4477 
4478         needsLoad = true;
4479         ArgSize = PtrByteSize;
4480       }
4481       if (CallConv != CallingConv::Fast || needsLoad)
4482         ArgOffset += 8;
4483       break;
4484 
4485     case MVT::f32:
4486     case MVT::f64:
4487       // These can be scalar arguments or elements of a float array type
4488       // passed directly.  The latter are used to implement ELFv2 homogenous
4489       // float aggregates.
4490       if (FPR_idx != Num_FPR_Regs) {
4491         unsigned VReg;
4492 
4493         if (ObjectVT == MVT::f32)
4494           VReg = MF.addLiveIn(FPR[FPR_idx],
4495                               Subtarget.hasP8Vector()
4496                                   ? &PPC::VSSRCRegClass
4497                                   : &PPC::F4RCRegClass);
4498         else
4499           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4500                                                 ? &PPC::VSFRCRegClass
4501                                                 : &PPC::F8RCRegClass);
4502 
4503         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4504         ++FPR_idx;
4505       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4506         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4507         // once we support fp <-> gpr moves.
4508 
4509         // This can only ever happen in the presence of f32 array types,
4510         // since otherwise we never run out of FPRs before running out
4511         // of GPRs.
4512         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4513         FuncInfo->addLiveInAttr(VReg, Flags);
4514         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4515 
4516         if (ObjectVT == MVT::f32) {
4517           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4518             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4519                                  DAG.getConstant(32, dl, MVT::i32));
4520           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4521         }
4522 
4523         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4524       } else {
4525         if (CallConv == CallingConv::Fast)
4526           ComputeArgOffset();
4527 
4528         needsLoad = true;
4529       }
4530 
4531       // When passing an array of floats, the array occupies consecutive
4532       // space in the argument area; only round up to the next doubleword
4533       // at the end of the array.  Otherwise, each float takes 8 bytes.
4534       if (CallConv != CallingConv::Fast || needsLoad) {
4535         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4536         ArgOffset += ArgSize;
4537         if (Flags.isInConsecutiveRegsLast())
4538           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4539       }
4540       break;
4541     case MVT::v4f32:
4542     case MVT::v4i32:
4543     case MVT::v8i16:
4544     case MVT::v16i8:
4545     case MVT::v2f64:
4546     case MVT::v2i64:
4547     case MVT::v1i128:
4548     case MVT::f128:
4549       // These can be scalar arguments or elements of a vector array type
4550       // passed directly.  The latter are used to implement ELFv2 homogenous
4551       // vector aggregates.
4552       if (VR_idx != Num_VR_Regs) {
4553         Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4554         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4555         ++VR_idx;
4556       } else {
4557         if (CallConv == CallingConv::Fast)
4558           ComputeArgOffset();
4559         needsLoad = true;
4560       }
4561       if (CallConv != CallingConv::Fast || needsLoad)
4562         ArgOffset += 16;
4563       break;
4564     }
4565 
4566     // We need to load the argument to a virtual register if we determined
4567     // above that we ran out of physical registers of the appropriate type.
4568     if (needsLoad) {
4569       if (ObjSize < ArgSize && !isLittleEndian)
4570         CurArgOffset += ArgSize - ObjSize;
4571       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4572       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4573       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4574     }
4575 
4576     InVals.push_back(ArgVal);
4577   }
4578 
4579   // Area that is at least reserved in the caller of this function.
4580   unsigned MinReservedArea;
4581   if (HasParameterArea)
4582     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4583   else
4584     MinReservedArea = LinkageSize;
4585 
4586   // Set the size that is at least reserved in caller of this function.  Tail
4587   // call optimized functions' reserved stack space needs to be aligned so that
4588   // taking the difference between two stack areas will result in an aligned
4589   // stack.
4590   MinReservedArea =
4591       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4592   FuncInfo->setMinReservedArea(MinReservedArea);
4593 
4594   // If the function takes variable number of arguments, make a frame index for
4595   // the start of the first vararg value... for expansion of llvm.va_start.
4596   // On ELFv2ABI spec, it writes:
4597   // C programs that are intended to be *portable* across different compilers
4598   // and architectures must use the header file <stdarg.h> to deal with variable
4599   // argument lists.
4600   if (isVarArg && MFI.hasVAStart()) {
4601     int Depth = ArgOffset;
4602 
4603     FuncInfo->setVarArgsFrameIndex(
4604       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4605     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4606 
4607     // If this function is vararg, store any remaining integer argument regs
4608     // to their spots on the stack so that they may be loaded by dereferencing
4609     // the result of va_next.
4610     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4611          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4612       Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4613       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4614       SDValue Store =
4615           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4616       MemOps.push_back(Store);
4617       // Increment the address by four for the next argument to store
4618       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4619       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4620     }
4621   }
4622 
4623   if (!MemOps.empty())
4624     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4625 
4626   return Chain;
4627 }
4628 
4629 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4630 /// adjusted to accommodate the arguments for the tailcall.
4631 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4632                                    unsigned ParamSize) {
4633 
4634   if (!isTailCall) return 0;
4635 
4636   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4637   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4638   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4639   // Remember only if the new adjustment is bigger.
4640   if (SPDiff < FI->getTailCallSPDelta())
4641     FI->setTailCallSPDelta(SPDiff);
4642 
4643   return SPDiff;
4644 }
4645 
4646 static bool isFunctionGlobalAddress(SDValue Callee);
4647 
4648 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4649                               const TargetMachine &TM) {
4650   // It does not make sense to call callsShareTOCBase() with a caller that
4651   // is PC Relative since PC Relative callers do not have a TOC.
4652 #ifndef NDEBUG
4653   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4654   assert(!STICaller->isUsingPCRelativeCalls() &&
4655          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4656 #endif
4657 
4658   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4659   // don't have enough information to determine if the caller and callee share
4660   // the same  TOC base, so we have to pessimistically assume they don't for
4661   // correctness.
4662   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4663   if (!G)
4664     return false;
4665 
4666   const GlobalValue *GV = G->getGlobal();
4667 
4668   // If the callee is preemptable, then the static linker will use a plt-stub
4669   // which saves the toc to the stack, and needs a nop after the call
4670   // instruction to convert to a toc-restore.
4671   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4672     return false;
4673 
4674   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4675   // We may need a TOC restore in the situation where the caller requires a
4676   // valid TOC but the callee is PC Relative and does not.
4677   const Function *F = dyn_cast<Function>(GV);
4678   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4679 
4680   // If we have an Alias we can try to get the function from there.
4681   if (Alias) {
4682     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4683     F = dyn_cast<Function>(GlobalObj);
4684   }
4685 
4686   // If we still have no valid function pointer we do not have enough
4687   // information to determine if the callee uses PC Relative calls so we must
4688   // assume that it does.
4689   if (!F)
4690     return false;
4691 
4692   // If the callee uses PC Relative we cannot guarantee that the callee won't
4693   // clobber the TOC of the caller and so we must assume that the two
4694   // functions do not share a TOC base.
4695   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4696   if (STICallee->isUsingPCRelativeCalls())
4697     return false;
4698 
4699   // If the GV is not a strong definition then we need to assume it can be
4700   // replaced by another function at link time. The function that replaces
4701   // it may not share the same TOC as the caller since the callee may be
4702   // replaced by a PC Relative version of the same function.
4703   if (!GV->isStrongDefinitionForLinker())
4704     return false;
4705 
4706   // The medium and large code models are expected to provide a sufficiently
4707   // large TOC to provide all data addressing needs of a module with a
4708   // single TOC.
4709   if (CodeModel::Medium == TM.getCodeModel() ||
4710       CodeModel::Large == TM.getCodeModel())
4711     return true;
4712 
4713   // Any explicitly-specified sections and section prefixes must also match.
4714   // Also, if we're using -ffunction-sections, then each function is always in
4715   // a different section (the same is true for COMDAT functions).
4716   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4717       GV->getSection() != Caller->getSection())
4718     return false;
4719   if (const auto *F = dyn_cast<Function>(GV)) {
4720     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4721       return false;
4722   }
4723 
4724   return true;
4725 }
4726 
4727 static bool
4728 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4729                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4730   assert(Subtarget.is64BitELFABI());
4731 
4732   const unsigned PtrByteSize = 8;
4733   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4734 
4735   static const MCPhysReg GPR[] = {
4736     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4737     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4738   };
4739   static const MCPhysReg VR[] = {
4740     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4741     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4742   };
4743 
4744   const unsigned NumGPRs = array_lengthof(GPR);
4745   const unsigned NumFPRs = 13;
4746   const unsigned NumVRs = array_lengthof(VR);
4747   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4748 
4749   unsigned NumBytes = LinkageSize;
4750   unsigned AvailableFPRs = NumFPRs;
4751   unsigned AvailableVRs = NumVRs;
4752 
4753   for (const ISD::OutputArg& Param : Outs) {
4754     if (Param.Flags.isNest()) continue;
4755 
4756     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4757                                LinkageSize, ParamAreaSize, NumBytes,
4758                                AvailableFPRs, AvailableVRs))
4759       return true;
4760   }
4761   return false;
4762 }
4763 
4764 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4765   if (CB.arg_size() != CallerFn->arg_size())
4766     return false;
4767 
4768   auto CalleeArgIter = CB.arg_begin();
4769   auto CalleeArgEnd = CB.arg_end();
4770   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4771 
4772   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4773     const Value* CalleeArg = *CalleeArgIter;
4774     const Value* CallerArg = &(*CallerArgIter);
4775     if (CalleeArg == CallerArg)
4776       continue;
4777 
4778     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4779     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4780     //      }
4781     // 1st argument of callee is undef and has the same type as caller.
4782     if (CalleeArg->getType() == CallerArg->getType() &&
4783         isa<UndefValue>(CalleeArg))
4784       continue;
4785 
4786     return false;
4787   }
4788 
4789   return true;
4790 }
4791 
4792 // Returns true if TCO is possible between the callers and callees
4793 // calling conventions.
4794 static bool
4795 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4796                                     CallingConv::ID CalleeCC) {
4797   // Tail calls are possible with fastcc and ccc.
4798   auto isTailCallableCC  = [] (CallingConv::ID CC){
4799       return  CC == CallingConv::C || CC == CallingConv::Fast;
4800   };
4801   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4802     return false;
4803 
4804   // We can safely tail call both fastcc and ccc callees from a c calling
4805   // convention caller. If the caller is fastcc, we may have less stack space
4806   // than a non-fastcc caller with the same signature so disable tail-calls in
4807   // that case.
4808   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4809 }
4810 
4811 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4812     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4813     const SmallVectorImpl<ISD::OutputArg> &Outs,
4814     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4815   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4816 
4817   if (DisableSCO && !TailCallOpt) return false;
4818 
4819   // Variadic argument functions are not supported.
4820   if (isVarArg) return false;
4821 
4822   auto &Caller = DAG.getMachineFunction().getFunction();
4823   // Check that the calling conventions are compatible for tco.
4824   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4825     return false;
4826 
4827   // Caller contains any byval parameter is not supported.
4828   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4829     return false;
4830 
4831   // Callee contains any byval parameter is not supported, too.
4832   // Note: This is a quick work around, because in some cases, e.g.
4833   // caller's stack size > callee's stack size, we are still able to apply
4834   // sibling call optimization. For example, gcc is able to do SCO for caller1
4835   // in the following example, but not for caller2.
4836   //   struct test {
4837   //     long int a;
4838   //     char ary[56];
4839   //   } gTest;
4840   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4841   //     b->a = v.a;
4842   //     return 0;
4843   //   }
4844   //   void caller1(struct test a, struct test c, struct test *b) {
4845   //     callee(gTest, b); }
4846   //   void caller2(struct test *b) { callee(gTest, b); }
4847   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4848     return false;
4849 
4850   // If callee and caller use different calling conventions, we cannot pass
4851   // parameters on stack since offsets for the parameter area may be different.
4852   if (Caller.getCallingConv() != CalleeCC &&
4853       needStackSlotPassParameters(Subtarget, Outs))
4854     return false;
4855 
4856   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4857   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4858   // callee potentially have different TOC bases then we cannot tail call since
4859   // we need to restore the TOC pointer after the call.
4860   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4861   // We cannot guarantee this for indirect calls or calls to external functions.
4862   // When PC-Relative addressing is used, the concept of the TOC is no longer
4863   // applicable so this check is not required.
4864   // Check first for indirect calls.
4865   if (!Subtarget.isUsingPCRelativeCalls() &&
4866       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4867     return false;
4868 
4869   // Check if we share the TOC base.
4870   if (!Subtarget.isUsingPCRelativeCalls() &&
4871       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4872     return false;
4873 
4874   // TCO allows altering callee ABI, so we don't have to check further.
4875   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4876     return true;
4877 
4878   if (DisableSCO) return false;
4879 
4880   // If callee use the same argument list that caller is using, then we can
4881   // apply SCO on this case. If it is not, then we need to check if callee needs
4882   // stack for passing arguments.
4883   // PC Relative tail calls may not have a CallBase.
4884   // If there is no CallBase we cannot verify if we have the same argument
4885   // list so assume that we don't have the same argument list.
4886   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4887       needStackSlotPassParameters(Subtarget, Outs))
4888     return false;
4889   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4890     return false;
4891 
4892   return true;
4893 }
4894 
4895 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4896 /// for tail call optimization. Targets which want to do tail call
4897 /// optimization should implement this function.
4898 bool
4899 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4900                                                      CallingConv::ID CalleeCC,
4901                                                      bool isVarArg,
4902                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4903                                                      SelectionDAG& DAG) const {
4904   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4905     return false;
4906 
4907   // Variable argument functions are not supported.
4908   if (isVarArg)
4909     return false;
4910 
4911   MachineFunction &MF = DAG.getMachineFunction();
4912   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4913   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4914     // Functions containing by val parameters are not supported.
4915     for (unsigned i = 0; i != Ins.size(); i++) {
4916        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4917        if (Flags.isByVal()) return false;
4918     }
4919 
4920     // Non-PIC/GOT tail calls are supported.
4921     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4922       return true;
4923 
4924     // At the moment we can only do local tail calls (in same module, hidden
4925     // or protected) if we are generating PIC.
4926     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4927       return G->getGlobal()->hasHiddenVisibility()
4928           || G->getGlobal()->hasProtectedVisibility();
4929   }
4930 
4931   return false;
4932 }
4933 
4934 /// isCallCompatibleAddress - Return the immediate to use if the specified
4935 /// 32-bit value is representable in the immediate field of a BxA instruction.
4936 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4937   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4938   if (!C) return nullptr;
4939 
4940   int Addr = C->getZExtValue();
4941   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4942       SignExtend32<26>(Addr) != Addr)
4943     return nullptr;  // Top 6 bits have to be sext of immediate.
4944 
4945   return DAG
4946       .getConstant(
4947           (int)C->getZExtValue() >> 2, SDLoc(Op),
4948           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4949       .getNode();
4950 }
4951 
4952 namespace {
4953 
4954 struct TailCallArgumentInfo {
4955   SDValue Arg;
4956   SDValue FrameIdxOp;
4957   int FrameIdx = 0;
4958 
4959   TailCallArgumentInfo() = default;
4960 };
4961 
4962 } // end anonymous namespace
4963 
4964 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4965 static void StoreTailCallArgumentsToStackSlot(
4966     SelectionDAG &DAG, SDValue Chain,
4967     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4968     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4969   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4970     SDValue Arg = TailCallArgs[i].Arg;
4971     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4972     int FI = TailCallArgs[i].FrameIdx;
4973     // Store relative to framepointer.
4974     MemOpChains.push_back(DAG.getStore(
4975         Chain, dl, Arg, FIN,
4976         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4977   }
4978 }
4979 
4980 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4981 /// the appropriate stack slot for the tail call optimized function call.
4982 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4983                                              SDValue OldRetAddr, SDValue OldFP,
4984                                              int SPDiff, const SDLoc &dl) {
4985   if (SPDiff) {
4986     // Calculate the new stack slot for the return address.
4987     MachineFunction &MF = DAG.getMachineFunction();
4988     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4989     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4990     bool isPPC64 = Subtarget.isPPC64();
4991     int SlotSize = isPPC64 ? 8 : 4;
4992     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4993     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4994                                                          NewRetAddrLoc, true);
4995     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4996     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4997     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4998                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4999   }
5000   return Chain;
5001 }
5002 
5003 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5004 /// the position of the argument.
5005 static void
5006 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5007                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5008                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5009   int Offset = ArgOffset + SPDiff;
5010   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5011   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5012   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5013   SDValue FIN = DAG.getFrameIndex(FI, VT);
5014   TailCallArgumentInfo Info;
5015   Info.Arg = Arg;
5016   Info.FrameIdxOp = FIN;
5017   Info.FrameIdx = FI;
5018   TailCallArguments.push_back(Info);
5019 }
5020 
5021 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5022 /// stack slot. Returns the chain as result and the loaded frame pointers in
5023 /// LROpOut/FPOpout. Used when tail calling.
5024 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5025     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5026     SDValue &FPOpOut, const SDLoc &dl) const {
5027   if (SPDiff) {
5028     // Load the LR and FP stack slot for later adjusting.
5029     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5030     LROpOut = getReturnAddrFrameIndex(DAG);
5031     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5032     Chain = SDValue(LROpOut.getNode(), 1);
5033   }
5034   return Chain;
5035 }
5036 
5037 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5038 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5039 /// specified by the specific parameter attribute. The copy will be passed as
5040 /// a byval function parameter.
5041 /// Sometimes what we are copying is the end of a larger object, the part that
5042 /// does not fit in registers.
5043 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5044                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5045                                          SelectionDAG &DAG, const SDLoc &dl) {
5046   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5047   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5048                        Flags.getNonZeroByValAlign(), false, false, false,
5049                        MachinePointerInfo(), MachinePointerInfo());
5050 }
5051 
5052 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5053 /// tail calls.
5054 static void LowerMemOpCallTo(
5055     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5056     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5057     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5058     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5059   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5060   if (!isTailCall) {
5061     if (isVector) {
5062       SDValue StackPtr;
5063       if (isPPC64)
5064         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5065       else
5066         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5067       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5068                            DAG.getConstant(ArgOffset, dl, PtrVT));
5069     }
5070     MemOpChains.push_back(
5071         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5072     // Calculate and remember argument location.
5073   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5074                                   TailCallArguments);
5075 }
5076 
5077 static void
5078 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5079                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5080                 SDValue FPOp,
5081                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5082   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5083   // might overwrite each other in case of tail call optimization.
5084   SmallVector<SDValue, 8> MemOpChains2;
5085   // Do not flag preceding copytoreg stuff together with the following stuff.
5086   InFlag = SDValue();
5087   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5088                                     MemOpChains2, dl);
5089   if (!MemOpChains2.empty())
5090     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5091 
5092   // Store the return address to the appropriate stack slot.
5093   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5094 
5095   // Emit callseq_end just before tailcall node.
5096   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5097                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5098   InFlag = Chain.getValue(1);
5099 }
5100 
5101 // Is this global address that of a function that can be called by name? (as
5102 // opposed to something that must hold a descriptor for an indirect call).
5103 static bool isFunctionGlobalAddress(SDValue Callee) {
5104   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5105     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5106         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5107       return false;
5108 
5109     return G->getGlobal()->getValueType()->isFunctionTy();
5110   }
5111 
5112   return false;
5113 }
5114 
5115 SDValue PPCTargetLowering::LowerCallResult(
5116     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5117     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5118     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5119   SmallVector<CCValAssign, 16> RVLocs;
5120   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5121                     *DAG.getContext());
5122 
5123   CCRetInfo.AnalyzeCallResult(
5124       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5125                ? RetCC_PPC_Cold
5126                : RetCC_PPC);
5127 
5128   // Copy all of the result registers out of their specified physreg.
5129   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5130     CCValAssign &VA = RVLocs[i];
5131     assert(VA.isRegLoc() && "Can only return in registers!");
5132 
5133     SDValue Val;
5134 
5135     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5136       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5137                                       InFlag);
5138       Chain = Lo.getValue(1);
5139       InFlag = Lo.getValue(2);
5140       VA = RVLocs[++i]; // skip ahead to next loc
5141       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5142                                       InFlag);
5143       Chain = Hi.getValue(1);
5144       InFlag = Hi.getValue(2);
5145       if (!Subtarget.isLittleEndian())
5146         std::swap (Lo, Hi);
5147       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5148     } else {
5149       Val = DAG.getCopyFromReg(Chain, dl,
5150                                VA.getLocReg(), VA.getLocVT(), InFlag);
5151       Chain = Val.getValue(1);
5152       InFlag = Val.getValue(2);
5153     }
5154 
5155     switch (VA.getLocInfo()) {
5156     default: llvm_unreachable("Unknown loc info!");
5157     case CCValAssign::Full: break;
5158     case CCValAssign::AExt:
5159       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5160       break;
5161     case CCValAssign::ZExt:
5162       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5163                         DAG.getValueType(VA.getValVT()));
5164       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5165       break;
5166     case CCValAssign::SExt:
5167       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5168                         DAG.getValueType(VA.getValVT()));
5169       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5170       break;
5171     }
5172 
5173     InVals.push_back(Val);
5174   }
5175 
5176   return Chain;
5177 }
5178 
5179 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5180                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5181   // PatchPoint calls are not indirect.
5182   if (isPatchPoint)
5183     return false;
5184 
5185   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5186     return false;
5187 
5188   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5189   // becuase the immediate function pointer points to a descriptor instead of
5190   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5191   // pointer immediate points to the global entry point, while the BLA would
5192   // need to jump to the local entry point (see rL211174).
5193   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5194       isBLACompatibleAddress(Callee, DAG))
5195     return false;
5196 
5197   return true;
5198 }
5199 
5200 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5201 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5202   return Subtarget.isAIXABI() ||
5203          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5204 }
5205 
5206 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5207                               const Function &Caller, const SDValue &Callee,
5208                               const PPCSubtarget &Subtarget,
5209                               const TargetMachine &TM,
5210                               bool IsStrictFPCall = false) {
5211   if (CFlags.IsTailCall)
5212     return PPCISD::TC_RETURN;
5213 
5214   unsigned RetOpc = 0;
5215   // This is a call through a function pointer.
5216   if (CFlags.IsIndirect) {
5217     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5218     // indirect calls. The save of the caller's TOC pointer to the stack will be
5219     // inserted into the DAG as part of call lowering. The restore of the TOC
5220     // pointer is modeled by using a pseudo instruction for the call opcode that
5221     // represents the 2 instruction sequence of an indirect branch and link,
5222     // immediately followed by a load of the TOC pointer from the the stack save
5223     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5224     // as it is not saved or used.
5225     RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5226                                                  : PPCISD::BCTRL;
5227   } else if (Subtarget.isUsingPCRelativeCalls()) {
5228     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5229     RetOpc = PPCISD::CALL_NOTOC;
5230   } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5231     // The ABIs that maintain a TOC pointer accross calls need to have a nop
5232     // immediately following the call instruction if the caller and callee may
5233     // have different TOC bases. At link time if the linker determines the calls
5234     // may not share a TOC base, the call is redirected to a trampoline inserted
5235     // by the linker. The trampoline will (among other things) save the callers
5236     // TOC pointer at an ABI designated offset in the linkage area and the
5237     // linker will rewrite the nop to be a load of the TOC pointer from the
5238     // linkage area into gpr2.
5239     RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5240                                                     : PPCISD::CALL_NOP;
5241   else
5242     RetOpc = PPCISD::CALL;
5243   if (IsStrictFPCall) {
5244     switch (RetOpc) {
5245     default:
5246       llvm_unreachable("Unknown call opcode");
5247     case PPCISD::BCTRL_LOAD_TOC:
5248       RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5249       break;
5250     case PPCISD::BCTRL:
5251       RetOpc = PPCISD::BCTRL_RM;
5252       break;
5253     case PPCISD::CALL_NOTOC:
5254       RetOpc = PPCISD::CALL_NOTOC_RM;
5255       break;
5256     case PPCISD::CALL:
5257       RetOpc = PPCISD::CALL_RM;
5258       break;
5259     case PPCISD::CALL_NOP:
5260       RetOpc = PPCISD::CALL_NOP_RM;
5261       break;
5262     }
5263   }
5264   return RetOpc;
5265 }
5266 
5267 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5268                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5269   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5270     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5271       return SDValue(Dest, 0);
5272 
5273   // Returns true if the callee is local, and false otherwise.
5274   auto isLocalCallee = [&]() {
5275     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5276     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5277     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5278 
5279     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5280            !isa_and_nonnull<GlobalIFunc>(GV);
5281   };
5282 
5283   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5284   // a static relocation model causes some versions of GNU LD (2.17.50, at
5285   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5286   // built with secure-PLT.
5287   bool UsePlt =
5288       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5289       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5290 
5291   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5292     const TargetMachine &TM = Subtarget.getTargetMachine();
5293     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5294     MCSymbolXCOFF *S =
5295         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5296 
5297     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5298     return DAG.getMCSymbol(S, PtrVT);
5299   };
5300 
5301   if (isFunctionGlobalAddress(Callee)) {
5302     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5303 
5304     if (Subtarget.isAIXABI()) {
5305       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5306       return getAIXFuncEntryPointSymbolSDNode(GV);
5307     }
5308     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5309                                       UsePlt ? PPCII::MO_PLT : 0);
5310   }
5311 
5312   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5313     const char *SymName = S->getSymbol();
5314     if (Subtarget.isAIXABI()) {
5315       // If there exists a user-declared function whose name is the same as the
5316       // ExternalSymbol's, then we pick up the user-declared version.
5317       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5318       if (const Function *F =
5319               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5320         return getAIXFuncEntryPointSymbolSDNode(F);
5321 
5322       // On AIX, direct function calls reference the symbol for the function's
5323       // entry point, which is named by prepending a "." before the function's
5324       // C-linkage name. A Qualname is returned here because an external
5325       // function entry point is a csect with XTY_ER property.
5326       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5327         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5328         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5329             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5330             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5331         return Sec->getQualNameSymbol();
5332       };
5333 
5334       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5335     }
5336     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5337                                        UsePlt ? PPCII::MO_PLT : 0);
5338   }
5339 
5340   // No transformation needed.
5341   assert(Callee.getNode() && "What no callee?");
5342   return Callee;
5343 }
5344 
5345 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5346   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5347          "Expected a CALLSEQ_STARTSDNode.");
5348 
5349   // The last operand is the chain, except when the node has glue. If the node
5350   // has glue, then the last operand is the glue, and the chain is the second
5351   // last operand.
5352   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5353   if (LastValue.getValueType() != MVT::Glue)
5354     return LastValue;
5355 
5356   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5357 }
5358 
5359 // Creates the node that moves a functions address into the count register
5360 // to prepare for an indirect call instruction.
5361 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5362                                 SDValue &Glue, SDValue &Chain,
5363                                 const SDLoc &dl) {
5364   SDValue MTCTROps[] = {Chain, Callee, Glue};
5365   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5366   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5367                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5368   // The glue is the second value produced.
5369   Glue = Chain.getValue(1);
5370 }
5371 
5372 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5373                                           SDValue &Glue, SDValue &Chain,
5374                                           SDValue CallSeqStart,
5375                                           const CallBase *CB, const SDLoc &dl,
5376                                           bool hasNest,
5377                                           const PPCSubtarget &Subtarget) {
5378   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5379   // entry point, but to the function descriptor (the function entry point
5380   // address is part of the function descriptor though).
5381   // The function descriptor is a three doubleword structure with the
5382   // following fields: function entry point, TOC base address and
5383   // environment pointer.
5384   // Thus for a call through a function pointer, the following actions need
5385   // to be performed:
5386   //   1. Save the TOC of the caller in the TOC save area of its stack
5387   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5388   //   2. Load the address of the function entry point from the function
5389   //      descriptor.
5390   //   3. Load the TOC of the callee from the function descriptor into r2.
5391   //   4. Load the environment pointer from the function descriptor into
5392   //      r11.
5393   //   5. Branch to the function entry point address.
5394   //   6. On return of the callee, the TOC of the caller needs to be
5395   //      restored (this is done in FinishCall()).
5396   //
5397   // The loads are scheduled at the beginning of the call sequence, and the
5398   // register copies are flagged together to ensure that no other
5399   // operations can be scheduled in between. E.g. without flagging the
5400   // copies together, a TOC access in the caller could be scheduled between
5401   // the assignment of the callee TOC and the branch to the callee, which leads
5402   // to incorrect code.
5403 
5404   // Start by loading the function address from the descriptor.
5405   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5406   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5407                       ? (MachineMemOperand::MODereferenceable |
5408                          MachineMemOperand::MOInvariant)
5409                       : MachineMemOperand::MONone;
5410 
5411   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5412 
5413   // Registers used in building the DAG.
5414   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5415   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5416 
5417   // Offsets of descriptor members.
5418   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5419   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5420 
5421   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5422   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5423 
5424   // One load for the functions entry point address.
5425   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5426                                     Alignment, MMOFlags);
5427 
5428   // One for loading the TOC anchor for the module that contains the called
5429   // function.
5430   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5431   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5432   SDValue TOCPtr =
5433       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5434                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5435 
5436   // One for loading the environment pointer.
5437   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5438   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5439   SDValue LoadEnvPtr =
5440       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5441                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5442 
5443 
5444   // Then copy the newly loaded TOC anchor to the TOC pointer.
5445   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5446   Chain = TOCVal.getValue(0);
5447   Glue = TOCVal.getValue(1);
5448 
5449   // If the function call has an explicit 'nest' parameter, it takes the
5450   // place of the environment pointer.
5451   assert((!hasNest || !Subtarget.isAIXABI()) &&
5452          "Nest parameter is not supported on AIX.");
5453   if (!hasNest) {
5454     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5455     Chain = EnvVal.getValue(0);
5456     Glue = EnvVal.getValue(1);
5457   }
5458 
5459   // The rest of the indirect call sequence is the same as the non-descriptor
5460   // DAG.
5461   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5462 }
5463 
5464 static void
5465 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5466                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5467                   SelectionDAG &DAG,
5468                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5469                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5470                   const PPCSubtarget &Subtarget) {
5471   const bool IsPPC64 = Subtarget.isPPC64();
5472   // MVT for a general purpose register.
5473   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5474 
5475   // First operand is always the chain.
5476   Ops.push_back(Chain);
5477 
5478   // If it's a direct call pass the callee as the second operand.
5479   if (!CFlags.IsIndirect)
5480     Ops.push_back(Callee);
5481   else {
5482     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5483 
5484     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5485     // on the stack (this would have been done in `LowerCall_64SVR4` or
5486     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5487     // represents both the indirect branch and a load that restores the TOC
5488     // pointer from the linkage area. The operand for the TOC restore is an add
5489     // of the TOC save offset to the stack pointer. This must be the second
5490     // operand: after the chain input but before any other variadic arguments.
5491     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5492     // saved or used.
5493     if (isTOCSaveRestoreRequired(Subtarget)) {
5494       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5495 
5496       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5497       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5498       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5499       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5500       Ops.push_back(AddTOC);
5501     }
5502 
5503     // Add the register used for the environment pointer.
5504     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5505       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5506                                     RegVT));
5507 
5508 
5509     // Add CTR register as callee so a bctr can be emitted later.
5510     if (CFlags.IsTailCall)
5511       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5512   }
5513 
5514   // If this is a tail call add stack pointer delta.
5515   if (CFlags.IsTailCall)
5516     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5517 
5518   // Add argument registers to the end of the list so that they are known live
5519   // into the call.
5520   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5521     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5522                                   RegsToPass[i].second.getValueType()));
5523 
5524   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5525   // no way to mark dependencies as implicit here.
5526   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5527   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5528        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5529     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5530 
5531   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5532   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5533     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5534 
5535   // Add a register mask operand representing the call-preserved registers.
5536   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5537   const uint32_t *Mask =
5538       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5539   assert(Mask && "Missing call preserved mask for calling convention");
5540   Ops.push_back(DAG.getRegisterMask(Mask));
5541 
5542   // If the glue is valid, it is the last operand.
5543   if (Glue.getNode())
5544     Ops.push_back(Glue);
5545 }
5546 
5547 SDValue PPCTargetLowering::FinishCall(
5548     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5549     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5550     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5551     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5552     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5553 
5554   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5555       Subtarget.isAIXABI())
5556     setUsesTOCBasePtr(DAG);
5557 
5558   unsigned CallOpc =
5559       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5560                     Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5561 
5562   if (!CFlags.IsIndirect)
5563     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5564   else if (Subtarget.usesFunctionDescriptors())
5565     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5566                                   dl, CFlags.HasNest, Subtarget);
5567   else
5568     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5569 
5570   // Build the operand list for the call instruction.
5571   SmallVector<SDValue, 8> Ops;
5572   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5573                     SPDiff, Subtarget);
5574 
5575   // Emit tail call.
5576   if (CFlags.IsTailCall) {
5577     // Indirect tail call when using PC Relative calls do not have the same
5578     // constraints.
5579     assert(((Callee.getOpcode() == ISD::Register &&
5580              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5581             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5582             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5583             isa<ConstantSDNode>(Callee) ||
5584             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5585            "Expecting a global address, external symbol, absolute value, "
5586            "register or an indirect tail call when PC Relative calls are "
5587            "used.");
5588     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5589     assert(CallOpc == PPCISD::TC_RETURN &&
5590            "Unexpected call opcode for a tail call.");
5591     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5592     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5593   }
5594 
5595   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5596   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5597   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5598   Glue = Chain.getValue(1);
5599 
5600   // When performing tail call optimization the callee pops its arguments off
5601   // the stack. Account for this here so these bytes can be pushed back on in
5602   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5603   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5604                          getTargetMachine().Options.GuaranteedTailCallOpt)
5605                             ? NumBytes
5606                             : 0;
5607 
5608   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5609                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5610                              Glue, dl);
5611   Glue = Chain.getValue(1);
5612 
5613   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5614                          DAG, InVals);
5615 }
5616 
5617 SDValue
5618 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5619                              SmallVectorImpl<SDValue> &InVals) const {
5620   SelectionDAG &DAG                     = CLI.DAG;
5621   SDLoc &dl                             = CLI.DL;
5622   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5623   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5624   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5625   SDValue Chain                         = CLI.Chain;
5626   SDValue Callee                        = CLI.Callee;
5627   bool &isTailCall                      = CLI.IsTailCall;
5628   CallingConv::ID CallConv              = CLI.CallConv;
5629   bool isVarArg                         = CLI.IsVarArg;
5630   bool isPatchPoint                     = CLI.IsPatchPoint;
5631   const CallBase *CB                    = CLI.CB;
5632 
5633   if (isTailCall) {
5634     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5635       isTailCall = false;
5636     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5637       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5638           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5639     else
5640       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5641                                                      Ins, DAG);
5642     if (isTailCall) {
5643       ++NumTailCalls;
5644       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5645         ++NumSiblingCalls;
5646 
5647       // PC Relative calls no longer guarantee that the callee is a Global
5648       // Address Node. The callee could be an indirect tail call in which
5649       // case the SDValue for the callee could be a load (to load the address
5650       // of a function pointer) or it may be a register copy (to move the
5651       // address of the callee from a function parameter into a virtual
5652       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5653       assert((Subtarget.isUsingPCRelativeCalls() ||
5654               isa<GlobalAddressSDNode>(Callee)) &&
5655              "Callee should be an llvm::Function object.");
5656 
5657       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5658                         << "\nTCO callee: ");
5659       LLVM_DEBUG(Callee.dump());
5660     }
5661   }
5662 
5663   if (!isTailCall && CB && CB->isMustTailCall())
5664     report_fatal_error("failed to perform tail call elimination on a call "
5665                        "site marked musttail");
5666 
5667   // When long calls (i.e. indirect calls) are always used, calls are always
5668   // made via function pointer. If we have a function name, first translate it
5669   // into a pointer.
5670   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5671       !isTailCall)
5672     Callee = LowerGlobalAddress(Callee, DAG);
5673 
5674   CallFlags CFlags(
5675       CallConv, isTailCall, isVarArg, isPatchPoint,
5676       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5677       // hasNest
5678       Subtarget.is64BitELFABI() &&
5679           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5680       CLI.NoMerge);
5681 
5682   if (Subtarget.isAIXABI())
5683     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5684                          InVals, CB);
5685 
5686   assert(Subtarget.isSVR4ABI());
5687   if (Subtarget.isPPC64())
5688     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5689                             InVals, CB);
5690   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5691                           InVals, CB);
5692 }
5693 
5694 SDValue PPCTargetLowering::LowerCall_32SVR4(
5695     SDValue Chain, SDValue Callee, CallFlags CFlags,
5696     const SmallVectorImpl<ISD::OutputArg> &Outs,
5697     const SmallVectorImpl<SDValue> &OutVals,
5698     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5699     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5700     const CallBase *CB) const {
5701   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5702   // of the 32-bit SVR4 ABI stack frame layout.
5703 
5704   const CallingConv::ID CallConv = CFlags.CallConv;
5705   const bool IsVarArg = CFlags.IsVarArg;
5706   const bool IsTailCall = CFlags.IsTailCall;
5707 
5708   assert((CallConv == CallingConv::C ||
5709           CallConv == CallingConv::Cold ||
5710           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5711 
5712   const Align PtrAlign(4);
5713 
5714   MachineFunction &MF = DAG.getMachineFunction();
5715 
5716   // Mark this function as potentially containing a function that contains a
5717   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5718   // and restoring the callers stack pointer in this functions epilog. This is
5719   // done because by tail calling the called function might overwrite the value
5720   // in this function's (MF) stack pointer stack slot 0(SP).
5721   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5722       CallConv == CallingConv::Fast)
5723     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5724 
5725   // Count how many bytes are to be pushed on the stack, including the linkage
5726   // area, parameter list area and the part of the local variable space which
5727   // contains copies of aggregates which are passed by value.
5728 
5729   // Assign locations to all of the outgoing arguments.
5730   SmallVector<CCValAssign, 16> ArgLocs;
5731   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5732 
5733   // Reserve space for the linkage area on the stack.
5734   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5735                        PtrAlign);
5736   if (useSoftFloat())
5737     CCInfo.PreAnalyzeCallOperands(Outs);
5738 
5739   if (IsVarArg) {
5740     // Handle fixed and variable vector arguments differently.
5741     // Fixed vector arguments go into registers as long as registers are
5742     // available. Variable vector arguments always go into memory.
5743     unsigned NumArgs = Outs.size();
5744 
5745     for (unsigned i = 0; i != NumArgs; ++i) {
5746       MVT ArgVT = Outs[i].VT;
5747       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5748       bool Result;
5749 
5750       if (Outs[i].IsFixed) {
5751         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5752                                CCInfo);
5753       } else {
5754         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5755                                       ArgFlags, CCInfo);
5756       }
5757 
5758       if (Result) {
5759 #ifndef NDEBUG
5760         errs() << "Call operand #" << i << " has unhandled type "
5761              << EVT(ArgVT).getEVTString() << "\n";
5762 #endif
5763         llvm_unreachable(nullptr);
5764       }
5765     }
5766   } else {
5767     // All arguments are treated the same.
5768     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5769   }
5770   CCInfo.clearWasPPCF128();
5771 
5772   // Assign locations to all of the outgoing aggregate by value arguments.
5773   SmallVector<CCValAssign, 16> ByValArgLocs;
5774   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5775 
5776   // Reserve stack space for the allocations in CCInfo.
5777   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5778 
5779   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5780 
5781   // Size of the linkage area, parameter list area and the part of the local
5782   // space variable where copies of aggregates which are passed by value are
5783   // stored.
5784   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5785 
5786   // Calculate by how many bytes the stack has to be adjusted in case of tail
5787   // call optimization.
5788   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5789 
5790   // Adjust the stack pointer for the new arguments...
5791   // These operations are automatically eliminated by the prolog/epilog pass
5792   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5793   SDValue CallSeqStart = Chain;
5794 
5795   // Load the return address and frame pointer so it can be moved somewhere else
5796   // later.
5797   SDValue LROp, FPOp;
5798   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5799 
5800   // Set up a copy of the stack pointer for use loading and storing any
5801   // arguments that may not fit in the registers available for argument
5802   // passing.
5803   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5804 
5805   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5806   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5807   SmallVector<SDValue, 8> MemOpChains;
5808 
5809   bool seenFloatArg = false;
5810   // Walk the register/memloc assignments, inserting copies/loads.
5811   // i - Tracks the index into the list of registers allocated for the call
5812   // RealArgIdx - Tracks the index into the list of actual function arguments
5813   // j - Tracks the index into the list of byval arguments
5814   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5815        i != e;
5816        ++i, ++RealArgIdx) {
5817     CCValAssign &VA = ArgLocs[i];
5818     SDValue Arg = OutVals[RealArgIdx];
5819     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5820 
5821     if (Flags.isByVal()) {
5822       // Argument is an aggregate which is passed by value, thus we need to
5823       // create a copy of it in the local variable space of the current stack
5824       // frame (which is the stack frame of the caller) and pass the address of
5825       // this copy to the callee.
5826       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5827       CCValAssign &ByValVA = ByValArgLocs[j++];
5828       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5829 
5830       // Memory reserved in the local variable space of the callers stack frame.
5831       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5832 
5833       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5834       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5835                            StackPtr, PtrOff);
5836 
5837       // Create a copy of the argument in the local area of the current
5838       // stack frame.
5839       SDValue MemcpyCall =
5840         CreateCopyOfByValArgument(Arg, PtrOff,
5841                                   CallSeqStart.getNode()->getOperand(0),
5842                                   Flags, DAG, dl);
5843 
5844       // This must go outside the CALLSEQ_START..END.
5845       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5846                                                      SDLoc(MemcpyCall));
5847       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5848                              NewCallSeqStart.getNode());
5849       Chain = CallSeqStart = NewCallSeqStart;
5850 
5851       // Pass the address of the aggregate copy on the stack either in a
5852       // physical register or in the parameter list area of the current stack
5853       // frame to the callee.
5854       Arg = PtrOff;
5855     }
5856 
5857     // When useCRBits() is true, there can be i1 arguments.
5858     // It is because getRegisterType(MVT::i1) => MVT::i1,
5859     // and for other integer types getRegisterType() => MVT::i32.
5860     // Extend i1 and ensure callee will get i32.
5861     if (Arg.getValueType() == MVT::i1)
5862       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5863                         dl, MVT::i32, Arg);
5864 
5865     if (VA.isRegLoc()) {
5866       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5867       // Put argument in a physical register.
5868       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5869         bool IsLE = Subtarget.isLittleEndian();
5870         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5871                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5872         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5873         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5874                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5875         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5876                              SVal.getValue(0)));
5877       } else
5878         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5879     } else {
5880       // Put argument in the parameter list area of the current stack frame.
5881       assert(VA.isMemLoc());
5882       unsigned LocMemOffset = VA.getLocMemOffset();
5883 
5884       if (!IsTailCall) {
5885         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5886         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5887                              StackPtr, PtrOff);
5888 
5889         MemOpChains.push_back(
5890             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5891       } else {
5892         // Calculate and remember argument location.
5893         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5894                                  TailCallArguments);
5895       }
5896     }
5897   }
5898 
5899   if (!MemOpChains.empty())
5900     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5901 
5902   // Build a sequence of copy-to-reg nodes chained together with token chain
5903   // and flag operands which copy the outgoing args into the appropriate regs.
5904   SDValue InFlag;
5905   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5906     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5907                              RegsToPass[i].second, InFlag);
5908     InFlag = Chain.getValue(1);
5909   }
5910 
5911   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5912   // registers.
5913   if (IsVarArg) {
5914     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5915     SDValue Ops[] = { Chain, InFlag };
5916 
5917     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5918                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5919 
5920     InFlag = Chain.getValue(1);
5921   }
5922 
5923   if (IsTailCall)
5924     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5925                     TailCallArguments);
5926 
5927   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5928                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5929 }
5930 
5931 // Copy an argument into memory, being careful to do this outside the
5932 // call sequence for the call to which the argument belongs.
5933 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5934     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5935     SelectionDAG &DAG, const SDLoc &dl) const {
5936   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5937                         CallSeqStart.getNode()->getOperand(0),
5938                         Flags, DAG, dl);
5939   // The MEMCPY must go outside the CALLSEQ_START..END.
5940   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5941   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5942                                                  SDLoc(MemcpyCall));
5943   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5944                          NewCallSeqStart.getNode());
5945   return NewCallSeqStart;
5946 }
5947 
5948 SDValue PPCTargetLowering::LowerCall_64SVR4(
5949     SDValue Chain, SDValue Callee, CallFlags CFlags,
5950     const SmallVectorImpl<ISD::OutputArg> &Outs,
5951     const SmallVectorImpl<SDValue> &OutVals,
5952     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5953     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5954     const CallBase *CB) const {
5955   bool isELFv2ABI = Subtarget.isELFv2ABI();
5956   bool isLittleEndian = Subtarget.isLittleEndian();
5957   unsigned NumOps = Outs.size();
5958   bool IsSibCall = false;
5959   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5960 
5961   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5962   unsigned PtrByteSize = 8;
5963 
5964   MachineFunction &MF = DAG.getMachineFunction();
5965 
5966   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5967     IsSibCall = true;
5968 
5969   // Mark this function as potentially containing a function that contains a
5970   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5971   // and restoring the callers stack pointer in this functions epilog. This is
5972   // done because by tail calling the called function might overwrite the value
5973   // in this function's (MF) stack pointer stack slot 0(SP).
5974   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5975     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5976 
5977   assert(!(IsFastCall && CFlags.IsVarArg) &&
5978          "fastcc not supported on varargs functions");
5979 
5980   // Count how many bytes are to be pushed on the stack, including the linkage
5981   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5982   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5983   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5984   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5985   unsigned NumBytes = LinkageSize;
5986   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5987 
5988   static const MCPhysReg GPR[] = {
5989     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5990     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5991   };
5992   static const MCPhysReg VR[] = {
5993     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5994     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5995   };
5996 
5997   const unsigned NumGPRs = array_lengthof(GPR);
5998   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5999   const unsigned NumVRs  = array_lengthof(VR);
6000 
6001   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6002   // can be passed to the callee in registers.
6003   // For the fast calling convention, there is another check below.
6004   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6005   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6006   if (!HasParameterArea) {
6007     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6008     unsigned AvailableFPRs = NumFPRs;
6009     unsigned AvailableVRs = NumVRs;
6010     unsigned NumBytesTmp = NumBytes;
6011     for (unsigned i = 0; i != NumOps; ++i) {
6012       if (Outs[i].Flags.isNest()) continue;
6013       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6014                                  PtrByteSize, LinkageSize, ParamAreaSize,
6015                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6016         HasParameterArea = true;
6017     }
6018   }
6019 
6020   // When using the fast calling convention, we don't provide backing for
6021   // arguments that will be in registers.
6022   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6023 
6024   // Avoid allocating parameter area for fastcc functions if all the arguments
6025   // can be passed in the registers.
6026   if (IsFastCall)
6027     HasParameterArea = false;
6028 
6029   // Add up all the space actually used.
6030   for (unsigned i = 0; i != NumOps; ++i) {
6031     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6032     EVT ArgVT = Outs[i].VT;
6033     EVT OrigVT = Outs[i].ArgVT;
6034 
6035     if (Flags.isNest())
6036       continue;
6037 
6038     if (IsFastCall) {
6039       if (Flags.isByVal()) {
6040         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6041         if (NumGPRsUsed > NumGPRs)
6042           HasParameterArea = true;
6043       } else {
6044         switch (ArgVT.getSimpleVT().SimpleTy) {
6045         default: llvm_unreachable("Unexpected ValueType for argument!");
6046         case MVT::i1:
6047         case MVT::i32:
6048         case MVT::i64:
6049           if (++NumGPRsUsed <= NumGPRs)
6050             continue;
6051           break;
6052         case MVT::v4i32:
6053         case MVT::v8i16:
6054         case MVT::v16i8:
6055         case MVT::v2f64:
6056         case MVT::v2i64:
6057         case MVT::v1i128:
6058         case MVT::f128:
6059           if (++NumVRsUsed <= NumVRs)
6060             continue;
6061           break;
6062         case MVT::v4f32:
6063           if (++NumVRsUsed <= NumVRs)
6064             continue;
6065           break;
6066         case MVT::f32:
6067         case MVT::f64:
6068           if (++NumFPRsUsed <= NumFPRs)
6069             continue;
6070           break;
6071         }
6072         HasParameterArea = true;
6073       }
6074     }
6075 
6076     /* Respect alignment of argument on the stack.  */
6077     auto Alignement =
6078         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6079     NumBytes = alignTo(NumBytes, Alignement);
6080 
6081     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6082     if (Flags.isInConsecutiveRegsLast())
6083       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6084   }
6085 
6086   unsigned NumBytesActuallyUsed = NumBytes;
6087 
6088   // In the old ELFv1 ABI,
6089   // the prolog code of the callee may store up to 8 GPR argument registers to
6090   // the stack, allowing va_start to index over them in memory if its varargs.
6091   // Because we cannot tell if this is needed on the caller side, we have to
6092   // conservatively assume that it is needed.  As such, make sure we have at
6093   // least enough stack space for the caller to store the 8 GPRs.
6094   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6095   // really requires memory operands, e.g. a vararg function.
6096   if (HasParameterArea)
6097     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6098   else
6099     NumBytes = LinkageSize;
6100 
6101   // Tail call needs the stack to be aligned.
6102   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6103     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6104 
6105   int SPDiff = 0;
6106 
6107   // Calculate by how many bytes the stack has to be adjusted in case of tail
6108   // call optimization.
6109   if (!IsSibCall)
6110     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6111 
6112   // To protect arguments on the stack from being clobbered in a tail call,
6113   // force all the loads to happen before doing any other lowering.
6114   if (CFlags.IsTailCall)
6115     Chain = DAG.getStackArgumentTokenFactor(Chain);
6116 
6117   // Adjust the stack pointer for the new arguments...
6118   // These operations are automatically eliminated by the prolog/epilog pass
6119   if (!IsSibCall)
6120     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6121   SDValue CallSeqStart = Chain;
6122 
6123   // Load the return address and frame pointer so it can be move somewhere else
6124   // later.
6125   SDValue LROp, FPOp;
6126   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6127 
6128   // Set up a copy of the stack pointer for use loading and storing any
6129   // arguments that may not fit in the registers available for argument
6130   // passing.
6131   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6132 
6133   // Figure out which arguments are going to go in registers, and which in
6134   // memory.  Also, if this is a vararg function, floating point operations
6135   // must be stored to our stack, and loaded into integer regs as well, if
6136   // any integer regs are available for argument passing.
6137   unsigned ArgOffset = LinkageSize;
6138 
6139   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6140   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6141 
6142   SmallVector<SDValue, 8> MemOpChains;
6143   for (unsigned i = 0; i != NumOps; ++i) {
6144     SDValue Arg = OutVals[i];
6145     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6146     EVT ArgVT = Outs[i].VT;
6147     EVT OrigVT = Outs[i].ArgVT;
6148 
6149     // PtrOff will be used to store the current argument to the stack if a
6150     // register cannot be found for it.
6151     SDValue PtrOff;
6152 
6153     // We re-align the argument offset for each argument, except when using the
6154     // fast calling convention, when we need to make sure we do that only when
6155     // we'll actually use a stack slot.
6156     auto ComputePtrOff = [&]() {
6157       /* Respect alignment of argument on the stack.  */
6158       auto Alignment =
6159           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6160       ArgOffset = alignTo(ArgOffset, Alignment);
6161 
6162       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6163 
6164       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6165     };
6166 
6167     if (!IsFastCall) {
6168       ComputePtrOff();
6169 
6170       /* Compute GPR index associated with argument offset.  */
6171       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6172       GPR_idx = std::min(GPR_idx, NumGPRs);
6173     }
6174 
6175     // Promote integers to 64-bit values.
6176     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6177       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6178       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6179       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6180     }
6181 
6182     // FIXME memcpy is used way more than necessary.  Correctness first.
6183     // Note: "by value" is code for passing a structure by value, not
6184     // basic types.
6185     if (Flags.isByVal()) {
6186       // Note: Size includes alignment padding, so
6187       //   struct x { short a; char b; }
6188       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6189       // These are the proper values we need for right-justifying the
6190       // aggregate in a parameter register.
6191       unsigned Size = Flags.getByValSize();
6192 
6193       // An empty aggregate parameter takes up no storage and no
6194       // registers.
6195       if (Size == 0)
6196         continue;
6197 
6198       if (IsFastCall)
6199         ComputePtrOff();
6200 
6201       // All aggregates smaller than 8 bytes must be passed right-justified.
6202       if (Size==1 || Size==2 || Size==4) {
6203         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6204         if (GPR_idx != NumGPRs) {
6205           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6206                                         MachinePointerInfo(), VT);
6207           MemOpChains.push_back(Load.getValue(1));
6208           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6209 
6210           ArgOffset += PtrByteSize;
6211           continue;
6212         }
6213       }
6214 
6215       if (GPR_idx == NumGPRs && Size < 8) {
6216         SDValue AddPtr = PtrOff;
6217         if (!isLittleEndian) {
6218           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6219                                           PtrOff.getValueType());
6220           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6221         }
6222         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6223                                                           CallSeqStart,
6224                                                           Flags, DAG, dl);
6225         ArgOffset += PtrByteSize;
6226         continue;
6227       }
6228       // Copy the object to parameter save area if it can not be entirely passed
6229       // by registers.
6230       // FIXME: we only need to copy the parts which need to be passed in
6231       // parameter save area. For the parts passed by registers, we don't need
6232       // to copy them to the stack although we need to allocate space for them
6233       // in parameter save area.
6234       if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6235         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6236                                                           CallSeqStart,
6237                                                           Flags, DAG, dl);
6238 
6239       // When a register is available, pass a small aggregate right-justified.
6240       if (Size < 8 && GPR_idx != NumGPRs) {
6241         // The easiest way to get this right-justified in a register
6242         // is to copy the structure into the rightmost portion of a
6243         // local variable slot, then load the whole slot into the
6244         // register.
6245         // FIXME: The memcpy seems to produce pretty awful code for
6246         // small aggregates, particularly for packed ones.
6247         // FIXME: It would be preferable to use the slot in the
6248         // parameter save area instead of a new local variable.
6249         SDValue AddPtr = PtrOff;
6250         if (!isLittleEndian) {
6251           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6252           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6253         }
6254         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6255                                                           CallSeqStart,
6256                                                           Flags, DAG, dl);
6257 
6258         // Load the slot into the register.
6259         SDValue Load =
6260             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6261         MemOpChains.push_back(Load.getValue(1));
6262         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6263 
6264         // Done with this argument.
6265         ArgOffset += PtrByteSize;
6266         continue;
6267       }
6268 
6269       // For aggregates larger than PtrByteSize, copy the pieces of the
6270       // object that fit into registers from the parameter save area.
6271       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6272         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6273         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6274         if (GPR_idx != NumGPRs) {
6275           unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6276           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6277           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6278                                         MachinePointerInfo(), ObjType);
6279 
6280           MemOpChains.push_back(Load.getValue(1));
6281           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6282           ArgOffset += PtrByteSize;
6283         } else {
6284           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6285           break;
6286         }
6287       }
6288       continue;
6289     }
6290 
6291     switch (Arg.getSimpleValueType().SimpleTy) {
6292     default: llvm_unreachable("Unexpected ValueType for argument!");
6293     case MVT::i1:
6294     case MVT::i32:
6295     case MVT::i64:
6296       if (Flags.isNest()) {
6297         // The 'nest' parameter, if any, is passed in R11.
6298         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6299         break;
6300       }
6301 
6302       // These can be scalar arguments or elements of an integer array type
6303       // passed directly.  Clang may use those instead of "byval" aggregate
6304       // types to avoid forcing arguments to memory unnecessarily.
6305       if (GPR_idx != NumGPRs) {
6306         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6307       } else {
6308         if (IsFastCall)
6309           ComputePtrOff();
6310 
6311         assert(HasParameterArea &&
6312                "Parameter area must exist to pass an argument in memory.");
6313         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6314                          true, CFlags.IsTailCall, false, MemOpChains,
6315                          TailCallArguments, dl);
6316         if (IsFastCall)
6317           ArgOffset += PtrByteSize;
6318       }
6319       if (!IsFastCall)
6320         ArgOffset += PtrByteSize;
6321       break;
6322     case MVT::f32:
6323     case MVT::f64: {
6324       // These can be scalar arguments or elements of a float array type
6325       // passed directly.  The latter are used to implement ELFv2 homogenous
6326       // float aggregates.
6327 
6328       // Named arguments go into FPRs first, and once they overflow, the
6329       // remaining arguments go into GPRs and then the parameter save area.
6330       // Unnamed arguments for vararg functions always go to GPRs and
6331       // then the parameter save area.  For now, put all arguments to vararg
6332       // routines always in both locations (FPR *and* GPR or stack slot).
6333       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6334       bool NeededLoad = false;
6335 
6336       // First load the argument into the next available FPR.
6337       if (FPR_idx != NumFPRs)
6338         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6339 
6340       // Next, load the argument into GPR or stack slot if needed.
6341       if (!NeedGPROrStack)
6342         ;
6343       else if (GPR_idx != NumGPRs && !IsFastCall) {
6344         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6345         // once we support fp <-> gpr moves.
6346 
6347         // In the non-vararg case, this can only ever happen in the
6348         // presence of f32 array types, since otherwise we never run
6349         // out of FPRs before running out of GPRs.
6350         SDValue ArgVal;
6351 
6352         // Double values are always passed in a single GPR.
6353         if (Arg.getValueType() != MVT::f32) {
6354           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6355 
6356         // Non-array float values are extended and passed in a GPR.
6357         } else if (!Flags.isInConsecutiveRegs()) {
6358           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6359           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6360 
6361         // If we have an array of floats, we collect every odd element
6362         // together with its predecessor into one GPR.
6363         } else if (ArgOffset % PtrByteSize != 0) {
6364           SDValue Lo, Hi;
6365           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6366           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6367           if (!isLittleEndian)
6368             std::swap(Lo, Hi);
6369           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6370 
6371         // The final element, if even, goes into the first half of a GPR.
6372         } else if (Flags.isInConsecutiveRegsLast()) {
6373           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6374           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6375           if (!isLittleEndian)
6376             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6377                                  DAG.getConstant(32, dl, MVT::i32));
6378 
6379         // Non-final even elements are skipped; they will be handled
6380         // together the with subsequent argument on the next go-around.
6381         } else
6382           ArgVal = SDValue();
6383 
6384         if (ArgVal.getNode())
6385           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6386       } else {
6387         if (IsFastCall)
6388           ComputePtrOff();
6389 
6390         // Single-precision floating-point values are mapped to the
6391         // second (rightmost) word of the stack doubleword.
6392         if (Arg.getValueType() == MVT::f32 &&
6393             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6394           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6395           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6396         }
6397 
6398         assert(HasParameterArea &&
6399                "Parameter area must exist to pass an argument in memory.");
6400         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6401                          true, CFlags.IsTailCall, false, MemOpChains,
6402                          TailCallArguments, dl);
6403 
6404         NeededLoad = true;
6405       }
6406       // When passing an array of floats, the array occupies consecutive
6407       // space in the argument area; only round up to the next doubleword
6408       // at the end of the array.  Otherwise, each float takes 8 bytes.
6409       if (!IsFastCall || NeededLoad) {
6410         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6411                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6412         if (Flags.isInConsecutiveRegsLast())
6413           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6414       }
6415       break;
6416     }
6417     case MVT::v4f32:
6418     case MVT::v4i32:
6419     case MVT::v8i16:
6420     case MVT::v16i8:
6421     case MVT::v2f64:
6422     case MVT::v2i64:
6423     case MVT::v1i128:
6424     case MVT::f128:
6425       // These can be scalar arguments or elements of a vector array type
6426       // passed directly.  The latter are used to implement ELFv2 homogenous
6427       // vector aggregates.
6428 
6429       // For a varargs call, named arguments go into VRs or on the stack as
6430       // usual; unnamed arguments always go to the stack or the corresponding
6431       // GPRs when within range.  For now, we always put the value in both
6432       // locations (or even all three).
6433       if (CFlags.IsVarArg) {
6434         assert(HasParameterArea &&
6435                "Parameter area must exist if we have a varargs call.");
6436         // We could elide this store in the case where the object fits
6437         // entirely in R registers.  Maybe later.
6438         SDValue Store =
6439             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6440         MemOpChains.push_back(Store);
6441         if (VR_idx != NumVRs) {
6442           SDValue Load =
6443               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6444           MemOpChains.push_back(Load.getValue(1));
6445           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6446         }
6447         ArgOffset += 16;
6448         for (unsigned i=0; i<16; i+=PtrByteSize) {
6449           if (GPR_idx == NumGPRs)
6450             break;
6451           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6452                                    DAG.getConstant(i, dl, PtrVT));
6453           SDValue Load =
6454               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6455           MemOpChains.push_back(Load.getValue(1));
6456           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6457         }
6458         break;
6459       }
6460 
6461       // Non-varargs Altivec params go into VRs or on the stack.
6462       if (VR_idx != NumVRs) {
6463         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6464       } else {
6465         if (IsFastCall)
6466           ComputePtrOff();
6467 
6468         assert(HasParameterArea &&
6469                "Parameter area must exist to pass an argument in memory.");
6470         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6471                          true, CFlags.IsTailCall, true, MemOpChains,
6472                          TailCallArguments, dl);
6473         if (IsFastCall)
6474           ArgOffset += 16;
6475       }
6476 
6477       if (!IsFastCall)
6478         ArgOffset += 16;
6479       break;
6480     }
6481   }
6482 
6483   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6484          "mismatch in size of parameter area");
6485   (void)NumBytesActuallyUsed;
6486 
6487   if (!MemOpChains.empty())
6488     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6489 
6490   // Check if this is an indirect call (MTCTR/BCTRL).
6491   // See prepareDescriptorIndirectCall and buildCallOperands for more
6492   // information about calls through function pointers in the 64-bit SVR4 ABI.
6493   if (CFlags.IsIndirect) {
6494     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6495     // caller in the TOC save area.
6496     if (isTOCSaveRestoreRequired(Subtarget)) {
6497       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6498       // Load r2 into a virtual register and store it to the TOC save area.
6499       setUsesTOCBasePtr(DAG);
6500       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6501       // TOC save area offset.
6502       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6503       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6504       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6505       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6506                            MachinePointerInfo::getStack(
6507                                DAG.getMachineFunction(), TOCSaveOffset));
6508     }
6509     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6510     // This does not mean the MTCTR instruction must use R12; it's easier
6511     // to model this as an extra parameter, so do that.
6512     if (isELFv2ABI && !CFlags.IsPatchPoint)
6513       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6514   }
6515 
6516   // Build a sequence of copy-to-reg nodes chained together with token chain
6517   // and flag operands which copy the outgoing args into the appropriate regs.
6518   SDValue InFlag;
6519   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6520     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6521                              RegsToPass[i].second, InFlag);
6522     InFlag = Chain.getValue(1);
6523   }
6524 
6525   if (CFlags.IsTailCall && !IsSibCall)
6526     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6527                     TailCallArguments);
6528 
6529   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6530                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6531 }
6532 
6533 // Returns true when the shadow of a general purpose argument register
6534 // in the parameter save area is aligned to at least 'RequiredAlign'.
6535 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6536   assert(RequiredAlign.value() <= 16 &&
6537          "Required alignment greater than stack alignment.");
6538   switch (Reg) {
6539   default:
6540     report_fatal_error("called on invalid register.");
6541   case PPC::R5:
6542   case PPC::R9:
6543   case PPC::X3:
6544   case PPC::X5:
6545   case PPC::X7:
6546   case PPC::X9:
6547     // These registers are 16 byte aligned which is the most strict aligment
6548     // we can support.
6549     return true;
6550   case PPC::R3:
6551   case PPC::R7:
6552   case PPC::X4:
6553   case PPC::X6:
6554   case PPC::X8:
6555   case PPC::X10:
6556     // The shadow of these registers in the PSA is 8 byte aligned.
6557     return RequiredAlign <= 8;
6558   case PPC::R4:
6559   case PPC::R6:
6560   case PPC::R8:
6561   case PPC::R10:
6562     return RequiredAlign <= 4;
6563   }
6564 }
6565 
6566 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6567                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6568                    CCState &S) {
6569   AIXCCState &State = static_cast<AIXCCState &>(S);
6570   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6571       State.getMachineFunction().getSubtarget());
6572   const bool IsPPC64 = Subtarget.isPPC64();
6573   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6574   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6575 
6576   if (ValVT == MVT::f128)
6577     report_fatal_error("f128 is unimplemented on AIX.");
6578 
6579   if (ArgFlags.isNest())
6580     report_fatal_error("Nest arguments are unimplemented.");
6581 
6582   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6583                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6584                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6585   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6586                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6587                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6588 
6589   static const MCPhysReg VR[] = {// Vector registers.
6590                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6591                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6592                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6593 
6594   if (ArgFlags.isByVal()) {
6595     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6596       report_fatal_error("Pass-by-value arguments with alignment greater than "
6597                          "register width are not supported.");
6598 
6599     const unsigned ByValSize = ArgFlags.getByValSize();
6600 
6601     // An empty aggregate parameter takes up no storage and no registers,
6602     // but needs a MemLoc for a stack slot for the formal arguments side.
6603     if (ByValSize == 0) {
6604       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6605                                        State.getNextStackOffset(), RegVT,
6606                                        LocInfo));
6607       return false;
6608     }
6609 
6610     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6611     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6612     for (const unsigned E = Offset + StackSize; Offset < E;
6613          Offset += PtrAlign.value()) {
6614       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6615         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6616       else {
6617         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6618                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6619                                          LocInfo));
6620         break;
6621       }
6622     }
6623     return false;
6624   }
6625 
6626   // Arguments always reserve parameter save area.
6627   switch (ValVT.SimpleTy) {
6628   default:
6629     report_fatal_error("Unhandled value type for argument.");
6630   case MVT::i64:
6631     // i64 arguments should have been split to i32 for PPC32.
6632     assert(IsPPC64 && "PPC32 should have split i64 values.");
6633     LLVM_FALLTHROUGH;
6634   case MVT::i1:
6635   case MVT::i32: {
6636     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6637     // AIX integer arguments are always passed in register width.
6638     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6639       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6640                                   : CCValAssign::LocInfo::ZExt;
6641     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6642       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6643     else
6644       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6645 
6646     return false;
6647   }
6648   case MVT::f32:
6649   case MVT::f64: {
6650     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6651     const unsigned StoreSize = LocVT.getStoreSize();
6652     // Floats are always 4-byte aligned in the PSA on AIX.
6653     // This includes f64 in 64-bit mode for ABI compatibility.
6654     const unsigned Offset =
6655         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6656     unsigned FReg = State.AllocateReg(FPR);
6657     if (FReg)
6658       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6659 
6660     // Reserve and initialize GPRs or initialize the PSA as required.
6661     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6662       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6663         assert(FReg && "An FPR should be available when a GPR is reserved.");
6664         if (State.isVarArg()) {
6665           // Successfully reserved GPRs are only initialized for vararg calls.
6666           // Custom handling is required for:
6667           //   f64 in PPC32 needs to be split into 2 GPRs.
6668           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6669           State.addLoc(
6670               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6671         }
6672       } else {
6673         // If there are insufficient GPRs, the PSA needs to be initialized.
6674         // Initialization occurs even if an FPR was initialized for
6675         // compatibility with the AIX XL compiler. The full memory for the
6676         // argument will be initialized even if a prior word is saved in GPR.
6677         // A custom memLoc is used when the argument also passes in FPR so
6678         // that the callee handling can skip over it easily.
6679         State.addLoc(
6680             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6681                                              LocInfo)
6682                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6683         break;
6684       }
6685     }
6686 
6687     return false;
6688   }
6689   case MVT::v4f32:
6690   case MVT::v4i32:
6691   case MVT::v8i16:
6692   case MVT::v16i8:
6693   case MVT::v2i64:
6694   case MVT::v2f64:
6695   case MVT::v1i128: {
6696     const unsigned VecSize = 16;
6697     const Align VecAlign(VecSize);
6698 
6699     if (!State.isVarArg()) {
6700       // If there are vector registers remaining we don't consume any stack
6701       // space.
6702       if (unsigned VReg = State.AllocateReg(VR)) {
6703         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6704         return false;
6705       }
6706       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6707       // might be allocated in the portion of the PSA that is shadowed by the
6708       // GPRs.
6709       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6710       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6711       return false;
6712     }
6713 
6714     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6715     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6716 
6717     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6718     // Burn any underaligned registers and their shadowed stack space until
6719     // we reach the required alignment.
6720     while (NextRegIndex != GPRs.size() &&
6721            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6722       // Shadow allocate register and its stack shadow.
6723       unsigned Reg = State.AllocateReg(GPRs);
6724       State.AllocateStack(PtrSize, PtrAlign);
6725       assert(Reg && "Allocating register unexpectedly failed.");
6726       (void)Reg;
6727       NextRegIndex = State.getFirstUnallocated(GPRs);
6728     }
6729 
6730     // Vectors that are passed as fixed arguments are handled differently.
6731     // They are passed in VRs if any are available (unlike arguments passed
6732     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6733     // functions)
6734     if (State.isFixed(ValNo)) {
6735       if (unsigned VReg = State.AllocateReg(VR)) {
6736         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6737         // Shadow allocate GPRs and stack space even though we pass in a VR.
6738         for (unsigned I = 0; I != VecSize; I += PtrSize)
6739           State.AllocateReg(GPRs);
6740         State.AllocateStack(VecSize, VecAlign);
6741         return false;
6742       }
6743       // No vector registers remain so pass on the stack.
6744       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6745       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6746       return false;
6747     }
6748 
6749     // If all GPRS are consumed then we pass the argument fully on the stack.
6750     if (NextRegIndex == GPRs.size()) {
6751       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6752       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6753       return false;
6754     }
6755 
6756     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6757     // half of the argument, and then need to pass the remaining half on the
6758     // stack.
6759     if (GPRs[NextRegIndex] == PPC::R9) {
6760       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6761       State.addLoc(
6762           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6763 
6764       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6765       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6766       assert(FirstReg && SecondReg &&
6767              "Allocating R9 or R10 unexpectedly failed.");
6768       State.addLoc(
6769           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6770       State.addLoc(
6771           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6772       return false;
6773     }
6774 
6775     // We have enough GPRs to fully pass the vector argument, and we have
6776     // already consumed any underaligned registers. Start with the custom
6777     // MemLoc and then the custom RegLocs.
6778     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6779     State.addLoc(
6780         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6781     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6782       const unsigned Reg = State.AllocateReg(GPRs);
6783       assert(Reg && "Failed to allocated register for vararg vector argument");
6784       State.addLoc(
6785           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6786     }
6787     return false;
6788   }
6789   }
6790   return true;
6791 }
6792 
6793 // So far, this function is only used by LowerFormalArguments_AIX()
6794 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6795                                                     bool IsPPC64,
6796                                                     bool HasP8Vector,
6797                                                     bool HasVSX) {
6798   assert((IsPPC64 || SVT != MVT::i64) &&
6799          "i64 should have been split for 32-bit codegen.");
6800 
6801   switch (SVT) {
6802   default:
6803     report_fatal_error("Unexpected value type for formal argument");
6804   case MVT::i1:
6805   case MVT::i32:
6806   case MVT::i64:
6807     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6808   case MVT::f32:
6809     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6810   case MVT::f64:
6811     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6812   case MVT::v4f32:
6813   case MVT::v4i32:
6814   case MVT::v8i16:
6815   case MVT::v16i8:
6816   case MVT::v2i64:
6817   case MVT::v2f64:
6818   case MVT::v1i128:
6819     return &PPC::VRRCRegClass;
6820   }
6821 }
6822 
6823 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6824                                         SelectionDAG &DAG, SDValue ArgValue,
6825                                         MVT LocVT, const SDLoc &dl) {
6826   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6827   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6828 
6829   if (Flags.isSExt())
6830     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6831                            DAG.getValueType(ValVT));
6832   else if (Flags.isZExt())
6833     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6834                            DAG.getValueType(ValVT));
6835 
6836   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6837 }
6838 
6839 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6840   const unsigned LASize = FL->getLinkageSize();
6841 
6842   if (PPC::GPRCRegClass.contains(Reg)) {
6843     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6844            "Reg must be a valid argument register!");
6845     return LASize + 4 * (Reg - PPC::R3);
6846   }
6847 
6848   if (PPC::G8RCRegClass.contains(Reg)) {
6849     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6850            "Reg must be a valid argument register!");
6851     return LASize + 8 * (Reg - PPC::X3);
6852   }
6853 
6854   llvm_unreachable("Only general purpose registers expected.");
6855 }
6856 
6857 //   AIX ABI Stack Frame Layout:
6858 //
6859 //   Low Memory +--------------------------------------------+
6860 //   SP   +---> | Back chain                                 | ---+
6861 //        |     +--------------------------------------------+    |
6862 //        |     | Saved Condition Register                   |    |
6863 //        |     +--------------------------------------------+    |
6864 //        |     | Saved Linkage Register                     |    |
6865 //        |     +--------------------------------------------+    | Linkage Area
6866 //        |     | Reserved for compilers                     |    |
6867 //        |     +--------------------------------------------+    |
6868 //        |     | Reserved for binders                       |    |
6869 //        |     +--------------------------------------------+    |
6870 //        |     | Saved TOC pointer                          | ---+
6871 //        |     +--------------------------------------------+
6872 //        |     | Parameter save area                        |
6873 //        |     +--------------------------------------------+
6874 //        |     | Alloca space                               |
6875 //        |     +--------------------------------------------+
6876 //        |     | Local variable space                       |
6877 //        |     +--------------------------------------------+
6878 //        |     | Float/int conversion temporary             |
6879 //        |     +--------------------------------------------+
6880 //        |     | Save area for AltiVec registers            |
6881 //        |     +--------------------------------------------+
6882 //        |     | AltiVec alignment padding                  |
6883 //        |     +--------------------------------------------+
6884 //        |     | Save area for VRSAVE register              |
6885 //        |     +--------------------------------------------+
6886 //        |     | Save area for General Purpose registers    |
6887 //        |     +--------------------------------------------+
6888 //        |     | Save area for Floating Point registers     |
6889 //        |     +--------------------------------------------+
6890 //        +---- | Back chain                                 |
6891 // High Memory  +--------------------------------------------+
6892 //
6893 //  Specifications:
6894 //  AIX 7.2 Assembler Language Reference
6895 //  Subroutine linkage convention
6896 
6897 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6898     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6899     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6900     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6901 
6902   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6903           CallConv == CallingConv::Fast) &&
6904          "Unexpected calling convention!");
6905 
6906   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6907     report_fatal_error("Tail call support is unimplemented on AIX.");
6908 
6909   if (useSoftFloat())
6910     report_fatal_error("Soft float support is unimplemented on AIX.");
6911 
6912   const PPCSubtarget &Subtarget =
6913       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6914 
6915   const bool IsPPC64 = Subtarget.isPPC64();
6916   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6917 
6918   // Assign locations to all of the incoming arguments.
6919   SmallVector<CCValAssign, 16> ArgLocs;
6920   MachineFunction &MF = DAG.getMachineFunction();
6921   MachineFrameInfo &MFI = MF.getFrameInfo();
6922   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6923   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6924 
6925   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6926   // Reserve space for the linkage area on the stack.
6927   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6928   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6929   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6930 
6931   SmallVector<SDValue, 8> MemOps;
6932 
6933   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6934     CCValAssign &VA = ArgLocs[I++];
6935     MVT LocVT = VA.getLocVT();
6936     MVT ValVT = VA.getValVT();
6937     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6938     // For compatibility with the AIX XL compiler, the float args in the
6939     // parameter save area are initialized even if the argument is available
6940     // in register.  The caller is required to initialize both the register
6941     // and memory, however, the callee can choose to expect it in either.
6942     // The memloc is dismissed here because the argument is retrieved from
6943     // the register.
6944     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6945       continue;
6946 
6947     auto HandleMemLoc = [&]() {
6948       const unsigned LocSize = LocVT.getStoreSize();
6949       const unsigned ValSize = ValVT.getStoreSize();
6950       assert((ValSize <= LocSize) &&
6951              "Object size is larger than size of MemLoc");
6952       int CurArgOffset = VA.getLocMemOffset();
6953       // Objects are right-justified because AIX is big-endian.
6954       if (LocSize > ValSize)
6955         CurArgOffset += LocSize - ValSize;
6956       // Potential tail calls could cause overwriting of argument stack slots.
6957       const bool IsImmutable =
6958           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6959             (CallConv == CallingConv::Fast));
6960       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6961       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6962       SDValue ArgValue =
6963           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6964       InVals.push_back(ArgValue);
6965     };
6966 
6967     // Vector arguments to VaArg functions are passed both on the stack, and
6968     // in any available GPRs. Load the value from the stack and add the GPRs
6969     // as live ins.
6970     if (VA.isMemLoc() && VA.needsCustom()) {
6971       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6972       assert(isVarArg && "Only use custom memloc for vararg.");
6973       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6974       // matching custom RegLocs.
6975       const unsigned OriginalValNo = VA.getValNo();
6976       (void)OriginalValNo;
6977 
6978       auto HandleCustomVecRegLoc = [&]() {
6979         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6980                "Missing custom RegLoc.");
6981         VA = ArgLocs[I++];
6982         assert(VA.getValVT().isVector() &&
6983                "Unexpected Val type for custom RegLoc.");
6984         assert(VA.getValNo() == OriginalValNo &&
6985                "ValNo mismatch between custom MemLoc and RegLoc.");
6986         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6987         MF.addLiveIn(VA.getLocReg(),
6988                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6989                                        Subtarget.hasVSX()));
6990       };
6991 
6992       HandleMemLoc();
6993       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
6994       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
6995       // R10.
6996       HandleCustomVecRegLoc();
6997       HandleCustomVecRegLoc();
6998 
6999       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7000       // we passed the vector in R5, R6, R7 and R8.
7001       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7002         assert(!IsPPC64 &&
7003                "Only 2 custom RegLocs expected for 64-bit codegen.");
7004         HandleCustomVecRegLoc();
7005         HandleCustomVecRegLoc();
7006       }
7007 
7008       continue;
7009     }
7010 
7011     if (VA.isRegLoc()) {
7012       if (VA.getValVT().isScalarInteger())
7013         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7014       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7015         switch (VA.getValVT().SimpleTy) {
7016         default:
7017           report_fatal_error("Unhandled value type for argument.");
7018         case MVT::f32:
7019           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7020           break;
7021         case MVT::f64:
7022           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7023           break;
7024         }
7025       } else if (VA.getValVT().isVector()) {
7026         switch (VA.getValVT().SimpleTy) {
7027         default:
7028           report_fatal_error("Unhandled value type for argument.");
7029         case MVT::v16i8:
7030           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7031           break;
7032         case MVT::v8i16:
7033           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7034           break;
7035         case MVT::v4i32:
7036         case MVT::v2i64:
7037         case MVT::v1i128:
7038           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7039           break;
7040         case MVT::v4f32:
7041         case MVT::v2f64:
7042           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7043           break;
7044         }
7045       }
7046     }
7047 
7048     if (Flags.isByVal() && VA.isMemLoc()) {
7049       const unsigned Size =
7050           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7051                   PtrByteSize);
7052       const int FI = MF.getFrameInfo().CreateFixedObject(
7053           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7054           /* IsAliased */ true);
7055       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7056       InVals.push_back(FIN);
7057 
7058       continue;
7059     }
7060 
7061     if (Flags.isByVal()) {
7062       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7063 
7064       const MCPhysReg ArgReg = VA.getLocReg();
7065       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7066 
7067       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7068         report_fatal_error("Over aligned byvals not supported yet.");
7069 
7070       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7071       const int FI = MF.getFrameInfo().CreateFixedObject(
7072           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7073           /* IsAliased */ true);
7074       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7075       InVals.push_back(FIN);
7076 
7077       // Add live ins for all the RegLocs for the same ByVal.
7078       const TargetRegisterClass *RegClass =
7079           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7080 
7081       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7082                                                unsigned Offset) {
7083         const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7084         // Since the callers side has left justified the aggregate in the
7085         // register, we can simply store the entire register into the stack
7086         // slot.
7087         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7088         // The store to the fixedstack object is needed becuase accessing a
7089         // field of the ByVal will use a gep and load. Ideally we will optimize
7090         // to extracting the value from the register directly, and elide the
7091         // stores when the arguments address is not taken, but that will need to
7092         // be future work.
7093         SDValue Store = DAG.getStore(
7094             CopyFrom.getValue(1), dl, CopyFrom,
7095             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7096             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7097 
7098         MemOps.push_back(Store);
7099       };
7100 
7101       unsigned Offset = 0;
7102       HandleRegLoc(VA.getLocReg(), Offset);
7103       Offset += PtrByteSize;
7104       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7105            Offset += PtrByteSize) {
7106         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7107                "RegLocs should be for ByVal argument.");
7108 
7109         const CCValAssign RL = ArgLocs[I++];
7110         HandleRegLoc(RL.getLocReg(), Offset);
7111         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7112       }
7113 
7114       if (Offset != StackSize) {
7115         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7116                "Expected MemLoc for remaining bytes.");
7117         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7118         // Consume the MemLoc.The InVal has already been emitted, so nothing
7119         // more needs to be done.
7120         ++I;
7121       }
7122 
7123       continue;
7124     }
7125 
7126     if (VA.isRegLoc() && !VA.needsCustom()) {
7127       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7128       Register VReg =
7129           MF.addLiveIn(VA.getLocReg(),
7130                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7131                                          Subtarget.hasVSX()));
7132       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7133       if (ValVT.isScalarInteger() &&
7134           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7135         ArgValue =
7136             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7137       }
7138       InVals.push_back(ArgValue);
7139       continue;
7140     }
7141     if (VA.isMemLoc()) {
7142       HandleMemLoc();
7143       continue;
7144     }
7145   }
7146 
7147   // On AIX a minimum of 8 words is saved to the parameter save area.
7148   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7149   // Area that is at least reserved in the caller of this function.
7150   unsigned CallerReservedArea =
7151       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7152 
7153   // Set the size that is at least reserved in caller of this function. Tail
7154   // call optimized function's reserved stack space needs to be aligned so
7155   // that taking the difference between two stack areas will result in an
7156   // aligned stack.
7157   CallerReservedArea =
7158       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7159   FuncInfo->setMinReservedArea(CallerReservedArea);
7160 
7161   if (isVarArg) {
7162     FuncInfo->setVarArgsFrameIndex(
7163         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7164     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7165 
7166     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7167                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7168 
7169     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7170                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7171     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7172 
7173     // The fixed integer arguments of a variadic function are stored to the
7174     // VarArgsFrameIndex on the stack so that they may be loaded by
7175     // dereferencing the result of va_next.
7176     for (unsigned GPRIndex =
7177              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7178          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7179 
7180       const Register VReg =
7181           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7182                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7183 
7184       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7185       SDValue Store =
7186           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7187       MemOps.push_back(Store);
7188       // Increment the address for the next argument to store.
7189       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7190       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7191     }
7192   }
7193 
7194   if (!MemOps.empty())
7195     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7196 
7197   return Chain;
7198 }
7199 
7200 SDValue PPCTargetLowering::LowerCall_AIX(
7201     SDValue Chain, SDValue Callee, CallFlags CFlags,
7202     const SmallVectorImpl<ISD::OutputArg> &Outs,
7203     const SmallVectorImpl<SDValue> &OutVals,
7204     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7205     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7206     const CallBase *CB) const {
7207   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7208   // AIX ABI stack frame layout.
7209 
7210   assert((CFlags.CallConv == CallingConv::C ||
7211           CFlags.CallConv == CallingConv::Cold ||
7212           CFlags.CallConv == CallingConv::Fast) &&
7213          "Unexpected calling convention!");
7214 
7215   if (CFlags.IsPatchPoint)
7216     report_fatal_error("This call type is unimplemented on AIX.");
7217 
7218   const PPCSubtarget& Subtarget =
7219       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7220 
7221   MachineFunction &MF = DAG.getMachineFunction();
7222   SmallVector<CCValAssign, 16> ArgLocs;
7223   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7224                     *DAG.getContext());
7225 
7226   // Reserve space for the linkage save area (LSA) on the stack.
7227   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7228   //   [SP][CR][LR][2 x reserved][TOC].
7229   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7230   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7231   const bool IsPPC64 = Subtarget.isPPC64();
7232   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7233   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7234   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7235   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7236 
7237   // The prolog code of the callee may store up to 8 GPR argument registers to
7238   // the stack, allowing va_start to index over them in memory if the callee
7239   // is variadic.
7240   // Because we cannot tell if this is needed on the caller side, we have to
7241   // conservatively assume that it is needed.  As such, make sure we have at
7242   // least enough stack space for the caller to store the 8 GPRs.
7243   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7244   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7245                                      CCInfo.getNextStackOffset());
7246 
7247   // Adjust the stack pointer for the new arguments...
7248   // These operations are automatically eliminated by the prolog/epilog pass.
7249   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7250   SDValue CallSeqStart = Chain;
7251 
7252   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7253   SmallVector<SDValue, 8> MemOpChains;
7254 
7255   // Set up a copy of the stack pointer for loading and storing any
7256   // arguments that may not fit in the registers available for argument
7257   // passing.
7258   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7259                                    : DAG.getRegister(PPC::R1, MVT::i32);
7260 
7261   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7262     const unsigned ValNo = ArgLocs[I].getValNo();
7263     SDValue Arg = OutVals[ValNo];
7264     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7265 
7266     if (Flags.isByVal()) {
7267       const unsigned ByValSize = Flags.getByValSize();
7268 
7269       // Nothing to do for zero-sized ByVals on the caller side.
7270       if (!ByValSize) {
7271         ++I;
7272         continue;
7273       }
7274 
7275       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7276         return DAG.getExtLoad(
7277             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7278             (LoadOffset != 0)
7279                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7280                 : Arg,
7281             MachinePointerInfo(), VT);
7282       };
7283 
7284       unsigned LoadOffset = 0;
7285 
7286       // Initialize registers, which are fully occupied by the by-val argument.
7287       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7288         SDValue Load = GetLoad(PtrVT, LoadOffset);
7289         MemOpChains.push_back(Load.getValue(1));
7290         LoadOffset += PtrByteSize;
7291         const CCValAssign &ByValVA = ArgLocs[I++];
7292         assert(ByValVA.getValNo() == ValNo &&
7293                "Unexpected location for pass-by-value argument.");
7294         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7295       }
7296 
7297       if (LoadOffset == ByValSize)
7298         continue;
7299 
7300       // There must be one more loc to handle the remainder.
7301       assert(ArgLocs[I].getValNo() == ValNo &&
7302              "Expected additional location for by-value argument.");
7303 
7304       if (ArgLocs[I].isMemLoc()) {
7305         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7306         const CCValAssign &ByValVA = ArgLocs[I++];
7307         ISD::ArgFlagsTy MemcpyFlags = Flags;
7308         // Only memcpy the bytes that don't pass in register.
7309         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7310         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7311             (LoadOffset != 0)
7312                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7313                 : Arg,
7314             DAG.getObjectPtrOffset(dl, StackPtr,
7315                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7316             CallSeqStart, MemcpyFlags, DAG, dl);
7317         continue;
7318       }
7319 
7320       // Initialize the final register residue.
7321       // Any residue that occupies the final by-val arg register must be
7322       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7323       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7324       // 2 and 1 byte loads.
7325       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7326       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7327              "Unexpected register residue for by-value argument.");
7328       SDValue ResidueVal;
7329       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7330         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7331         const MVT VT =
7332             N == 1 ? MVT::i8
7333                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7334         SDValue Load = GetLoad(VT, LoadOffset);
7335         MemOpChains.push_back(Load.getValue(1));
7336         LoadOffset += N;
7337         Bytes += N;
7338 
7339         // By-val arguments are passed left-justfied in register.
7340         // Every load here needs to be shifted, otherwise a full register load
7341         // should have been used.
7342         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7343                "Unexpected load emitted during handling of pass-by-value "
7344                "argument.");
7345         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7346         EVT ShiftAmountTy =
7347             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7348         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7349         SDValue ShiftedLoad =
7350             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7351         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7352                                               ShiftedLoad)
7353                                 : ShiftedLoad;
7354       }
7355 
7356       const CCValAssign &ByValVA = ArgLocs[I++];
7357       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7358       continue;
7359     }
7360 
7361     CCValAssign &VA = ArgLocs[I++];
7362     const MVT LocVT = VA.getLocVT();
7363     const MVT ValVT = VA.getValVT();
7364 
7365     switch (VA.getLocInfo()) {
7366     default:
7367       report_fatal_error("Unexpected argument extension type.");
7368     case CCValAssign::Full:
7369       break;
7370     case CCValAssign::ZExt:
7371       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7372       break;
7373     case CCValAssign::SExt:
7374       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7375       break;
7376     }
7377 
7378     if (VA.isRegLoc() && !VA.needsCustom()) {
7379       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7380       continue;
7381     }
7382 
7383     // Vector arguments passed to VarArg functions need custom handling when
7384     // they are passed (at least partially) in GPRs.
7385     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7386       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7387       // Store value to its stack slot.
7388       SDValue PtrOff =
7389           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7390       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7391       SDValue Store =
7392           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7393       MemOpChains.push_back(Store);
7394       const unsigned OriginalValNo = VA.getValNo();
7395       // Then load the GPRs from the stack
7396       unsigned LoadOffset = 0;
7397       auto HandleCustomVecRegLoc = [&]() {
7398         assert(I != E && "Unexpected end of CCvalAssigns.");
7399         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7400                "Expected custom RegLoc.");
7401         CCValAssign RegVA = ArgLocs[I++];
7402         assert(RegVA.getValNo() == OriginalValNo &&
7403                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7404         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7405                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7406         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7407         MemOpChains.push_back(Load.getValue(1));
7408         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7409         LoadOffset += PtrByteSize;
7410       };
7411 
7412       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7413       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7414       // R10.
7415       HandleCustomVecRegLoc();
7416       HandleCustomVecRegLoc();
7417 
7418       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7419           ArgLocs[I].getValNo() == OriginalValNo) {
7420         assert(!IsPPC64 &&
7421                "Only 2 custom RegLocs expected for 64-bit codegen.");
7422         HandleCustomVecRegLoc();
7423         HandleCustomVecRegLoc();
7424       }
7425 
7426       continue;
7427     }
7428 
7429     if (VA.isMemLoc()) {
7430       SDValue PtrOff =
7431           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7432       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7433       MemOpChains.push_back(
7434           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7435 
7436       continue;
7437     }
7438 
7439     if (!ValVT.isFloatingPoint())
7440       report_fatal_error(
7441           "Unexpected register handling for calling convention.");
7442 
7443     // Custom handling is used for GPR initializations for vararg float
7444     // arguments.
7445     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7446            LocVT.isInteger() &&
7447            "Custom register handling only expected for VarArg.");
7448 
7449     SDValue ArgAsInt =
7450         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7451 
7452     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7453       // f32 in 32-bit GPR
7454       // f64 in 64-bit GPR
7455       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7456     else if (Arg.getValueType().getFixedSizeInBits() <
7457              LocVT.getFixedSizeInBits())
7458       // f32 in 64-bit GPR.
7459       RegsToPass.push_back(std::make_pair(
7460           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7461     else {
7462       // f64 in two 32-bit GPRs
7463       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7464       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7465              "Unexpected custom register for argument!");
7466       CCValAssign &GPR1 = VA;
7467       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7468                                      DAG.getConstant(32, dl, MVT::i8));
7469       RegsToPass.push_back(std::make_pair(
7470           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7471 
7472       if (I != E) {
7473         // If only 1 GPR was available, there will only be one custom GPR and
7474         // the argument will also pass in memory.
7475         CCValAssign &PeekArg = ArgLocs[I];
7476         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7477           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7478           CCValAssign &GPR2 = ArgLocs[I++];
7479           RegsToPass.push_back(std::make_pair(
7480               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7481         }
7482       }
7483     }
7484   }
7485 
7486   if (!MemOpChains.empty())
7487     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7488 
7489   // For indirect calls, we need to save the TOC base to the stack for
7490   // restoration after the call.
7491   if (CFlags.IsIndirect) {
7492     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7493     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7494     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7495     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7496     const unsigned TOCSaveOffset =
7497         Subtarget.getFrameLowering()->getTOCSaveOffset();
7498 
7499     setUsesTOCBasePtr(DAG);
7500     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7501     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7502     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7503     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7504     Chain = DAG.getStore(
7505         Val.getValue(1), dl, Val, AddPtr,
7506         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7507   }
7508 
7509   // Build a sequence of copy-to-reg nodes chained together with token chain
7510   // and flag operands which copy the outgoing args into the appropriate regs.
7511   SDValue InFlag;
7512   for (auto Reg : RegsToPass) {
7513     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7514     InFlag = Chain.getValue(1);
7515   }
7516 
7517   const int SPDiff = 0;
7518   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7519                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7520 }
7521 
7522 bool
7523 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7524                                   MachineFunction &MF, bool isVarArg,
7525                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7526                                   LLVMContext &Context) const {
7527   SmallVector<CCValAssign, 16> RVLocs;
7528   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7529   return CCInfo.CheckReturn(
7530       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7531                 ? RetCC_PPC_Cold
7532                 : RetCC_PPC);
7533 }
7534 
7535 SDValue
7536 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7537                                bool isVarArg,
7538                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7539                                const SmallVectorImpl<SDValue> &OutVals,
7540                                const SDLoc &dl, SelectionDAG &DAG) const {
7541   SmallVector<CCValAssign, 16> RVLocs;
7542   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7543                  *DAG.getContext());
7544   CCInfo.AnalyzeReturn(Outs,
7545                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7546                            ? RetCC_PPC_Cold
7547                            : RetCC_PPC);
7548 
7549   SDValue Flag;
7550   SmallVector<SDValue, 4> RetOps(1, Chain);
7551 
7552   // Copy the result values into the output registers.
7553   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7554     CCValAssign &VA = RVLocs[i];
7555     assert(VA.isRegLoc() && "Can only return in registers!");
7556 
7557     SDValue Arg = OutVals[RealResIdx];
7558 
7559     switch (VA.getLocInfo()) {
7560     default: llvm_unreachable("Unknown loc info!");
7561     case CCValAssign::Full: break;
7562     case CCValAssign::AExt:
7563       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7564       break;
7565     case CCValAssign::ZExt:
7566       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7567       break;
7568     case CCValAssign::SExt:
7569       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7570       break;
7571     }
7572     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7573       bool isLittleEndian = Subtarget.isLittleEndian();
7574       // Legalize ret f64 -> ret 2 x i32.
7575       SDValue SVal =
7576           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7577                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7578       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7579       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7580       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7581                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7582       Flag = Chain.getValue(1);
7583       VA = RVLocs[++i]; // skip ahead to next loc
7584       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7585     } else
7586       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7587     Flag = Chain.getValue(1);
7588     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7589   }
7590 
7591   RetOps[0] = Chain;  // Update chain.
7592 
7593   // Add the flag if we have it.
7594   if (Flag.getNode())
7595     RetOps.push_back(Flag);
7596 
7597   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7598 }
7599 
7600 SDValue
7601 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7602                                                 SelectionDAG &DAG) const {
7603   SDLoc dl(Op);
7604 
7605   // Get the correct type for integers.
7606   EVT IntVT = Op.getValueType();
7607 
7608   // Get the inputs.
7609   SDValue Chain = Op.getOperand(0);
7610   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7611   // Build a DYNAREAOFFSET node.
7612   SDValue Ops[2] = {Chain, FPSIdx};
7613   SDVTList VTs = DAG.getVTList(IntVT);
7614   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7615 }
7616 
7617 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7618                                              SelectionDAG &DAG) const {
7619   // When we pop the dynamic allocation we need to restore the SP link.
7620   SDLoc dl(Op);
7621 
7622   // Get the correct type for pointers.
7623   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7624 
7625   // Construct the stack pointer operand.
7626   bool isPPC64 = Subtarget.isPPC64();
7627   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7628   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7629 
7630   // Get the operands for the STACKRESTORE.
7631   SDValue Chain = Op.getOperand(0);
7632   SDValue SaveSP = Op.getOperand(1);
7633 
7634   // Load the old link SP.
7635   SDValue LoadLinkSP =
7636       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7637 
7638   // Restore the stack pointer.
7639   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7640 
7641   // Store the old link SP.
7642   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7643 }
7644 
7645 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7646   MachineFunction &MF = DAG.getMachineFunction();
7647   bool isPPC64 = Subtarget.isPPC64();
7648   EVT PtrVT = getPointerTy(MF.getDataLayout());
7649 
7650   // Get current frame pointer save index.  The users of this index will be
7651   // primarily DYNALLOC instructions.
7652   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7653   int RASI = FI->getReturnAddrSaveIndex();
7654 
7655   // If the frame pointer save index hasn't been defined yet.
7656   if (!RASI) {
7657     // Find out what the fix offset of the frame pointer save area.
7658     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7659     // Allocate the frame index for frame pointer save area.
7660     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7661     // Save the result.
7662     FI->setReturnAddrSaveIndex(RASI);
7663   }
7664   return DAG.getFrameIndex(RASI, PtrVT);
7665 }
7666 
7667 SDValue
7668 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7669   MachineFunction &MF = DAG.getMachineFunction();
7670   bool isPPC64 = Subtarget.isPPC64();
7671   EVT PtrVT = getPointerTy(MF.getDataLayout());
7672 
7673   // Get current frame pointer save index.  The users of this index will be
7674   // primarily DYNALLOC instructions.
7675   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7676   int FPSI = FI->getFramePointerSaveIndex();
7677 
7678   // If the frame pointer save index hasn't been defined yet.
7679   if (!FPSI) {
7680     // Find out what the fix offset of the frame pointer save area.
7681     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7682     // Allocate the frame index for frame pointer save area.
7683     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7684     // Save the result.
7685     FI->setFramePointerSaveIndex(FPSI);
7686   }
7687   return DAG.getFrameIndex(FPSI, PtrVT);
7688 }
7689 
7690 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7691                                                    SelectionDAG &DAG) const {
7692   MachineFunction &MF = DAG.getMachineFunction();
7693   // Get the inputs.
7694   SDValue Chain = Op.getOperand(0);
7695   SDValue Size  = Op.getOperand(1);
7696   SDLoc dl(Op);
7697 
7698   // Get the correct type for pointers.
7699   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7700   // Negate the size.
7701   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7702                                 DAG.getConstant(0, dl, PtrVT), Size);
7703   // Construct a node for the frame pointer save index.
7704   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7705   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7706   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7707   if (hasInlineStackProbe(MF))
7708     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7709   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7710 }
7711 
7712 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7713                                                      SelectionDAG &DAG) const {
7714   MachineFunction &MF = DAG.getMachineFunction();
7715 
7716   bool isPPC64 = Subtarget.isPPC64();
7717   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7718 
7719   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7720   return DAG.getFrameIndex(FI, PtrVT);
7721 }
7722 
7723 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7724                                                SelectionDAG &DAG) const {
7725   SDLoc DL(Op);
7726   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7727                      DAG.getVTList(MVT::i32, MVT::Other),
7728                      Op.getOperand(0), Op.getOperand(1));
7729 }
7730 
7731 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7732                                                 SelectionDAG &DAG) const {
7733   SDLoc DL(Op);
7734   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7735                      Op.getOperand(0), Op.getOperand(1));
7736 }
7737 
7738 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7739   if (Op.getValueType().isVector())
7740     return LowerVectorLoad(Op, DAG);
7741 
7742   assert(Op.getValueType() == MVT::i1 &&
7743          "Custom lowering only for i1 loads");
7744 
7745   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7746 
7747   SDLoc dl(Op);
7748   LoadSDNode *LD = cast<LoadSDNode>(Op);
7749 
7750   SDValue Chain = LD->getChain();
7751   SDValue BasePtr = LD->getBasePtr();
7752   MachineMemOperand *MMO = LD->getMemOperand();
7753 
7754   SDValue NewLD =
7755       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7756                      BasePtr, MVT::i8, MMO);
7757   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7758 
7759   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7760   return DAG.getMergeValues(Ops, dl);
7761 }
7762 
7763 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7764   if (Op.getOperand(1).getValueType().isVector())
7765     return LowerVectorStore(Op, DAG);
7766 
7767   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7768          "Custom lowering only for i1 stores");
7769 
7770   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7771 
7772   SDLoc dl(Op);
7773   StoreSDNode *ST = cast<StoreSDNode>(Op);
7774 
7775   SDValue Chain = ST->getChain();
7776   SDValue BasePtr = ST->getBasePtr();
7777   SDValue Value = ST->getValue();
7778   MachineMemOperand *MMO = ST->getMemOperand();
7779 
7780   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7781                       Value);
7782   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7783 }
7784 
7785 // FIXME: Remove this once the ANDI glue bug is fixed:
7786 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7787   assert(Op.getValueType() == MVT::i1 &&
7788          "Custom lowering only for i1 results");
7789 
7790   SDLoc DL(Op);
7791   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7792 }
7793 
7794 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7795                                                SelectionDAG &DAG) const {
7796 
7797   // Implements a vector truncate that fits in a vector register as a shuffle.
7798   // We want to legalize vector truncates down to where the source fits in
7799   // a vector register (and target is therefore smaller than vector register
7800   // size).  At that point legalization will try to custom lower the sub-legal
7801   // result and get here - where we can contain the truncate as a single target
7802   // operation.
7803 
7804   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7805   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7806   //
7807   // We will implement it for big-endian ordering as this (where x denotes
7808   // undefined):
7809   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7810   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7811   //
7812   // The same operation in little-endian ordering will be:
7813   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7814   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7815 
7816   EVT TrgVT = Op.getValueType();
7817   assert(TrgVT.isVector() && "Vector type expected.");
7818   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7819   EVT EltVT = TrgVT.getVectorElementType();
7820   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7821       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7822       !isPowerOf2_32(EltVT.getSizeInBits()))
7823     return SDValue();
7824 
7825   SDValue N1 = Op.getOperand(0);
7826   EVT SrcVT = N1.getValueType();
7827   unsigned SrcSize = SrcVT.getSizeInBits();
7828   if (SrcSize > 256 ||
7829       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7830       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7831     return SDValue();
7832   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7833     return SDValue();
7834 
7835   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7836   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7837 
7838   SDLoc DL(Op);
7839   SDValue Op1, Op2;
7840   if (SrcSize == 256) {
7841     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7842     EVT SplitVT =
7843         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7844     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7845     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7846                       DAG.getConstant(0, DL, VecIdxTy));
7847     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7848                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7849   }
7850   else {
7851     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7852     Op2 = DAG.getUNDEF(WideVT);
7853   }
7854 
7855   // First list the elements we want to keep.
7856   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7857   SmallVector<int, 16> ShuffV;
7858   if (Subtarget.isLittleEndian())
7859     for (unsigned i = 0; i < TrgNumElts; ++i)
7860       ShuffV.push_back(i * SizeMult);
7861   else
7862     for (unsigned i = 1; i <= TrgNumElts; ++i)
7863       ShuffV.push_back(i * SizeMult - 1);
7864 
7865   // Populate the remaining elements with undefs.
7866   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7867     // ShuffV.push_back(i + WideNumElts);
7868     ShuffV.push_back(WideNumElts + 1);
7869 
7870   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7871   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7872   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7873 }
7874 
7875 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7876 /// possible.
7877 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7878   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7879   EVT ResVT = Op.getValueType();
7880   EVT CmpVT = Op.getOperand(0).getValueType();
7881   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7882   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7883   SDLoc dl(Op);
7884 
7885   // Without power9-vector, we don't have native instruction for f128 comparison.
7886   // Following transformation to libcall is needed for setcc:
7887   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7888   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7889     SDValue Z = DAG.getSetCC(
7890         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7891         LHS, RHS, CC);
7892     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7893     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7894   }
7895 
7896   // Not FP, or using SPE? Not a fsel.
7897   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7898       Subtarget.hasSPE())
7899     return Op;
7900 
7901   SDNodeFlags Flags = Op.getNode()->getFlags();
7902 
7903   // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
7904   // presence of infinities.
7905   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7906     switch (CC) {
7907     default:
7908       break;
7909     case ISD::SETOGT:
7910     case ISD::SETGT:
7911       return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
7912     case ISD::SETOLT:
7913     case ISD::SETLT:
7914       return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
7915     }
7916   }
7917 
7918   // We might be able to do better than this under some circumstances, but in
7919   // general, fsel-based lowering of select is a finite-math-only optimization.
7920   // For more information, see section F.3 of the 2.06 ISA specification.
7921   // With ISA 3.0
7922   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7923       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7924     return Op;
7925 
7926   // If the RHS of the comparison is a 0.0, we don't need to do the
7927   // subtraction at all.
7928   SDValue Sel1;
7929   if (isFloatingPointZero(RHS))
7930     switch (CC) {
7931     default: break;       // SETUO etc aren't handled by fsel.
7932     case ISD::SETNE:
7933       std::swap(TV, FV);
7934       LLVM_FALLTHROUGH;
7935     case ISD::SETEQ:
7936       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7937         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7938       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7939       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7940         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7941       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7942                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7943     case ISD::SETULT:
7944     case ISD::SETLT:
7945       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7946       LLVM_FALLTHROUGH;
7947     case ISD::SETOGE:
7948     case ISD::SETGE:
7949       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7950         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7951       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7952     case ISD::SETUGT:
7953     case ISD::SETGT:
7954       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7955       LLVM_FALLTHROUGH;
7956     case ISD::SETOLE:
7957     case ISD::SETLE:
7958       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7959         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7960       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7961                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7962     }
7963 
7964   SDValue Cmp;
7965   switch (CC) {
7966   default: break;       // SETUO etc aren't handled by fsel.
7967   case ISD::SETNE:
7968     std::swap(TV, FV);
7969     LLVM_FALLTHROUGH;
7970   case ISD::SETEQ:
7971     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7972     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7973       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7974     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7975     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7976       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7977     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7978                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7979   case ISD::SETULT:
7980   case ISD::SETLT:
7981     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7982     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7983       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7984     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7985   case ISD::SETOGE:
7986   case ISD::SETGE:
7987     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7988     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7989       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7990     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7991   case ISD::SETUGT:
7992   case ISD::SETGT:
7993     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7994     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7995       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7996     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7997   case ISD::SETOLE:
7998   case ISD::SETLE:
7999     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8000     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8001       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8002     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8003   }
8004   return Op;
8005 }
8006 
8007 static unsigned getPPCStrictOpcode(unsigned Opc) {
8008   switch (Opc) {
8009   default:
8010     llvm_unreachable("No strict version of this opcode!");
8011   case PPCISD::FCTIDZ:
8012     return PPCISD::STRICT_FCTIDZ;
8013   case PPCISD::FCTIWZ:
8014     return PPCISD::STRICT_FCTIWZ;
8015   case PPCISD::FCTIDUZ:
8016     return PPCISD::STRICT_FCTIDUZ;
8017   case PPCISD::FCTIWUZ:
8018     return PPCISD::STRICT_FCTIWUZ;
8019   case PPCISD::FCFID:
8020     return PPCISD::STRICT_FCFID;
8021   case PPCISD::FCFIDU:
8022     return PPCISD::STRICT_FCFIDU;
8023   case PPCISD::FCFIDS:
8024     return PPCISD::STRICT_FCFIDS;
8025   case PPCISD::FCFIDUS:
8026     return PPCISD::STRICT_FCFIDUS;
8027   }
8028 }
8029 
8030 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8031                               const PPCSubtarget &Subtarget) {
8032   SDLoc dl(Op);
8033   bool IsStrict = Op->isStrictFPOpcode();
8034   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8035                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8036 
8037   // TODO: Any other flags to propagate?
8038   SDNodeFlags Flags;
8039   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8040 
8041   // For strict nodes, source is the second operand.
8042   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8043   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8044   assert(Src.getValueType().isFloatingPoint());
8045   if (Src.getValueType() == MVT::f32) {
8046     if (IsStrict) {
8047       Src =
8048           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8049                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8050       Chain = Src.getValue(1);
8051     } else
8052       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8053   }
8054   SDValue Conv;
8055   unsigned Opc = ISD::DELETED_NODE;
8056   switch (Op.getSimpleValueType().SimpleTy) {
8057   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8058   case MVT::i32:
8059     Opc = IsSigned ? PPCISD::FCTIWZ
8060                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8061     break;
8062   case MVT::i64:
8063     assert((IsSigned || Subtarget.hasFPCVT()) &&
8064            "i64 FP_TO_UINT is supported only with FPCVT");
8065     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8066   }
8067   if (IsStrict) {
8068     Opc = getPPCStrictOpcode(Opc);
8069     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8070                        {Chain, Src}, Flags);
8071   } else {
8072     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8073   }
8074   return Conv;
8075 }
8076 
8077 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8078                                                SelectionDAG &DAG,
8079                                                const SDLoc &dl) const {
8080   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8081   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8082                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8083   bool IsStrict = Op->isStrictFPOpcode();
8084 
8085   // Convert the FP value to an int value through memory.
8086   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8087                   (IsSigned || Subtarget.hasFPCVT());
8088   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8089   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8090   MachinePointerInfo MPI =
8091       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8092 
8093   // Emit a store to the stack slot.
8094   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8095   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8096   if (i32Stack) {
8097     MachineFunction &MF = DAG.getMachineFunction();
8098     Alignment = Align(4);
8099     MachineMemOperand *MMO =
8100         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8101     SDValue Ops[] = { Chain, Tmp, FIPtr };
8102     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8103               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8104   } else
8105     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8106 
8107   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8108   // add in a bias on big endian.
8109   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8110     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8111                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8112     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8113   }
8114 
8115   RLI.Chain = Chain;
8116   RLI.Ptr = FIPtr;
8117   RLI.MPI = MPI;
8118   RLI.Alignment = Alignment;
8119 }
8120 
8121 /// Custom lowers floating point to integer conversions to use
8122 /// the direct move instructions available in ISA 2.07 to avoid the
8123 /// need for load/store combinations.
8124 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8125                                                     SelectionDAG &DAG,
8126                                                     const SDLoc &dl) const {
8127   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8128   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8129   if (Op->isStrictFPOpcode())
8130     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8131   else
8132     return Mov;
8133 }
8134 
8135 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8136                                           const SDLoc &dl) const {
8137   bool IsStrict = Op->isStrictFPOpcode();
8138   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8139                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8140   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8141   EVT SrcVT = Src.getValueType();
8142   EVT DstVT = Op.getValueType();
8143 
8144   // FP to INT conversions are legal for f128.
8145   if (SrcVT == MVT::f128)
8146     return Subtarget.hasP9Vector() ? Op : SDValue();
8147 
8148   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8149   // PPC (the libcall is not available).
8150   if (SrcVT == MVT::ppcf128) {
8151     if (DstVT == MVT::i32) {
8152       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8153       // set other fast-math flags to FP operations in both strict and
8154       // non-strict cases. (FP_TO_SINT, FSUB)
8155       SDNodeFlags Flags;
8156       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8157 
8158       if (IsSigned) {
8159         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8160                                  DAG.getIntPtrConstant(0, dl));
8161         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8162                                  DAG.getIntPtrConstant(1, dl));
8163 
8164         // Add the two halves of the long double in round-to-zero mode, and use
8165         // a smaller FP_TO_SINT.
8166         if (IsStrict) {
8167           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8168                                     DAG.getVTList(MVT::f64, MVT::Other),
8169                                     {Op.getOperand(0), Lo, Hi}, Flags);
8170           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8171                              DAG.getVTList(MVT::i32, MVT::Other),
8172                              {Res.getValue(1), Res}, Flags);
8173         } else {
8174           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8175           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8176         }
8177       } else {
8178         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8179         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8180         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8181         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8182         if (IsStrict) {
8183           // Sel = Src < 0x80000000
8184           // FltOfs = select Sel, 0.0, 0x80000000
8185           // IntOfs = select Sel, 0, 0x80000000
8186           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8187           SDValue Chain = Op.getOperand(0);
8188           EVT SetCCVT =
8189               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8190           EVT DstSetCCVT =
8191               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8192           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8193                                      Chain, true);
8194           Chain = Sel.getValue(1);
8195 
8196           SDValue FltOfs = DAG.getSelect(
8197               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8198           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8199 
8200           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8201                                     DAG.getVTList(SrcVT, MVT::Other),
8202                                     {Chain, Src, FltOfs}, Flags);
8203           Chain = Val.getValue(1);
8204           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8205                                      DAG.getVTList(DstVT, MVT::Other),
8206                                      {Chain, Val}, Flags);
8207           Chain = SInt.getValue(1);
8208           SDValue IntOfs = DAG.getSelect(
8209               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8210           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8211           return DAG.getMergeValues({Result, Chain}, dl);
8212         } else {
8213           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8214           // FIXME: generated code sucks.
8215           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8216           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8217           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8218           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8219           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8220         }
8221       }
8222     }
8223 
8224     return SDValue();
8225   }
8226 
8227   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8228     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8229 
8230   ReuseLoadInfo RLI;
8231   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8232 
8233   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8234                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8235 }
8236 
8237 // We're trying to insert a regular store, S, and then a load, L. If the
8238 // incoming value, O, is a load, we might just be able to have our load use the
8239 // address used by O. However, we don't know if anything else will store to
8240 // that address before we can load from it. To prevent this situation, we need
8241 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8242 // the same chain operand as O, we create a token factor from the chain results
8243 // of O and L, and we replace all uses of O's chain result with that token
8244 // factor (see spliceIntoChain below for this last part).
8245 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8246                                             ReuseLoadInfo &RLI,
8247                                             SelectionDAG &DAG,
8248                                             ISD::LoadExtType ET) const {
8249   // Conservatively skip reusing for constrained FP nodes.
8250   if (Op->isStrictFPOpcode())
8251     return false;
8252 
8253   SDLoc dl(Op);
8254   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8255                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8256   if (ET == ISD::NON_EXTLOAD &&
8257       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8258       isOperationLegalOrCustom(Op.getOpcode(),
8259                                Op.getOperand(0).getValueType())) {
8260 
8261     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8262     return true;
8263   }
8264 
8265   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8266   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8267       LD->isNonTemporal())
8268     return false;
8269   if (LD->getMemoryVT() != MemVT)
8270     return false;
8271 
8272   // If the result of the load is an illegal type, then we can't build a
8273   // valid chain for reuse since the legalised loads and token factor node that
8274   // ties the legalised loads together uses a different output chain then the
8275   // illegal load.
8276   if (!isTypeLegal(LD->getValueType(0)))
8277     return false;
8278 
8279   RLI.Ptr = LD->getBasePtr();
8280   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8281     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8282            "Non-pre-inc AM on PPC?");
8283     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8284                           LD->getOffset());
8285   }
8286 
8287   RLI.Chain = LD->getChain();
8288   RLI.MPI = LD->getPointerInfo();
8289   RLI.IsDereferenceable = LD->isDereferenceable();
8290   RLI.IsInvariant = LD->isInvariant();
8291   RLI.Alignment = LD->getAlign();
8292   RLI.AAInfo = LD->getAAInfo();
8293   RLI.Ranges = LD->getRanges();
8294 
8295   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8296   return true;
8297 }
8298 
8299 // Given the head of the old chain, ResChain, insert a token factor containing
8300 // it and NewResChain, and make users of ResChain now be users of that token
8301 // factor.
8302 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8303 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8304                                         SDValue NewResChain,
8305                                         SelectionDAG &DAG) const {
8306   if (!ResChain)
8307     return;
8308 
8309   SDLoc dl(NewResChain);
8310 
8311   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8312                            NewResChain, DAG.getUNDEF(MVT::Other));
8313   assert(TF.getNode() != NewResChain.getNode() &&
8314          "A new TF really is required here");
8315 
8316   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8317   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8318 }
8319 
8320 /// Analyze profitability of direct move
8321 /// prefer float load to int load plus direct move
8322 /// when there is no integer use of int load
8323 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8324   SDNode *Origin = Op.getOperand(0).getNode();
8325   if (Origin->getOpcode() != ISD::LOAD)
8326     return true;
8327 
8328   // If there is no LXSIBZX/LXSIHZX, like Power8,
8329   // prefer direct move if the memory size is 1 or 2 bytes.
8330   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8331   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8332     return true;
8333 
8334   for (SDNode::use_iterator UI = Origin->use_begin(),
8335                             UE = Origin->use_end();
8336        UI != UE; ++UI) {
8337 
8338     // Only look at the users of the loaded value.
8339     if (UI.getUse().get().getResNo() != 0)
8340       continue;
8341 
8342     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8343         UI->getOpcode() != ISD::UINT_TO_FP &&
8344         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8345         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8346       return true;
8347   }
8348 
8349   return false;
8350 }
8351 
8352 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8353                               const PPCSubtarget &Subtarget,
8354                               SDValue Chain = SDValue()) {
8355   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8356                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8357   SDLoc dl(Op);
8358 
8359   // TODO: Any other flags to propagate?
8360   SDNodeFlags Flags;
8361   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8362 
8363   // If we have FCFIDS, then use it when converting to single-precision.
8364   // Otherwise, convert to double-precision and then round.
8365   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8366   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8367                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8368   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8369   if (Op->isStrictFPOpcode()) {
8370     if (!Chain)
8371       Chain = Op.getOperand(0);
8372     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8373                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8374   } else
8375     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8376 }
8377 
8378 /// Custom lowers integer to floating point conversions to use
8379 /// the direct move instructions available in ISA 2.07 to avoid the
8380 /// need for load/store combinations.
8381 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8382                                                     SelectionDAG &DAG,
8383                                                     const SDLoc &dl) const {
8384   assert((Op.getValueType() == MVT::f32 ||
8385           Op.getValueType() == MVT::f64) &&
8386          "Invalid floating point type as target of conversion");
8387   assert(Subtarget.hasFPCVT() &&
8388          "Int to FP conversions with direct moves require FPCVT");
8389   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8390   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8391   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8392                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8393   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8394   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8395   return convertIntToFP(Op, Mov, DAG, Subtarget);
8396 }
8397 
8398 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8399 
8400   EVT VecVT = Vec.getValueType();
8401   assert(VecVT.isVector() && "Expected a vector type.");
8402   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8403 
8404   EVT EltVT = VecVT.getVectorElementType();
8405   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8406   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8407 
8408   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8409   SmallVector<SDValue, 16> Ops(NumConcat);
8410   Ops[0] = Vec;
8411   SDValue UndefVec = DAG.getUNDEF(VecVT);
8412   for (unsigned i = 1; i < NumConcat; ++i)
8413     Ops[i] = UndefVec;
8414 
8415   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8416 }
8417 
8418 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8419                                                 const SDLoc &dl) const {
8420   bool IsStrict = Op->isStrictFPOpcode();
8421   unsigned Opc = Op.getOpcode();
8422   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8423   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8424           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8425          "Unexpected conversion type");
8426   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8427          "Supports conversions to v2f64/v4f32 only.");
8428 
8429   // TODO: Any other flags to propagate?
8430   SDNodeFlags Flags;
8431   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8432 
8433   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8434   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8435 
8436   SDValue Wide = widenVec(DAG, Src, dl);
8437   EVT WideVT = Wide.getValueType();
8438   unsigned WideNumElts = WideVT.getVectorNumElements();
8439   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8440 
8441   SmallVector<int, 16> ShuffV;
8442   for (unsigned i = 0; i < WideNumElts; ++i)
8443     ShuffV.push_back(i + WideNumElts);
8444 
8445   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8446   int SaveElts = FourEltRes ? 4 : 2;
8447   if (Subtarget.isLittleEndian())
8448     for (int i = 0; i < SaveElts; i++)
8449       ShuffV[i * Stride] = i;
8450   else
8451     for (int i = 1; i <= SaveElts; i++)
8452       ShuffV[i * Stride - 1] = i - 1;
8453 
8454   SDValue ShuffleSrc2 =
8455       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8456   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8457 
8458   SDValue Extend;
8459   if (SignedConv) {
8460     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8461     EVT ExtVT = Src.getValueType();
8462     if (Subtarget.hasP9Altivec())
8463       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8464                                IntermediateVT.getVectorNumElements());
8465 
8466     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8467                          DAG.getValueType(ExtVT));
8468   } else
8469     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8470 
8471   if (IsStrict)
8472     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8473                        {Op.getOperand(0), Extend}, Flags);
8474 
8475   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8476 }
8477 
8478 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8479                                           SelectionDAG &DAG) const {
8480   SDLoc dl(Op);
8481   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8482                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8483   bool IsStrict = Op->isStrictFPOpcode();
8484   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8485   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8486 
8487   // TODO: Any other flags to propagate?
8488   SDNodeFlags Flags;
8489   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8490 
8491   EVT InVT = Src.getValueType();
8492   EVT OutVT = Op.getValueType();
8493   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8494       isOperationCustom(Op.getOpcode(), InVT))
8495     return LowerINT_TO_FPVector(Op, DAG, dl);
8496 
8497   // Conversions to f128 are legal.
8498   if (Op.getValueType() == MVT::f128)
8499     return Subtarget.hasP9Vector() ? Op : SDValue();
8500 
8501   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8502   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8503     return SDValue();
8504 
8505   if (Src.getValueType() == MVT::i1) {
8506     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8507                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8508                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8509     if (IsStrict)
8510       return DAG.getMergeValues({Sel, Chain}, dl);
8511     else
8512       return Sel;
8513   }
8514 
8515   // If we have direct moves, we can do all the conversion, skip the store/load
8516   // however, without FPCVT we can't do most conversions.
8517   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8518       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8519     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8520 
8521   assert((IsSigned || Subtarget.hasFPCVT()) &&
8522          "UINT_TO_FP is supported only with FPCVT");
8523 
8524   if (Src.getValueType() == MVT::i64) {
8525     SDValue SINT = Src;
8526     // When converting to single-precision, we actually need to convert
8527     // to double-precision first and then round to single-precision.
8528     // To avoid double-rounding effects during that operation, we have
8529     // to prepare the input operand.  Bits that might be truncated when
8530     // converting to double-precision are replaced by a bit that won't
8531     // be lost at this stage, but is below the single-precision rounding
8532     // position.
8533     //
8534     // However, if -enable-unsafe-fp-math is in effect, accept double
8535     // rounding to avoid the extra overhead.
8536     if (Op.getValueType() == MVT::f32 &&
8537         !Subtarget.hasFPCVT() &&
8538         !DAG.getTarget().Options.UnsafeFPMath) {
8539 
8540       // Twiddle input to make sure the low 11 bits are zero.  (If this
8541       // is the case, we are guaranteed the value will fit into the 53 bit
8542       // mantissa of an IEEE double-precision value without rounding.)
8543       // If any of those low 11 bits were not zero originally, make sure
8544       // bit 12 (value 2048) is set instead, so that the final rounding
8545       // to single-precision gets the correct result.
8546       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8547                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8548       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8549                           Round, DAG.getConstant(2047, dl, MVT::i64));
8550       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8551       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8552                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8553 
8554       // However, we cannot use that value unconditionally: if the magnitude
8555       // of the input value is small, the bit-twiddling we did above might
8556       // end up visibly changing the output.  Fortunately, in that case, we
8557       // don't need to twiddle bits since the original input will convert
8558       // exactly to double-precision floating-point already.  Therefore,
8559       // construct a conditional to use the original value if the top 11
8560       // bits are all sign-bit copies, and use the rounded value computed
8561       // above otherwise.
8562       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8563                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8564       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8565                          Cond, DAG.getConstant(1, dl, MVT::i64));
8566       Cond = DAG.getSetCC(
8567           dl,
8568           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8569           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8570 
8571       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8572     }
8573 
8574     ReuseLoadInfo RLI;
8575     SDValue Bits;
8576 
8577     MachineFunction &MF = DAG.getMachineFunction();
8578     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8579       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8580                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8581       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8582     } else if (Subtarget.hasLFIWAX() &&
8583                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8584       MachineMemOperand *MMO =
8585         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8586                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8587       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8588       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8589                                      DAG.getVTList(MVT::f64, MVT::Other),
8590                                      Ops, MVT::i32, MMO);
8591       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8592     } else if (Subtarget.hasFPCVT() &&
8593                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8594       MachineMemOperand *MMO =
8595         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8596                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8597       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8598       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8599                                      DAG.getVTList(MVT::f64, MVT::Other),
8600                                      Ops, MVT::i32, MMO);
8601       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8602     } else if (((Subtarget.hasLFIWAX() &&
8603                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8604                 (Subtarget.hasFPCVT() &&
8605                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8606                SINT.getOperand(0).getValueType() == MVT::i32) {
8607       MachineFrameInfo &MFI = MF.getFrameInfo();
8608       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8609 
8610       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8611       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8612 
8613       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8614                                    MachinePointerInfo::getFixedStack(
8615                                        DAG.getMachineFunction(), FrameIdx));
8616       Chain = Store;
8617 
8618       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8619              "Expected an i32 store");
8620 
8621       RLI.Ptr = FIdx;
8622       RLI.Chain = Chain;
8623       RLI.MPI =
8624           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8625       RLI.Alignment = Align(4);
8626 
8627       MachineMemOperand *MMO =
8628         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8629                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8630       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8631       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8632                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8633                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8634                                      Ops, MVT::i32, MMO);
8635       Chain = Bits.getValue(1);
8636     } else
8637       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8638 
8639     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8640     if (IsStrict)
8641       Chain = FP.getValue(1);
8642 
8643     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8644       if (IsStrict)
8645         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8646                          DAG.getVTList(MVT::f32, MVT::Other),
8647                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8648       else
8649         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8650                          DAG.getIntPtrConstant(0, dl));
8651     }
8652     return FP;
8653   }
8654 
8655   assert(Src.getValueType() == MVT::i32 &&
8656          "Unhandled INT_TO_FP type in custom expander!");
8657   // Since we only generate this in 64-bit mode, we can take advantage of
8658   // 64-bit registers.  In particular, sign extend the input value into the
8659   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8660   // then lfd it and fcfid it.
8661   MachineFunction &MF = DAG.getMachineFunction();
8662   MachineFrameInfo &MFI = MF.getFrameInfo();
8663   EVT PtrVT = getPointerTy(MF.getDataLayout());
8664 
8665   SDValue Ld;
8666   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8667     ReuseLoadInfo RLI;
8668     bool ReusingLoad;
8669     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8670       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8671       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8672 
8673       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8674                                    MachinePointerInfo::getFixedStack(
8675                                        DAG.getMachineFunction(), FrameIdx));
8676       Chain = Store;
8677 
8678       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8679              "Expected an i32 store");
8680 
8681       RLI.Ptr = FIdx;
8682       RLI.Chain = Chain;
8683       RLI.MPI =
8684           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8685       RLI.Alignment = Align(4);
8686     }
8687 
8688     MachineMemOperand *MMO =
8689       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8690                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8691     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8692     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8693                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8694                                  MVT::i32, MMO);
8695     Chain = Ld.getValue(1);
8696     if (ReusingLoad)
8697       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8698   } else {
8699     assert(Subtarget.isPPC64() &&
8700            "i32->FP without LFIWAX supported only on PPC64");
8701 
8702     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8703     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8704 
8705     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8706 
8707     // STD the extended value into the stack slot.
8708     SDValue Store = DAG.getStore(
8709         Chain, dl, Ext64, FIdx,
8710         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8711     Chain = Store;
8712 
8713     // Load the value as a double.
8714     Ld = DAG.getLoad(
8715         MVT::f64, dl, Chain, FIdx,
8716         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8717     Chain = Ld.getValue(1);
8718   }
8719 
8720   // FCFID it and return it.
8721   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8722   if (IsStrict)
8723     Chain = FP.getValue(1);
8724   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8725     if (IsStrict)
8726       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8727                        DAG.getVTList(MVT::f32, MVT::Other),
8728                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8729     else
8730       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8731                        DAG.getIntPtrConstant(0, dl));
8732   }
8733   return FP;
8734 }
8735 
8736 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8737                                             SelectionDAG &DAG) const {
8738   SDLoc dl(Op);
8739   /*
8740    The rounding mode is in bits 30:31 of FPSR, and has the following
8741    settings:
8742      00 Round to nearest
8743      01 Round to 0
8744      10 Round to +inf
8745      11 Round to -inf
8746 
8747   FLT_ROUNDS, on the other hand, expects the following:
8748     -1 Undefined
8749      0 Round to 0
8750      1 Round to nearest
8751      2 Round to +inf
8752      3 Round to -inf
8753 
8754   To perform the conversion, we do:
8755     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8756   */
8757 
8758   MachineFunction &MF = DAG.getMachineFunction();
8759   EVT VT = Op.getValueType();
8760   EVT PtrVT = getPointerTy(MF.getDataLayout());
8761 
8762   // Save FP Control Word to register
8763   SDValue Chain = Op.getOperand(0);
8764   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8765   Chain = MFFS.getValue(1);
8766 
8767   SDValue CWD;
8768   if (isTypeLegal(MVT::i64)) {
8769     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8770                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8771   } else {
8772     // Save FP register to stack slot
8773     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8774     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8775     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8776 
8777     // Load FP Control Word from low 32 bits of stack slot.
8778     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8779            "Stack slot adjustment is valid only on big endian subtargets!");
8780     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8781     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8782     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8783     Chain = CWD.getValue(1);
8784   }
8785 
8786   // Transform as necessary
8787   SDValue CWD1 =
8788     DAG.getNode(ISD::AND, dl, MVT::i32,
8789                 CWD, DAG.getConstant(3, dl, MVT::i32));
8790   SDValue CWD2 =
8791     DAG.getNode(ISD::SRL, dl, MVT::i32,
8792                 DAG.getNode(ISD::AND, dl, MVT::i32,
8793                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8794                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8795                             DAG.getConstant(3, dl, MVT::i32)),
8796                 DAG.getConstant(1, dl, MVT::i32));
8797 
8798   SDValue RetVal =
8799     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8800 
8801   RetVal =
8802       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8803                   dl, VT, RetVal);
8804 
8805   return DAG.getMergeValues({RetVal, Chain}, dl);
8806 }
8807 
8808 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8809   EVT VT = Op.getValueType();
8810   unsigned BitWidth = VT.getSizeInBits();
8811   SDLoc dl(Op);
8812   assert(Op.getNumOperands() == 3 &&
8813          VT == Op.getOperand(1).getValueType() &&
8814          "Unexpected SHL!");
8815 
8816   // Expand into a bunch of logical ops.  Note that these ops
8817   // depend on the PPC behavior for oversized shift amounts.
8818   SDValue Lo = Op.getOperand(0);
8819   SDValue Hi = Op.getOperand(1);
8820   SDValue Amt = Op.getOperand(2);
8821   EVT AmtVT = Amt.getValueType();
8822 
8823   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8824                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8825   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8826   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8827   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8828   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8829                              DAG.getConstant(-BitWidth, dl, AmtVT));
8830   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8831   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8832   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8833   SDValue OutOps[] = { OutLo, OutHi };
8834   return DAG.getMergeValues(OutOps, dl);
8835 }
8836 
8837 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8838   EVT VT = Op.getValueType();
8839   SDLoc dl(Op);
8840   unsigned BitWidth = VT.getSizeInBits();
8841   assert(Op.getNumOperands() == 3 &&
8842          VT == Op.getOperand(1).getValueType() &&
8843          "Unexpected SRL!");
8844 
8845   // Expand into a bunch of logical ops.  Note that these ops
8846   // depend on the PPC behavior for oversized shift amounts.
8847   SDValue Lo = Op.getOperand(0);
8848   SDValue Hi = Op.getOperand(1);
8849   SDValue Amt = Op.getOperand(2);
8850   EVT AmtVT = Amt.getValueType();
8851 
8852   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8853                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8854   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8855   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8856   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8857   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8858                              DAG.getConstant(-BitWidth, dl, AmtVT));
8859   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8860   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8861   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8862   SDValue OutOps[] = { OutLo, OutHi };
8863   return DAG.getMergeValues(OutOps, dl);
8864 }
8865 
8866 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8867   SDLoc dl(Op);
8868   EVT VT = Op.getValueType();
8869   unsigned BitWidth = VT.getSizeInBits();
8870   assert(Op.getNumOperands() == 3 &&
8871          VT == Op.getOperand(1).getValueType() &&
8872          "Unexpected SRA!");
8873 
8874   // Expand into a bunch of logical ops, followed by a select_cc.
8875   SDValue Lo = Op.getOperand(0);
8876   SDValue Hi = Op.getOperand(1);
8877   SDValue Amt = Op.getOperand(2);
8878   EVT AmtVT = Amt.getValueType();
8879 
8880   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8881                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8882   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8883   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8884   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8885   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8886                              DAG.getConstant(-BitWidth, dl, AmtVT));
8887   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8888   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8889   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8890                                   Tmp4, Tmp6, ISD::SETLE);
8891   SDValue OutOps[] = { OutLo, OutHi };
8892   return DAG.getMergeValues(OutOps, dl);
8893 }
8894 
8895 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8896                                             SelectionDAG &DAG) const {
8897   SDLoc dl(Op);
8898   EVT VT = Op.getValueType();
8899   unsigned BitWidth = VT.getSizeInBits();
8900 
8901   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8902   SDValue X = Op.getOperand(0);
8903   SDValue Y = Op.getOperand(1);
8904   SDValue Z = Op.getOperand(2);
8905   EVT AmtVT = Z.getValueType();
8906 
8907   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8908   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8909   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8910   // on PowerPC shift by BW being well defined.
8911   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8912                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8913   SDValue SubZ =
8914       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8915   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8916   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8917   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8918 }
8919 
8920 //===----------------------------------------------------------------------===//
8921 // Vector related lowering.
8922 //
8923 
8924 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8925 /// element size of SplatSize. Cast the result to VT.
8926 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8927                                       SelectionDAG &DAG, const SDLoc &dl) {
8928   static const MVT VTys[] = { // canonical VT to use for each size.
8929     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8930   };
8931 
8932   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8933 
8934   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8935   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8936     SplatSize = 1;
8937     Val = 0xFF;
8938   }
8939 
8940   EVT CanonicalVT = VTys[SplatSize-1];
8941 
8942   // Build a canonical splat for this value.
8943   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8944 }
8945 
8946 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8947 /// specified intrinsic ID.
8948 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8949                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8950   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8951   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8952                      DAG.getConstant(IID, dl, MVT::i32), Op);
8953 }
8954 
8955 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8956 /// specified intrinsic ID.
8957 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8958                                 SelectionDAG &DAG, const SDLoc &dl,
8959                                 EVT DestVT = MVT::Other) {
8960   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8961   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8962                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8963 }
8964 
8965 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8966 /// specified intrinsic ID.
8967 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8968                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8969                                 EVT DestVT = MVT::Other) {
8970   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8971   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8972                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8973 }
8974 
8975 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8976 /// amount.  The result has the specified value type.
8977 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8978                            SelectionDAG &DAG, const SDLoc &dl) {
8979   // Force LHS/RHS to be the right type.
8980   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8981   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8982 
8983   int Ops[16];
8984   for (unsigned i = 0; i != 16; ++i)
8985     Ops[i] = i + Amt;
8986   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8987   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8988 }
8989 
8990 /// Do we have an efficient pattern in a .td file for this node?
8991 ///
8992 /// \param V - pointer to the BuildVectorSDNode being matched
8993 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8994 ///
8995 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8996 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8997 /// the opposite is true (expansion is beneficial) are:
8998 /// - The node builds a vector out of integers that are not 32 or 64-bits
8999 /// - The node builds a vector out of constants
9000 /// - The node is a "load-and-splat"
9001 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9002 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9003                                             bool HasDirectMove,
9004                                             bool HasP8Vector) {
9005   EVT VecVT = V->getValueType(0);
9006   bool RightType = VecVT == MVT::v2f64 ||
9007     (HasP8Vector && VecVT == MVT::v4f32) ||
9008     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9009   if (!RightType)
9010     return false;
9011 
9012   bool IsSplat = true;
9013   bool IsLoad = false;
9014   SDValue Op0 = V->getOperand(0);
9015 
9016   // This function is called in a block that confirms the node is not a constant
9017   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9018   // different constants.
9019   if (V->isConstant())
9020     return false;
9021   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9022     if (V->getOperand(i).isUndef())
9023       return false;
9024     // We want to expand nodes that represent load-and-splat even if the
9025     // loaded value is a floating point truncation or conversion to int.
9026     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9027         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9028          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9029         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9030          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9031         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9032          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9033       IsLoad = true;
9034     // If the operands are different or the input is not a load and has more
9035     // uses than just this BV node, then it isn't a splat.
9036     if (V->getOperand(i) != Op0 ||
9037         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9038       IsSplat = false;
9039   }
9040   return !(IsSplat && IsLoad);
9041 }
9042 
9043 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9044 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9045 
9046   SDLoc dl(Op);
9047   SDValue Op0 = Op->getOperand(0);
9048 
9049   if ((Op.getValueType() != MVT::f128) ||
9050       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9051       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9052       (Op0.getOperand(1).getValueType() != MVT::i64))
9053     return SDValue();
9054 
9055   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9056                      Op0.getOperand(1));
9057 }
9058 
9059 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9060   const SDValue *InputLoad = &Op;
9061   if (InputLoad->getOpcode() == ISD::BITCAST)
9062     InputLoad = &InputLoad->getOperand(0);
9063   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9064       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9065     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9066     InputLoad = &InputLoad->getOperand(0);
9067   }
9068   if (InputLoad->getOpcode() != ISD::LOAD)
9069     return nullptr;
9070   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9071   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9072 }
9073 
9074 // Convert the argument APFloat to a single precision APFloat if there is no
9075 // loss in information during the conversion to single precision APFloat and the
9076 // resulting number is not a denormal number. Return true if successful.
9077 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9078   APFloat APFloatToConvert = ArgAPFloat;
9079   bool LosesInfo = true;
9080   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9081                            &LosesInfo);
9082   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9083   if (Success)
9084     ArgAPFloat = APFloatToConvert;
9085   return Success;
9086 }
9087 
9088 // Bitcast the argument APInt to a double and convert it to a single precision
9089 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9090 // argument if there is no loss in information during the conversion from
9091 // double to single precision APFloat and the resulting number is not a denormal
9092 // number. Return true if successful.
9093 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9094   double DpValue = ArgAPInt.bitsToDouble();
9095   APFloat APFloatDp(DpValue);
9096   bool Success = convertToNonDenormSingle(APFloatDp);
9097   if (Success)
9098     ArgAPInt = APFloatDp.bitcastToAPInt();
9099   return Success;
9100 }
9101 
9102 // Nondestructive check for convertTonNonDenormSingle.
9103 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9104   // Only convert if it loses info, since XXSPLTIDP should
9105   // handle the other case.
9106   APFloat APFloatToConvert = ArgAPFloat;
9107   bool LosesInfo = true;
9108   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9109                            &LosesInfo);
9110 
9111   return (!LosesInfo && !APFloatToConvert.isDenormal());
9112 }
9113 
9114 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9115                              unsigned &Opcode) {
9116   LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9117   if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9118     return false;
9119 
9120   EVT Ty = Op->getValueType(0);
9121   // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9122   // as we cannot handle extending loads for these types.
9123   if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9124       ISD::isNON_EXTLoad(InputNode))
9125     return true;
9126 
9127   EVT MemVT = InputNode->getMemoryVT();
9128   // For v8i16 and v16i8 types, extending loads can be handled as long as the
9129   // memory VT is the same vector element VT type.
9130   // The loads feeding into the v8i16 and v16i8 types will be extending because
9131   // scalar i8/i16 are not legal types.
9132   if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9133       (MemVT == Ty.getVectorElementType()))
9134     return true;
9135 
9136   if (Ty == MVT::v2i64) {
9137     // Check the extend type, when the input type is i32, and the output vector
9138     // type is v2i64.
9139     if (MemVT == MVT::i32) {
9140       if (ISD::isZEXTLoad(InputNode))
9141         Opcode = PPCISD::ZEXT_LD_SPLAT;
9142       if (ISD::isSEXTLoad(InputNode))
9143         Opcode = PPCISD::SEXT_LD_SPLAT;
9144     }
9145     return true;
9146   }
9147   return false;
9148 }
9149 
9150 // If this is a case we can't handle, return null and let the default
9151 // expansion code take care of it.  If we CAN select this case, and if it
9152 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9153 // this case more efficiently than a constant pool load, lower it to the
9154 // sequence of ops that should be used.
9155 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9156                                              SelectionDAG &DAG) const {
9157   SDLoc dl(Op);
9158   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9159   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9160 
9161   // Check if this is a splat of a constant value.
9162   APInt APSplatBits, APSplatUndef;
9163   unsigned SplatBitSize;
9164   bool HasAnyUndefs;
9165   bool BVNIsConstantSplat =
9166       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9167                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9168 
9169   // If it is a splat of a double, check if we can shrink it to a 32 bit
9170   // non-denormal float which when converted back to double gives us the same
9171   // double. This is to exploit the XXSPLTIDP instruction.
9172   // If we lose precision, we use XXSPLTI32DX.
9173   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9174       Subtarget.hasPrefixInstrs()) {
9175     // Check the type first to short-circuit so we don't modify APSplatBits if
9176     // this block isn't executed.
9177     if ((Op->getValueType(0) == MVT::v2f64) &&
9178         convertToNonDenormSingle(APSplatBits)) {
9179       SDValue SplatNode = DAG.getNode(
9180           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9181           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9182       return DAG.getBitcast(Op.getValueType(), SplatNode);
9183     } else {
9184       // We may lose precision, so we have to use XXSPLTI32DX.
9185 
9186       uint32_t Hi =
9187           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9188       uint32_t Lo =
9189           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9190       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9191 
9192       if (!Hi || !Lo)
9193         // If either load is 0, then we should generate XXLXOR to set to 0.
9194         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9195 
9196       if (Hi)
9197         SplatNode = DAG.getNode(
9198             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9199             DAG.getTargetConstant(0, dl, MVT::i32),
9200             DAG.getTargetConstant(Hi, dl, MVT::i32));
9201 
9202       if (Lo)
9203         SplatNode =
9204             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9205                         DAG.getTargetConstant(1, dl, MVT::i32),
9206                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9207 
9208       return DAG.getBitcast(Op.getValueType(), SplatNode);
9209     }
9210   }
9211 
9212   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9213     unsigned NewOpcode = PPCISD::LD_SPLAT;
9214 
9215     // Handle load-and-splat patterns as we have instructions that will do this
9216     // in one go.
9217     if (DAG.isSplatValue(Op, true) &&
9218         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9219       const SDValue *InputLoad = &Op.getOperand(0);
9220       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9221 
9222       // If the input load is an extending load, it will be an i32 -> i64
9223       // extending load and isValidSplatLoad() will update NewOpcode.
9224       unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9225       unsigned ElementSize =
9226           MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9227 
9228       assert(((ElementSize == 2 * MemorySize)
9229                   ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9230                      NewOpcode == PPCISD::SEXT_LD_SPLAT)
9231                   : (NewOpcode == PPCISD::LD_SPLAT)) &&
9232              "Unmatched element size and opcode!\n");
9233 
9234       // Checking for a single use of this load, we have to check for vector
9235       // width (128 bits) / ElementSize uses (since each operand of the
9236       // BUILD_VECTOR is a separate use of the value.
9237       unsigned NumUsesOfInputLD = 128 / ElementSize;
9238       for (SDValue BVInOp : Op->ops())
9239         if (BVInOp.isUndef())
9240           NumUsesOfInputLD--;
9241 
9242       // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9243       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9244       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9245       // 15", but funciton IsValidSplatLoad() now will only return true when
9246       // the data at index 0 is not nullptr. So we will not get into trouble for
9247       // these cases.
9248       //
9249       // case 1 - lfiwzx/lfiwax
9250       // 1.1: load result is i32 and is sign/zero extend to i64;
9251       // 1.2: build a v2i64 vector type with above loaded value;
9252       // 1.3: the vector has only one value at index 0, others are all undef;
9253       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9254       if (NumUsesOfInputLD == 1 &&
9255           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9256            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9257            Subtarget.hasLFIWAX()))
9258         return SDValue();
9259 
9260       // case 2 - lxvr[hb]x
9261       // 2.1: load result is at most i16;
9262       // 2.2: build a vector with above loaded value;
9263       // 2.3: the vector has only one value at index 0, others are all undef;
9264       // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9265       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9266           Subtarget.isISA3_1() && ElementSize <= 16)
9267         return SDValue();
9268 
9269       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9270       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9271           Subtarget.hasVSX()) {
9272         SDValue Ops[] = {
9273           LD->getChain(),    // Chain
9274           LD->getBasePtr(),  // Ptr
9275           DAG.getValueType(Op.getValueType()) // VT
9276         };
9277         SDValue LdSplt = DAG.getMemIntrinsicNode(
9278             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9279             LD->getMemoryVT(), LD->getMemOperand());
9280         // Replace all uses of the output chain of the original load with the
9281         // output chain of the new load.
9282         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9283                                       LdSplt.getValue(1));
9284         return LdSplt;
9285       }
9286     }
9287 
9288     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9289     // 32-bits can be lowered to VSX instructions under certain conditions.
9290     // Without VSX, there is no pattern more efficient than expanding the node.
9291     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9292         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9293                                         Subtarget.hasP8Vector()))
9294       return Op;
9295     return SDValue();
9296   }
9297 
9298   uint64_t SplatBits = APSplatBits.getZExtValue();
9299   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9300   unsigned SplatSize = SplatBitSize / 8;
9301 
9302   // First, handle single instruction cases.
9303 
9304   // All zeros?
9305   if (SplatBits == 0) {
9306     // Canonicalize all zero vectors to be v4i32.
9307     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9308       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9309       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9310     }
9311     return Op;
9312   }
9313 
9314   // We have XXSPLTIW for constant splats four bytes wide.
9315   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9316   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9317   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9318   // turned into a 4-byte splat of 0xABABABAB.
9319   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9320     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9321                                   Op.getValueType(), DAG, dl);
9322 
9323   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9324     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9325                                   dl);
9326 
9327   // We have XXSPLTIB for constant splats one byte wide.
9328   if (Subtarget.hasP9Vector() && SplatSize == 1)
9329     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9330                                   dl);
9331 
9332   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9333   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9334                     (32-SplatBitSize));
9335   if (SextVal >= -16 && SextVal <= 15)
9336     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9337                                   dl);
9338 
9339   // Two instruction sequences.
9340 
9341   // If this value is in the range [-32,30] and is even, use:
9342   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9343   // If this value is in the range [17,31] and is odd, use:
9344   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9345   // If this value is in the range [-31,-17] and is odd, use:
9346   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9347   // Note the last two are three-instruction sequences.
9348   if (SextVal >= -32 && SextVal <= 31) {
9349     // To avoid having these optimizations undone by constant folding,
9350     // we convert to a pseudo that will be expanded later into one of
9351     // the above forms.
9352     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9353     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9354               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9355     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9356     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9357     if (VT == Op.getValueType())
9358       return RetVal;
9359     else
9360       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9361   }
9362 
9363   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9364   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9365   // for fneg/fabs.
9366   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9367     // Make -1 and vspltisw -1:
9368     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9369 
9370     // Make the VSLW intrinsic, computing 0x8000_0000.
9371     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9372                                    OnesV, DAG, dl);
9373 
9374     // xor by OnesV to invert it.
9375     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9376     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9377   }
9378 
9379   // Check to see if this is a wide variety of vsplti*, binop self cases.
9380   static const signed char SplatCsts[] = {
9381     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9382     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9383   };
9384 
9385   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9386     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9387     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9388     int i = SplatCsts[idx];
9389 
9390     // Figure out what shift amount will be used by altivec if shifted by i in
9391     // this splat size.
9392     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9393 
9394     // vsplti + shl self.
9395     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9396       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9397       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9398         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9399         Intrinsic::ppc_altivec_vslw
9400       };
9401       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9402       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9403     }
9404 
9405     // vsplti + srl self.
9406     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9407       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9408       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9409         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9410         Intrinsic::ppc_altivec_vsrw
9411       };
9412       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9413       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9414     }
9415 
9416     // vsplti + rol self.
9417     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9418                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9419       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9420       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9421         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9422         Intrinsic::ppc_altivec_vrlw
9423       };
9424       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9425       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9426     }
9427 
9428     // t = vsplti c, result = vsldoi t, t, 1
9429     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9430       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9431       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9432       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9433     }
9434     // t = vsplti c, result = vsldoi t, t, 2
9435     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9436       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9437       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9438       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9439     }
9440     // t = vsplti c, result = vsldoi t, t, 3
9441     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9442       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9443       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9444       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9445     }
9446   }
9447 
9448   return SDValue();
9449 }
9450 
9451 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9452 /// the specified operations to build the shuffle.
9453 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9454                                       SDValue RHS, SelectionDAG &DAG,
9455                                       const SDLoc &dl) {
9456   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9457   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9458   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9459 
9460   enum {
9461     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9462     OP_VMRGHW,
9463     OP_VMRGLW,
9464     OP_VSPLTISW0,
9465     OP_VSPLTISW1,
9466     OP_VSPLTISW2,
9467     OP_VSPLTISW3,
9468     OP_VSLDOI4,
9469     OP_VSLDOI8,
9470     OP_VSLDOI12
9471   };
9472 
9473   if (OpNum == OP_COPY) {
9474     if (LHSID == (1*9+2)*9+3) return LHS;
9475     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9476     return RHS;
9477   }
9478 
9479   SDValue OpLHS, OpRHS;
9480   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9481   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9482 
9483   int ShufIdxs[16];
9484   switch (OpNum) {
9485   default: llvm_unreachable("Unknown i32 permute!");
9486   case OP_VMRGHW:
9487     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9488     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9489     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9490     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9491     break;
9492   case OP_VMRGLW:
9493     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9494     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9495     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9496     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9497     break;
9498   case OP_VSPLTISW0:
9499     for (unsigned i = 0; i != 16; ++i)
9500       ShufIdxs[i] = (i&3)+0;
9501     break;
9502   case OP_VSPLTISW1:
9503     for (unsigned i = 0; i != 16; ++i)
9504       ShufIdxs[i] = (i&3)+4;
9505     break;
9506   case OP_VSPLTISW2:
9507     for (unsigned i = 0; i != 16; ++i)
9508       ShufIdxs[i] = (i&3)+8;
9509     break;
9510   case OP_VSPLTISW3:
9511     for (unsigned i = 0; i != 16; ++i)
9512       ShufIdxs[i] = (i&3)+12;
9513     break;
9514   case OP_VSLDOI4:
9515     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9516   case OP_VSLDOI8:
9517     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9518   case OP_VSLDOI12:
9519     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9520   }
9521   EVT VT = OpLHS.getValueType();
9522   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9523   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9524   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9525   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9526 }
9527 
9528 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9529 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9530 /// SDValue.
9531 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9532                                            SelectionDAG &DAG) const {
9533   const unsigned BytesInVector = 16;
9534   bool IsLE = Subtarget.isLittleEndian();
9535   SDLoc dl(N);
9536   SDValue V1 = N->getOperand(0);
9537   SDValue V2 = N->getOperand(1);
9538   unsigned ShiftElts = 0, InsertAtByte = 0;
9539   bool Swap = false;
9540 
9541   // Shifts required to get the byte we want at element 7.
9542   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9543                                    0, 15, 14, 13, 12, 11, 10, 9};
9544   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9545                                 1, 2,  3,  4,  5,  6,  7,  8};
9546 
9547   ArrayRef<int> Mask = N->getMask();
9548   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9549 
9550   // For each mask element, find out if we're just inserting something
9551   // from V2 into V1 or vice versa.
9552   // Possible permutations inserting an element from V2 into V1:
9553   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9554   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9555   //   ...
9556   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9557   // Inserting from V1 into V2 will be similar, except mask range will be
9558   // [16,31].
9559 
9560   bool FoundCandidate = false;
9561   // If both vector operands for the shuffle are the same vector, the mask
9562   // will contain only elements from the first one and the second one will be
9563   // undef.
9564   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9565   // Go through the mask of half-words to find an element that's being moved
9566   // from one vector to the other.
9567   for (unsigned i = 0; i < BytesInVector; ++i) {
9568     unsigned CurrentElement = Mask[i];
9569     // If 2nd operand is undefined, we should only look for element 7 in the
9570     // Mask.
9571     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9572       continue;
9573 
9574     bool OtherElementsInOrder = true;
9575     // Examine the other elements in the Mask to see if they're in original
9576     // order.
9577     for (unsigned j = 0; j < BytesInVector; ++j) {
9578       if (j == i)
9579         continue;
9580       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9581       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9582       // in which we always assume we're always picking from the 1st operand.
9583       int MaskOffset =
9584           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9585       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9586         OtherElementsInOrder = false;
9587         break;
9588       }
9589     }
9590     // If other elements are in original order, we record the number of shifts
9591     // we need to get the element we want into element 7. Also record which byte
9592     // in the vector we should insert into.
9593     if (OtherElementsInOrder) {
9594       // If 2nd operand is undefined, we assume no shifts and no swapping.
9595       if (V2.isUndef()) {
9596         ShiftElts = 0;
9597         Swap = false;
9598       } else {
9599         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9600         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9601                          : BigEndianShifts[CurrentElement & 0xF];
9602         Swap = CurrentElement < BytesInVector;
9603       }
9604       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9605       FoundCandidate = true;
9606       break;
9607     }
9608   }
9609 
9610   if (!FoundCandidate)
9611     return SDValue();
9612 
9613   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9614   // optionally with VECSHL if shift is required.
9615   if (Swap)
9616     std::swap(V1, V2);
9617   if (V2.isUndef())
9618     V2 = V1;
9619   if (ShiftElts) {
9620     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9621                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9622     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9623                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9624   }
9625   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9626                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9627 }
9628 
9629 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9630 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9631 /// SDValue.
9632 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9633                                            SelectionDAG &DAG) const {
9634   const unsigned NumHalfWords = 8;
9635   const unsigned BytesInVector = NumHalfWords * 2;
9636   // Check that the shuffle is on half-words.
9637   if (!isNByteElemShuffleMask(N, 2, 1))
9638     return SDValue();
9639 
9640   bool IsLE = Subtarget.isLittleEndian();
9641   SDLoc dl(N);
9642   SDValue V1 = N->getOperand(0);
9643   SDValue V2 = N->getOperand(1);
9644   unsigned ShiftElts = 0, InsertAtByte = 0;
9645   bool Swap = false;
9646 
9647   // Shifts required to get the half-word we want at element 3.
9648   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9649   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9650 
9651   uint32_t Mask = 0;
9652   uint32_t OriginalOrderLow = 0x1234567;
9653   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9654   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9655   // 32-bit space, only need 4-bit nibbles per element.
9656   for (unsigned i = 0; i < NumHalfWords; ++i) {
9657     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9658     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9659   }
9660 
9661   // For each mask element, find out if we're just inserting something
9662   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9663   // from V2 into V1:
9664   //   X, 1, 2, 3, 4, 5, 6, 7
9665   //   0, X, 2, 3, 4, 5, 6, 7
9666   //   0, 1, X, 3, 4, 5, 6, 7
9667   //   0, 1, 2, X, 4, 5, 6, 7
9668   //   0, 1, 2, 3, X, 5, 6, 7
9669   //   0, 1, 2, 3, 4, X, 6, 7
9670   //   0, 1, 2, 3, 4, 5, X, 7
9671   //   0, 1, 2, 3, 4, 5, 6, X
9672   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9673 
9674   bool FoundCandidate = false;
9675   // Go through the mask of half-words to find an element that's being moved
9676   // from one vector to the other.
9677   for (unsigned i = 0; i < NumHalfWords; ++i) {
9678     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9679     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9680     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9681     uint32_t TargetOrder = 0x0;
9682 
9683     // If both vector operands for the shuffle are the same vector, the mask
9684     // will contain only elements from the first one and the second one will be
9685     // undef.
9686     if (V2.isUndef()) {
9687       ShiftElts = 0;
9688       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9689       TargetOrder = OriginalOrderLow;
9690       Swap = false;
9691       // Skip if not the correct element or mask of other elements don't equal
9692       // to our expected order.
9693       if (MaskOneElt == VINSERTHSrcElem &&
9694           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9695         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9696         FoundCandidate = true;
9697         break;
9698       }
9699     } else { // If both operands are defined.
9700       // Target order is [8,15] if the current mask is between [0,7].
9701       TargetOrder =
9702           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9703       // Skip if mask of other elements don't equal our expected order.
9704       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9705         // We only need the last 3 bits for the number of shifts.
9706         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9707                          : BigEndianShifts[MaskOneElt & 0x7];
9708         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9709         Swap = MaskOneElt < NumHalfWords;
9710         FoundCandidate = true;
9711         break;
9712       }
9713     }
9714   }
9715 
9716   if (!FoundCandidate)
9717     return SDValue();
9718 
9719   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9720   // optionally with VECSHL if shift is required.
9721   if (Swap)
9722     std::swap(V1, V2);
9723   if (V2.isUndef())
9724     V2 = V1;
9725   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9726   if (ShiftElts) {
9727     // Double ShiftElts because we're left shifting on v16i8 type.
9728     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9729                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9730     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9731     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9732                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9733     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9734   }
9735   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9736   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9737                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9738   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9739 }
9740 
9741 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9742 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9743 /// return the default SDValue.
9744 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9745                                               SelectionDAG &DAG) const {
9746   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9747   // to v16i8. Peek through the bitcasts to get the actual operands.
9748   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9749   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9750 
9751   auto ShuffleMask = SVN->getMask();
9752   SDValue VecShuffle(SVN, 0);
9753   SDLoc DL(SVN);
9754 
9755   // Check that we have a four byte shuffle.
9756   if (!isNByteElemShuffleMask(SVN, 4, 1))
9757     return SDValue();
9758 
9759   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9760   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9761     std::swap(LHS, RHS);
9762     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9763     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9764   }
9765 
9766   // Ensure that the RHS is a vector of constants.
9767   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9768   if (!BVN)
9769     return SDValue();
9770 
9771   // Check if RHS is a splat of 4-bytes (or smaller).
9772   APInt APSplatValue, APSplatUndef;
9773   unsigned SplatBitSize;
9774   bool HasAnyUndefs;
9775   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9776                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9777       SplatBitSize > 32)
9778     return SDValue();
9779 
9780   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9781   // The instruction splats a constant C into two words of the source vector
9782   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9783   // Thus we check that the shuffle mask is the equivalent  of
9784   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9785   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9786   // within each word are consecutive, so we only need to check the first byte.
9787   SDValue Index;
9788   bool IsLE = Subtarget.isLittleEndian();
9789   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9790       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9791        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9792     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9793   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9794            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9795             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9796     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9797   else
9798     return SDValue();
9799 
9800   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9801   // for XXSPLTI32DX.
9802   unsigned SplatVal = APSplatValue.getZExtValue();
9803   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9804     SplatVal |= (SplatVal << SplatBitSize);
9805 
9806   SDValue SplatNode = DAG.getNode(
9807       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9808       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9809   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9810 }
9811 
9812 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9813 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9814 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9815 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9816 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9817   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9818   assert(Op.getValueType() == MVT::v1i128 &&
9819          "Only set v1i128 as custom, other type shouldn't reach here!");
9820   SDLoc dl(Op);
9821   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9822   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9823   unsigned SHLAmt = N1.getConstantOperandVal(0);
9824   if (SHLAmt % 8 == 0) {
9825     std::array<int, 16> Mask;
9826     std::iota(Mask.begin(), Mask.end(), 0);
9827     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9828     if (SDValue Shuffle =
9829             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9830                                  DAG.getUNDEF(MVT::v16i8), Mask))
9831       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9832   }
9833   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9834   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9835                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9836   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9837                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9838   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9839   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9840 }
9841 
9842 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9843 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9844 /// return the code it can be lowered into.  Worst case, it can always be
9845 /// lowered into a vperm.
9846 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9847                                                SelectionDAG &DAG) const {
9848   SDLoc dl(Op);
9849   SDValue V1 = Op.getOperand(0);
9850   SDValue V2 = Op.getOperand(1);
9851   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9852 
9853   // Any nodes that were combined in the target-independent combiner prior
9854   // to vector legalization will not be sent to the target combine. Try to
9855   // combine it here.
9856   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9857     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9858       return NewShuffle;
9859     Op = NewShuffle;
9860     SVOp = cast<ShuffleVectorSDNode>(Op);
9861     V1 = Op.getOperand(0);
9862     V2 = Op.getOperand(1);
9863   }
9864   EVT VT = Op.getValueType();
9865   bool isLittleEndian = Subtarget.isLittleEndian();
9866 
9867   unsigned ShiftElts, InsertAtByte;
9868   bool Swap = false;
9869 
9870   // If this is a load-and-splat, we can do that with a single instruction
9871   // in some cases. However if the load has multiple uses, we don't want to
9872   // combine it because that will just produce multiple loads.
9873   bool IsPermutedLoad = false;
9874   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9875   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9876       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9877       InputLoad->hasOneUse()) {
9878     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9879     int SplatIdx =
9880       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9881 
9882     // The splat index for permuted loads will be in the left half of the vector
9883     // which is strictly wider than the loaded value by 8 bytes. So we need to
9884     // adjust the splat index to point to the correct address in memory.
9885     if (IsPermutedLoad) {
9886       assert((isLittleEndian || IsFourByte) &&
9887              "Unexpected size for permuted load on big endian target");
9888       SplatIdx += IsFourByte ? 2 : 1;
9889       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9890              "Splat of a value outside of the loaded memory");
9891     }
9892 
9893     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9894     // For 4-byte load-and-splat, we need Power9.
9895     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9896       uint64_t Offset = 0;
9897       if (IsFourByte)
9898         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9899       else
9900         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9901 
9902       // If the width of the load is the same as the width of the splat,
9903       // loading with an offset would load the wrong memory.
9904       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9905         Offset = 0;
9906 
9907       SDValue BasePtr = LD->getBasePtr();
9908       if (Offset != 0)
9909         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9910                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9911       SDValue Ops[] = {
9912         LD->getChain(),    // Chain
9913         BasePtr,           // BasePtr
9914         DAG.getValueType(Op.getValueType()) // VT
9915       };
9916       SDVTList VTL =
9917         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9918       SDValue LdSplt =
9919         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9920                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9921       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9922       if (LdSplt.getValueType() != SVOp->getValueType(0))
9923         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9924       return LdSplt;
9925     }
9926   }
9927   if (Subtarget.hasP9Vector() &&
9928       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9929                            isLittleEndian)) {
9930     if (Swap)
9931       std::swap(V1, V2);
9932     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9933     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9934     if (ShiftElts) {
9935       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9936                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9937       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9938                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9939       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9940     }
9941     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9942                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9943     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9944   }
9945 
9946   if (Subtarget.hasPrefixInstrs()) {
9947     SDValue SplatInsertNode;
9948     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9949       return SplatInsertNode;
9950   }
9951 
9952   if (Subtarget.hasP9Altivec()) {
9953     SDValue NewISDNode;
9954     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9955       return NewISDNode;
9956 
9957     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9958       return NewISDNode;
9959   }
9960 
9961   if (Subtarget.hasVSX() &&
9962       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9963     if (Swap)
9964       std::swap(V1, V2);
9965     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9966     SDValue Conv2 =
9967         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9968 
9969     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9970                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9971     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9972   }
9973 
9974   if (Subtarget.hasVSX() &&
9975     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9976     if (Swap)
9977       std::swap(V1, V2);
9978     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9979     SDValue Conv2 =
9980         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9981 
9982     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9983                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9984     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9985   }
9986 
9987   if (Subtarget.hasP9Vector()) {
9988      if (PPC::isXXBRHShuffleMask(SVOp)) {
9989       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9990       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9991       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9992     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9993       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9994       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9995       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9996     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9997       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9998       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9999       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10000     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10001       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10002       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10003       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10004     }
10005   }
10006 
10007   if (Subtarget.hasVSX()) {
10008     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10009       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10010 
10011       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10012       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10013                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10014       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10015     }
10016 
10017     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10018     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10019       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10020       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10021       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10022     }
10023   }
10024 
10025   // Cases that are handled by instructions that take permute immediates
10026   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10027   // selected by the instruction selector.
10028   if (V2.isUndef()) {
10029     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10030         PPC::isSplatShuffleMask(SVOp, 2) ||
10031         PPC::isSplatShuffleMask(SVOp, 4) ||
10032         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10033         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10034         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10035         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10036         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10037         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10038         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10039         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10040         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10041         (Subtarget.hasP8Altivec() && (
10042          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10043          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10044          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10045       return Op;
10046     }
10047   }
10048 
10049   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10050   // and produce a fixed permutation.  If any of these match, do not lower to
10051   // VPERM.
10052   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10053   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10054       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10055       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10056       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10057       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10058       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10059       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10060       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10061       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10062       (Subtarget.hasP8Altivec() && (
10063        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10064        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10065        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10066     return Op;
10067 
10068   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10069   // perfect shuffle table to emit an optimal matching sequence.
10070   ArrayRef<int> PermMask = SVOp->getMask();
10071 
10072   if (!DisablePerfectShuffle && !isLittleEndian) {
10073     unsigned PFIndexes[4];
10074     bool isFourElementShuffle = true;
10075     for (unsigned i = 0; i != 4 && isFourElementShuffle;
10076          ++i) {                           // Element number
10077       unsigned EltNo = 8;                 // Start out undef.
10078       for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10079         if (PermMask[i * 4 + j] < 0)
10080           continue; // Undef, ignore it.
10081 
10082         unsigned ByteSource = PermMask[i * 4 + j];
10083         if ((ByteSource & 3) != j) {
10084           isFourElementShuffle = false;
10085           break;
10086         }
10087 
10088         if (EltNo == 8) {
10089           EltNo = ByteSource / 4;
10090         } else if (EltNo != ByteSource / 4) {
10091           isFourElementShuffle = false;
10092           break;
10093         }
10094       }
10095       PFIndexes[i] = EltNo;
10096     }
10097 
10098     // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10099     // perfect shuffle vector to determine if it is cost effective to do this as
10100     // discrete instructions, or whether we should use a vperm.
10101     // For now, we skip this for little endian until such time as we have a
10102     // little-endian perfect shuffle table.
10103     if (isFourElementShuffle) {
10104       // Compute the index in the perfect shuffle table.
10105       unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10106                               PFIndexes[2] * 9 + PFIndexes[3];
10107 
10108       unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10109       unsigned Cost = (PFEntry >> 30);
10110 
10111       // Determining when to avoid vperm is tricky.  Many things affect the cost
10112       // of vperm, particularly how many times the perm mask needs to be
10113       // computed. For example, if the perm mask can be hoisted out of a loop or
10114       // is already used (perhaps because there are multiple permutes with the
10115       // same shuffle mask?) the vperm has a cost of 1.  OTOH, hoisting the
10116       // permute mask out of the loop requires an extra register.
10117       //
10118       // As a compromise, we only emit discrete instructions if the shuffle can
10119       // be generated in 3 or fewer operations.  When we have loop information
10120       // available, if this block is within a loop, we should avoid using vperm
10121       // for 3-operation perms and use a constant pool load instead.
10122       if (Cost < 3)
10123         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10124     }
10125   }
10126 
10127   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10128   // vector that will get spilled to the constant pool.
10129   if (V2.isUndef()) V2 = V1;
10130 
10131   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10132   // that it is in input element units, not in bytes.  Convert now.
10133 
10134   // For little endian, the order of the input vectors is reversed, and
10135   // the permutation mask is complemented with respect to 31.  This is
10136   // necessary to produce proper semantics with the big-endian-biased vperm
10137   // instruction.
10138   EVT EltVT = V1.getValueType().getVectorElementType();
10139   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10140 
10141   SmallVector<SDValue, 16> ResultMask;
10142   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10143     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10144 
10145     for (unsigned j = 0; j != BytesPerElement; ++j)
10146       if (isLittleEndian)
10147         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10148                                              dl, MVT::i32));
10149       else
10150         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10151                                              MVT::i32));
10152   }
10153 
10154   ShufflesHandledWithVPERM++;
10155   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10156   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10157   LLVM_DEBUG(SVOp->dump());
10158   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10159   LLVM_DEBUG(VPermMask.dump());
10160 
10161   if (isLittleEndian)
10162     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10163                        V2, V1, VPermMask);
10164   else
10165     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10166                        V1, V2, VPermMask);
10167 }
10168 
10169 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10170 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10171 /// information about the intrinsic.
10172 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10173                                  bool &isDot, const PPCSubtarget &Subtarget) {
10174   unsigned IntrinsicID =
10175       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10176   CompareOpc = -1;
10177   isDot = false;
10178   switch (IntrinsicID) {
10179   default:
10180     return false;
10181   // Comparison predicates.
10182   case Intrinsic::ppc_altivec_vcmpbfp_p:
10183     CompareOpc = 966;
10184     isDot = true;
10185     break;
10186   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10187     CompareOpc = 198;
10188     isDot = true;
10189     break;
10190   case Intrinsic::ppc_altivec_vcmpequb_p:
10191     CompareOpc = 6;
10192     isDot = true;
10193     break;
10194   case Intrinsic::ppc_altivec_vcmpequh_p:
10195     CompareOpc = 70;
10196     isDot = true;
10197     break;
10198   case Intrinsic::ppc_altivec_vcmpequw_p:
10199     CompareOpc = 134;
10200     isDot = true;
10201     break;
10202   case Intrinsic::ppc_altivec_vcmpequd_p:
10203     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10204       CompareOpc = 199;
10205       isDot = true;
10206     } else
10207       return false;
10208     break;
10209   case Intrinsic::ppc_altivec_vcmpneb_p:
10210   case Intrinsic::ppc_altivec_vcmpneh_p:
10211   case Intrinsic::ppc_altivec_vcmpnew_p:
10212   case Intrinsic::ppc_altivec_vcmpnezb_p:
10213   case Intrinsic::ppc_altivec_vcmpnezh_p:
10214   case Intrinsic::ppc_altivec_vcmpnezw_p:
10215     if (Subtarget.hasP9Altivec()) {
10216       switch (IntrinsicID) {
10217       default:
10218         llvm_unreachable("Unknown comparison intrinsic.");
10219       case Intrinsic::ppc_altivec_vcmpneb_p:
10220         CompareOpc = 7;
10221         break;
10222       case Intrinsic::ppc_altivec_vcmpneh_p:
10223         CompareOpc = 71;
10224         break;
10225       case Intrinsic::ppc_altivec_vcmpnew_p:
10226         CompareOpc = 135;
10227         break;
10228       case Intrinsic::ppc_altivec_vcmpnezb_p:
10229         CompareOpc = 263;
10230         break;
10231       case Intrinsic::ppc_altivec_vcmpnezh_p:
10232         CompareOpc = 327;
10233         break;
10234       case Intrinsic::ppc_altivec_vcmpnezw_p:
10235         CompareOpc = 391;
10236         break;
10237       }
10238       isDot = true;
10239     } else
10240       return false;
10241     break;
10242   case Intrinsic::ppc_altivec_vcmpgefp_p:
10243     CompareOpc = 454;
10244     isDot = true;
10245     break;
10246   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10247     CompareOpc = 710;
10248     isDot = true;
10249     break;
10250   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10251     CompareOpc = 774;
10252     isDot = true;
10253     break;
10254   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10255     CompareOpc = 838;
10256     isDot = true;
10257     break;
10258   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10259     CompareOpc = 902;
10260     isDot = true;
10261     break;
10262   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10263     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10264       CompareOpc = 967;
10265       isDot = true;
10266     } else
10267       return false;
10268     break;
10269   case Intrinsic::ppc_altivec_vcmpgtub_p:
10270     CompareOpc = 518;
10271     isDot = true;
10272     break;
10273   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10274     CompareOpc = 582;
10275     isDot = true;
10276     break;
10277   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10278     CompareOpc = 646;
10279     isDot = true;
10280     break;
10281   case Intrinsic::ppc_altivec_vcmpgtud_p:
10282     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10283       CompareOpc = 711;
10284       isDot = true;
10285     } else
10286       return false;
10287     break;
10288 
10289   case Intrinsic::ppc_altivec_vcmpequq:
10290   case Intrinsic::ppc_altivec_vcmpgtsq:
10291   case Intrinsic::ppc_altivec_vcmpgtuq:
10292     if (!Subtarget.isISA3_1())
10293       return false;
10294     switch (IntrinsicID) {
10295     default:
10296       llvm_unreachable("Unknown comparison intrinsic.");
10297     case Intrinsic::ppc_altivec_vcmpequq:
10298       CompareOpc = 455;
10299       break;
10300     case Intrinsic::ppc_altivec_vcmpgtsq:
10301       CompareOpc = 903;
10302       break;
10303     case Intrinsic::ppc_altivec_vcmpgtuq:
10304       CompareOpc = 647;
10305       break;
10306     }
10307     break;
10308 
10309   // VSX predicate comparisons use the same infrastructure
10310   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10311   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10312   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10313   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10314   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10315   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10316     if (Subtarget.hasVSX()) {
10317       switch (IntrinsicID) {
10318       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10319         CompareOpc = 99;
10320         break;
10321       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10322         CompareOpc = 115;
10323         break;
10324       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10325         CompareOpc = 107;
10326         break;
10327       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10328         CompareOpc = 67;
10329         break;
10330       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10331         CompareOpc = 83;
10332         break;
10333       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10334         CompareOpc = 75;
10335         break;
10336       }
10337       isDot = true;
10338     } else
10339       return false;
10340     break;
10341 
10342   // Normal Comparisons.
10343   case Intrinsic::ppc_altivec_vcmpbfp:
10344     CompareOpc = 966;
10345     break;
10346   case Intrinsic::ppc_altivec_vcmpeqfp:
10347     CompareOpc = 198;
10348     break;
10349   case Intrinsic::ppc_altivec_vcmpequb:
10350     CompareOpc = 6;
10351     break;
10352   case Intrinsic::ppc_altivec_vcmpequh:
10353     CompareOpc = 70;
10354     break;
10355   case Intrinsic::ppc_altivec_vcmpequw:
10356     CompareOpc = 134;
10357     break;
10358   case Intrinsic::ppc_altivec_vcmpequd:
10359     if (Subtarget.hasP8Altivec())
10360       CompareOpc = 199;
10361     else
10362       return false;
10363     break;
10364   case Intrinsic::ppc_altivec_vcmpneb:
10365   case Intrinsic::ppc_altivec_vcmpneh:
10366   case Intrinsic::ppc_altivec_vcmpnew:
10367   case Intrinsic::ppc_altivec_vcmpnezb:
10368   case Intrinsic::ppc_altivec_vcmpnezh:
10369   case Intrinsic::ppc_altivec_vcmpnezw:
10370     if (Subtarget.hasP9Altivec())
10371       switch (IntrinsicID) {
10372       default:
10373         llvm_unreachable("Unknown comparison intrinsic.");
10374       case Intrinsic::ppc_altivec_vcmpneb:
10375         CompareOpc = 7;
10376         break;
10377       case Intrinsic::ppc_altivec_vcmpneh:
10378         CompareOpc = 71;
10379         break;
10380       case Intrinsic::ppc_altivec_vcmpnew:
10381         CompareOpc = 135;
10382         break;
10383       case Intrinsic::ppc_altivec_vcmpnezb:
10384         CompareOpc = 263;
10385         break;
10386       case Intrinsic::ppc_altivec_vcmpnezh:
10387         CompareOpc = 327;
10388         break;
10389       case Intrinsic::ppc_altivec_vcmpnezw:
10390         CompareOpc = 391;
10391         break;
10392       }
10393     else
10394       return false;
10395     break;
10396   case Intrinsic::ppc_altivec_vcmpgefp:
10397     CompareOpc = 454;
10398     break;
10399   case Intrinsic::ppc_altivec_vcmpgtfp:
10400     CompareOpc = 710;
10401     break;
10402   case Intrinsic::ppc_altivec_vcmpgtsb:
10403     CompareOpc = 774;
10404     break;
10405   case Intrinsic::ppc_altivec_vcmpgtsh:
10406     CompareOpc = 838;
10407     break;
10408   case Intrinsic::ppc_altivec_vcmpgtsw:
10409     CompareOpc = 902;
10410     break;
10411   case Intrinsic::ppc_altivec_vcmpgtsd:
10412     if (Subtarget.hasP8Altivec())
10413       CompareOpc = 967;
10414     else
10415       return false;
10416     break;
10417   case Intrinsic::ppc_altivec_vcmpgtub:
10418     CompareOpc = 518;
10419     break;
10420   case Intrinsic::ppc_altivec_vcmpgtuh:
10421     CompareOpc = 582;
10422     break;
10423   case Intrinsic::ppc_altivec_vcmpgtuw:
10424     CompareOpc = 646;
10425     break;
10426   case Intrinsic::ppc_altivec_vcmpgtud:
10427     if (Subtarget.hasP8Altivec())
10428       CompareOpc = 711;
10429     else
10430       return false;
10431     break;
10432   case Intrinsic::ppc_altivec_vcmpequq_p:
10433   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10434   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10435     if (!Subtarget.isISA3_1())
10436       return false;
10437     switch (IntrinsicID) {
10438     default:
10439       llvm_unreachable("Unknown comparison intrinsic.");
10440     case Intrinsic::ppc_altivec_vcmpequq_p:
10441       CompareOpc = 455;
10442       break;
10443     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10444       CompareOpc = 903;
10445       break;
10446     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10447       CompareOpc = 647;
10448       break;
10449     }
10450     isDot = true;
10451     break;
10452   }
10453   return true;
10454 }
10455 
10456 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10457 /// lower, do it, otherwise return null.
10458 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10459                                                    SelectionDAG &DAG) const {
10460   unsigned IntrinsicID =
10461     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10462 
10463   SDLoc dl(Op);
10464 
10465   switch (IntrinsicID) {
10466   case Intrinsic::thread_pointer:
10467     // Reads the thread pointer register, used for __builtin_thread_pointer.
10468     if (Subtarget.isPPC64())
10469       return DAG.getRegister(PPC::X13, MVT::i64);
10470     return DAG.getRegister(PPC::R2, MVT::i32);
10471 
10472   case Intrinsic::ppc_mma_disassemble_acc:
10473   case Intrinsic::ppc_vsx_disassemble_pair: {
10474     int NumVecs = 2;
10475     SDValue WideVec = Op.getOperand(1);
10476     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10477       NumVecs = 4;
10478       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10479     }
10480     SmallVector<SDValue, 4> RetOps;
10481     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10482       SDValue Extract = DAG.getNode(
10483           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10484           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10485                                                      : VecNo,
10486                           dl, getPointerTy(DAG.getDataLayout())));
10487       RetOps.push_back(Extract);
10488     }
10489     return DAG.getMergeValues(RetOps, dl);
10490   }
10491 
10492   case Intrinsic::ppc_unpack_longdouble: {
10493     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10494     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10495            "Argument of long double unpack must be 0 or 1!");
10496     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10497                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10498                                        Idx->getValueType(0)));
10499   }
10500 
10501   case Intrinsic::ppc_compare_exp_lt:
10502   case Intrinsic::ppc_compare_exp_gt:
10503   case Intrinsic::ppc_compare_exp_eq:
10504   case Intrinsic::ppc_compare_exp_uo: {
10505     unsigned Pred;
10506     switch (IntrinsicID) {
10507     case Intrinsic::ppc_compare_exp_lt:
10508       Pred = PPC::PRED_LT;
10509       break;
10510     case Intrinsic::ppc_compare_exp_gt:
10511       Pred = PPC::PRED_GT;
10512       break;
10513     case Intrinsic::ppc_compare_exp_eq:
10514       Pred = PPC::PRED_EQ;
10515       break;
10516     case Intrinsic::ppc_compare_exp_uo:
10517       Pred = PPC::PRED_UN;
10518       break;
10519     }
10520     return SDValue(
10521         DAG.getMachineNode(
10522             PPC::SELECT_CC_I4, dl, MVT::i32,
10523             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10524                                         Op.getOperand(1), Op.getOperand(2)),
10525                      0),
10526              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10527              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10528         0);
10529   }
10530   case Intrinsic::ppc_test_data_class_d:
10531   case Intrinsic::ppc_test_data_class_f: {
10532     unsigned CmprOpc = PPC::XSTSTDCDP;
10533     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10534       CmprOpc = PPC::XSTSTDCSP;
10535     return SDValue(
10536         DAG.getMachineNode(
10537             PPC::SELECT_CC_I4, dl, MVT::i32,
10538             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10539                                         Op.getOperand(1)),
10540                      0),
10541              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10542              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10543         0);
10544   }
10545   case Intrinsic::ppc_fnmsub: {
10546     EVT VT = Op.getOperand(1).getValueType();
10547     if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
10548       return DAG.getNode(
10549           ISD::FNEG, dl, VT,
10550           DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
10551                       DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
10552     return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
10553                        Op.getOperand(2), Op.getOperand(3));
10554   }
10555   case Intrinsic::ppc_convert_f128_to_ppcf128:
10556   case Intrinsic::ppc_convert_ppcf128_to_f128: {
10557     RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10558                             ? RTLIB::CONVERT_PPCF128_F128
10559                             : RTLIB::CONVERT_F128_PPCF128;
10560     MakeLibCallOptions CallOptions;
10561     std::pair<SDValue, SDValue> Result =
10562         makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10563                     dl, SDValue());
10564     return Result.first;
10565   }
10566   }
10567 
10568   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10569   // opcode number of the comparison.
10570   int CompareOpc;
10571   bool isDot;
10572   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10573     return SDValue();    // Don't custom lower most intrinsics.
10574 
10575   // If this is a non-dot comparison, make the VCMP node and we are done.
10576   if (!isDot) {
10577     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10578                               Op.getOperand(1), Op.getOperand(2),
10579                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10580     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10581   }
10582 
10583   // Create the PPCISD altivec 'dot' comparison node.
10584   SDValue Ops[] = {
10585     Op.getOperand(2),  // LHS
10586     Op.getOperand(3),  // RHS
10587     DAG.getConstant(CompareOpc, dl, MVT::i32)
10588   };
10589   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10590   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10591 
10592   // Now that we have the comparison, emit a copy from the CR to a GPR.
10593   // This is flagged to the above dot comparison.
10594   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10595                                 DAG.getRegister(PPC::CR6, MVT::i32),
10596                                 CompNode.getValue(1));
10597 
10598   // Unpack the result based on how the target uses it.
10599   unsigned BitNo;   // Bit # of CR6.
10600   bool InvertBit;   // Invert result?
10601   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10602   default:  // Can't happen, don't crash on invalid number though.
10603   case 0:   // Return the value of the EQ bit of CR6.
10604     BitNo = 0; InvertBit = false;
10605     break;
10606   case 1:   // Return the inverted value of the EQ bit of CR6.
10607     BitNo = 0; InvertBit = true;
10608     break;
10609   case 2:   // Return the value of the LT bit of CR6.
10610     BitNo = 2; InvertBit = false;
10611     break;
10612   case 3:   // Return the inverted value of the LT bit of CR6.
10613     BitNo = 2; InvertBit = true;
10614     break;
10615   }
10616 
10617   // Shift the bit into the low position.
10618   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10619                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10620   // Isolate the bit.
10621   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10622                       DAG.getConstant(1, dl, MVT::i32));
10623 
10624   // If we are supposed to, toggle the bit.
10625   if (InvertBit)
10626     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10627                         DAG.getConstant(1, dl, MVT::i32));
10628   return Flags;
10629 }
10630 
10631 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10632                                                SelectionDAG &DAG) const {
10633   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10634   // the beginning of the argument list.
10635   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10636   SDLoc DL(Op);
10637   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10638   case Intrinsic::ppc_cfence: {
10639     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10640     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10641     SDValue Val = Op.getOperand(ArgStart + 1);
10642     EVT Ty = Val.getValueType();
10643     if (Ty == MVT::i128) {
10644       // FIXME: Testing one of two paired registers is sufficient to guarantee
10645       // ordering?
10646       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10647     }
10648     return SDValue(
10649         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10650                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10651                            Op.getOperand(0)),
10652         0);
10653   }
10654   default:
10655     break;
10656   }
10657   return SDValue();
10658 }
10659 
10660 // Lower scalar BSWAP64 to xxbrd.
10661 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10662   SDLoc dl(Op);
10663   if (!Subtarget.isPPC64())
10664     return Op;
10665   // MTVSRDD
10666   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10667                    Op.getOperand(0));
10668   // XXBRD
10669   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10670   // MFVSRD
10671   int VectorIndex = 0;
10672   if (Subtarget.isLittleEndian())
10673     VectorIndex = 1;
10674   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10675                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10676   return Op;
10677 }
10678 
10679 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10680 // compared to a value that is atomically loaded (atomic loads zero-extend).
10681 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10682                                                 SelectionDAG &DAG) const {
10683   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10684          "Expecting an atomic compare-and-swap here.");
10685   SDLoc dl(Op);
10686   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10687   EVT MemVT = AtomicNode->getMemoryVT();
10688   if (MemVT.getSizeInBits() >= 32)
10689     return Op;
10690 
10691   SDValue CmpOp = Op.getOperand(2);
10692   // If this is already correctly zero-extended, leave it alone.
10693   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10694   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10695     return Op;
10696 
10697   // Clear the high bits of the compare operand.
10698   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10699   SDValue NewCmpOp =
10700     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10701                 DAG.getConstant(MaskVal, dl, MVT::i32));
10702 
10703   // Replace the existing compare operand with the properly zero-extended one.
10704   SmallVector<SDValue, 4> Ops;
10705   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10706     Ops.push_back(AtomicNode->getOperand(i));
10707   Ops[2] = NewCmpOp;
10708   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10709   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10710   auto NodeTy =
10711     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10712   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10713 }
10714 
10715 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10716                                                   SelectionDAG &DAG) const {
10717   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10718   EVT MemVT = N->getMemoryVT();
10719   assert(MemVT.getSimpleVT() == MVT::i128 &&
10720          "Expect quadword atomic operations");
10721   SDLoc dl(N);
10722   unsigned Opc = N->getOpcode();
10723   switch (Opc) {
10724   case ISD::ATOMIC_LOAD: {
10725     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10726     // lowered to ppc instructions by pattern matching instruction selector.
10727     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10728     SmallVector<SDValue, 4> Ops{
10729         N->getOperand(0),
10730         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10731     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10732       Ops.push_back(N->getOperand(I));
10733     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10734                                                 Ops, MemVT, N->getMemOperand());
10735     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10736     SDValue ValHi =
10737         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10738     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10739                         DAG.getConstant(64, dl, MVT::i32));
10740     SDValue Val =
10741         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10742     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10743                        {Val, LoadedVal.getValue(2)});
10744   }
10745   case ISD::ATOMIC_STORE: {
10746     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10747     // lowered to ppc instructions by pattern matching instruction selector.
10748     SDVTList Tys = DAG.getVTList(MVT::Other);
10749     SmallVector<SDValue, 4> Ops{
10750         N->getOperand(0),
10751         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10752     SDValue Val = N->getOperand(2);
10753     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10754     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10755                                 DAG.getConstant(64, dl, MVT::i32));
10756     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10757     Ops.push_back(ValLo);
10758     Ops.push_back(ValHi);
10759     Ops.push_back(N->getOperand(1));
10760     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10761                                    N->getMemOperand());
10762   }
10763   default:
10764     llvm_unreachable("Unexpected atomic opcode");
10765   }
10766 }
10767 
10768 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10769                                                  SelectionDAG &DAG) const {
10770   SDLoc dl(Op);
10771   // Create a stack slot that is 16-byte aligned.
10772   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10773   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10774   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10775   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10776 
10777   // Store the input value into Value#0 of the stack slot.
10778   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10779                                MachinePointerInfo());
10780   // Load it out.
10781   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10782 }
10783 
10784 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10785                                                   SelectionDAG &DAG) const {
10786   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10787          "Should only be called for ISD::INSERT_VECTOR_ELT");
10788 
10789   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10790 
10791   EVT VT = Op.getValueType();
10792   SDLoc dl(Op);
10793   SDValue V1 = Op.getOperand(0);
10794   SDValue V2 = Op.getOperand(1);
10795 
10796   if (VT == MVT::v2f64 && C)
10797     return Op;
10798 
10799   if (Subtarget.hasP9Vector()) {
10800     // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
10801     // because on P10, it allows this specific insert_vector_elt load pattern to
10802     // utilize the refactored load and store infrastructure in order to exploit
10803     // prefixed loads.
10804     // On targets with inexpensive direct moves (Power9 and up), a
10805     // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
10806     // load since a single precision load will involve conversion to double
10807     // precision on the load followed by another conversion to single precision.
10808     if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
10809         (isa<LoadSDNode>(V2))) {
10810       SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
10811       SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
10812       SDValue InsVecElt =
10813           DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
10814                       BitcastLoad, Op.getOperand(2));
10815       return DAG.getBitcast(MVT::v4f32, InsVecElt);
10816     }
10817   }
10818 
10819   if (Subtarget.isISA3_1()) {
10820     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10821       return SDValue();
10822     // On P10, we have legal lowering for constant and variable indices for
10823     // all vectors.
10824     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10825         VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
10826       return Op;
10827   }
10828 
10829   // Before P10, we have legal lowering for constant indices but not for
10830   // variable ones.
10831   if (!C)
10832     return SDValue();
10833 
10834   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10835   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10836     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10837     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10838     unsigned InsertAtElement = C->getZExtValue();
10839     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10840     if (Subtarget.isLittleEndian()) {
10841       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10842     }
10843     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10844                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10845   }
10846   return Op;
10847 }
10848 
10849 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10850                                            SelectionDAG &DAG) const {
10851   SDLoc dl(Op);
10852   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10853   SDValue LoadChain = LN->getChain();
10854   SDValue BasePtr = LN->getBasePtr();
10855   EVT VT = Op.getValueType();
10856 
10857   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10858     return Op;
10859 
10860   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10861   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10862   // 2 or 4 vsx registers.
10863   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10864          "Type unsupported without MMA");
10865   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10866          "Type unsupported without paired vector support");
10867   Align Alignment = LN->getAlign();
10868   SmallVector<SDValue, 4> Loads;
10869   SmallVector<SDValue, 4> LoadChains;
10870   unsigned NumVecs = VT.getSizeInBits() / 128;
10871   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10872     SDValue Load =
10873         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10874                     LN->getPointerInfo().getWithOffset(Idx * 16),
10875                     commonAlignment(Alignment, Idx * 16),
10876                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10877     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10878                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10879     Loads.push_back(Load);
10880     LoadChains.push_back(Load.getValue(1));
10881   }
10882   if (Subtarget.isLittleEndian()) {
10883     std::reverse(Loads.begin(), Loads.end());
10884     std::reverse(LoadChains.begin(), LoadChains.end());
10885   }
10886   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10887   SDValue Value =
10888       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10889                   dl, VT, Loads);
10890   SDValue RetOps[] = {Value, TF};
10891   return DAG.getMergeValues(RetOps, dl);
10892 }
10893 
10894 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10895                                             SelectionDAG &DAG) const {
10896   SDLoc dl(Op);
10897   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10898   SDValue StoreChain = SN->getChain();
10899   SDValue BasePtr = SN->getBasePtr();
10900   SDValue Value = SN->getValue();
10901   EVT StoreVT = Value.getValueType();
10902 
10903   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10904     return Op;
10905 
10906   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10907   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10908   // underlying registers individually.
10909   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10910          "Type unsupported without MMA");
10911   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10912          "Type unsupported without paired vector support");
10913   Align Alignment = SN->getAlign();
10914   SmallVector<SDValue, 4> Stores;
10915   unsigned NumVecs = 2;
10916   if (StoreVT == MVT::v512i1) {
10917     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10918     NumVecs = 4;
10919   }
10920   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10921     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10922     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10923                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10924     SDValue Store =
10925         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10926                      SN->getPointerInfo().getWithOffset(Idx * 16),
10927                      commonAlignment(Alignment, Idx * 16),
10928                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10929     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10930                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10931     Stores.push_back(Store);
10932   }
10933   SDValue TF = DAG.getTokenFactor(dl, Stores);
10934   return TF;
10935 }
10936 
10937 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10938   SDLoc dl(Op);
10939   if (Op.getValueType() == MVT::v4i32) {
10940     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10941 
10942     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10943     // +16 as shift amt.
10944     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10945     SDValue RHSSwap =   // = vrlw RHS, 16
10946       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10947 
10948     // Shrinkify inputs to v8i16.
10949     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10950     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10951     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10952 
10953     // Low parts multiplied together, generating 32-bit results (we ignore the
10954     // top parts).
10955     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10956                                         LHS, RHS, DAG, dl, MVT::v4i32);
10957 
10958     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10959                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10960     // Shift the high parts up 16 bits.
10961     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10962                               Neg16, DAG, dl);
10963     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10964   } else if (Op.getValueType() == MVT::v16i8) {
10965     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10966     bool isLittleEndian = Subtarget.isLittleEndian();
10967 
10968     // Multiply the even 8-bit parts, producing 16-bit sums.
10969     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10970                                            LHS, RHS, DAG, dl, MVT::v8i16);
10971     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10972 
10973     // Multiply the odd 8-bit parts, producing 16-bit sums.
10974     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10975                                           LHS, RHS, DAG, dl, MVT::v8i16);
10976     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10977 
10978     // Merge the results together.  Because vmuleub and vmuloub are
10979     // instructions with a big-endian bias, we must reverse the
10980     // element numbering and reverse the meaning of "odd" and "even"
10981     // when generating little endian code.
10982     int Ops[16];
10983     for (unsigned i = 0; i != 8; ++i) {
10984       if (isLittleEndian) {
10985         Ops[i*2  ] = 2*i;
10986         Ops[i*2+1] = 2*i+16;
10987       } else {
10988         Ops[i*2  ] = 2*i+1;
10989         Ops[i*2+1] = 2*i+1+16;
10990       }
10991     }
10992     if (isLittleEndian)
10993       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10994     else
10995       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10996   } else {
10997     llvm_unreachable("Unknown mul to lower!");
10998   }
10999 }
11000 
11001 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11002   bool IsStrict = Op->isStrictFPOpcode();
11003   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
11004       !Subtarget.hasP9Vector())
11005     return SDValue();
11006 
11007   return Op;
11008 }
11009 
11010 // Custom lowering for fpext vf32 to v2f64
11011 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11012 
11013   assert(Op.getOpcode() == ISD::FP_EXTEND &&
11014          "Should only be called for ISD::FP_EXTEND");
11015 
11016   // FIXME: handle extends from half precision float vectors on P9.
11017   // We only want to custom lower an extend from v2f32 to v2f64.
11018   if (Op.getValueType() != MVT::v2f64 ||
11019       Op.getOperand(0).getValueType() != MVT::v2f32)
11020     return SDValue();
11021 
11022   SDLoc dl(Op);
11023   SDValue Op0 = Op.getOperand(0);
11024 
11025   switch (Op0.getOpcode()) {
11026   default:
11027     return SDValue();
11028   case ISD::EXTRACT_SUBVECTOR: {
11029     assert(Op0.getNumOperands() == 2 &&
11030            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11031            "Node should have 2 operands with second one being a constant!");
11032 
11033     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11034       return SDValue();
11035 
11036     // Custom lower is only done for high or low doubleword.
11037     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11038     if (Idx % 2 != 0)
11039       return SDValue();
11040 
11041     // Since input is v4f32, at this point Idx is either 0 or 2.
11042     // Shift to get the doubleword position we want.
11043     int DWord = Idx >> 1;
11044 
11045     // High and low word positions are different on little endian.
11046     if (Subtarget.isLittleEndian())
11047       DWord ^= 0x1;
11048 
11049     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11050                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11051   }
11052   case ISD::FADD:
11053   case ISD::FMUL:
11054   case ISD::FSUB: {
11055     SDValue NewLoad[2];
11056     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11057       // Ensure both input are loads.
11058       SDValue LdOp = Op0.getOperand(i);
11059       if (LdOp.getOpcode() != ISD::LOAD)
11060         return SDValue();
11061       // Generate new load node.
11062       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11063       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11064       NewLoad[i] = DAG.getMemIntrinsicNode(
11065           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11066           LD->getMemoryVT(), LD->getMemOperand());
11067     }
11068     SDValue NewOp =
11069         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11070                     NewLoad[1], Op0.getNode()->getFlags());
11071     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11072                        DAG.getConstant(0, dl, MVT::i32));
11073   }
11074   case ISD::LOAD: {
11075     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11076     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11077     SDValue NewLd = DAG.getMemIntrinsicNode(
11078         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11079         LD->getMemoryVT(), LD->getMemOperand());
11080     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11081                        DAG.getConstant(0, dl, MVT::i32));
11082   }
11083   }
11084   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11085 }
11086 
11087 /// LowerOperation - Provide custom lowering hooks for some operations.
11088 ///
11089 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11090   switch (Op.getOpcode()) {
11091   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11092   case ISD::FPOW:               return lowerPow(Op, DAG);
11093   case ISD::FSIN:               return lowerSin(Op, DAG);
11094   case ISD::FCOS:               return lowerCos(Op, DAG);
11095   case ISD::FLOG:               return lowerLog(Op, DAG);
11096   case ISD::FLOG10:             return lowerLog10(Op, DAG);
11097   case ISD::FEXP:               return lowerExp(Op, DAG);
11098   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11099   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11100   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11101   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11102   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11103   case ISD::STRICT_FSETCC:
11104   case ISD::STRICT_FSETCCS:
11105   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11106   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11107   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11108 
11109   case ISD::INLINEASM:
11110   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11111   // Variable argument lowering.
11112   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11113   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11114   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11115 
11116   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11117   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11118   case ISD::GET_DYNAMIC_AREA_OFFSET:
11119     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11120 
11121   // Exception handling lowering.
11122   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11123   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11124   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11125 
11126   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11127   case ISD::STORE:              return LowerSTORE(Op, DAG);
11128   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11129   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11130   case ISD::STRICT_FP_TO_UINT:
11131   case ISD::STRICT_FP_TO_SINT:
11132   case ISD::FP_TO_UINT:
11133   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11134   case ISD::STRICT_UINT_TO_FP:
11135   case ISD::STRICT_SINT_TO_FP:
11136   case ISD::UINT_TO_FP:
11137   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11138   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11139 
11140   // Lower 64-bit shifts.
11141   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11142   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11143   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11144 
11145   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11146   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11147 
11148   // Vector-related lowering.
11149   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11150   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11151   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11152   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11153   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11154   case ISD::MUL:                return LowerMUL(Op, DAG);
11155   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11156   case ISD::STRICT_FP_ROUND:
11157   case ISD::FP_ROUND:
11158     return LowerFP_ROUND(Op, DAG);
11159   case ISD::ROTL:               return LowerROTL(Op, DAG);
11160 
11161   // For counter-based loop handling.
11162   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11163 
11164   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11165 
11166   // Frame & Return address.
11167   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11168   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11169 
11170   case ISD::INTRINSIC_VOID:
11171     return LowerINTRINSIC_VOID(Op, DAG);
11172   case ISD::BSWAP:
11173     return LowerBSWAP(Op, DAG);
11174   case ISD::ATOMIC_CMP_SWAP:
11175     return LowerATOMIC_CMP_SWAP(Op, DAG);
11176   case ISD::ATOMIC_STORE:
11177     return LowerATOMIC_LOAD_STORE(Op, DAG);
11178   }
11179 }
11180 
11181 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11182                                            SmallVectorImpl<SDValue>&Results,
11183                                            SelectionDAG &DAG) const {
11184   SDLoc dl(N);
11185   switch (N->getOpcode()) {
11186   default:
11187     llvm_unreachable("Do not know how to custom type legalize this operation!");
11188   case ISD::ATOMIC_LOAD: {
11189     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11190     Results.push_back(Res);
11191     Results.push_back(Res.getValue(1));
11192     break;
11193   }
11194   case ISD::READCYCLECOUNTER: {
11195     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11196     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11197 
11198     Results.push_back(
11199         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11200     Results.push_back(RTB.getValue(2));
11201     break;
11202   }
11203   case ISD::INTRINSIC_W_CHAIN: {
11204     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11205         Intrinsic::loop_decrement)
11206       break;
11207 
11208     assert(N->getValueType(0) == MVT::i1 &&
11209            "Unexpected result type for CTR decrement intrinsic");
11210     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11211                                  N->getValueType(0));
11212     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11213     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11214                                  N->getOperand(1));
11215 
11216     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11217     Results.push_back(NewInt.getValue(1));
11218     break;
11219   }
11220   case ISD::INTRINSIC_WO_CHAIN: {
11221     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11222     case Intrinsic::ppc_pack_longdouble:
11223       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11224                                     N->getOperand(2), N->getOperand(1)));
11225       break;
11226     case Intrinsic::ppc_fnmsub:
11227     case Intrinsic::ppc_convert_f128_to_ppcf128:
11228       Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11229       break;
11230     }
11231     break;
11232   }
11233   case ISD::VAARG: {
11234     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11235       return;
11236 
11237     EVT VT = N->getValueType(0);
11238 
11239     if (VT == MVT::i64) {
11240       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11241 
11242       Results.push_back(NewNode);
11243       Results.push_back(NewNode.getValue(1));
11244     }
11245     return;
11246   }
11247   case ISD::STRICT_FP_TO_SINT:
11248   case ISD::STRICT_FP_TO_UINT:
11249   case ISD::FP_TO_SINT:
11250   case ISD::FP_TO_UINT: {
11251     // LowerFP_TO_INT() can only handle f32 and f64.
11252     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11253         MVT::ppcf128)
11254       return;
11255     SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11256     Results.push_back(LoweredValue);
11257     if (N->isStrictFPOpcode())
11258       Results.push_back(LoweredValue.getValue(1));
11259     return;
11260   }
11261   case ISD::TRUNCATE: {
11262     if (!N->getValueType(0).isVector())
11263       return;
11264     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11265     if (Lowered)
11266       Results.push_back(Lowered);
11267     return;
11268   }
11269   case ISD::FSHL:
11270   case ISD::FSHR:
11271     // Don't handle funnel shifts here.
11272     return;
11273   case ISD::BITCAST:
11274     // Don't handle bitcast here.
11275     return;
11276   case ISD::FP_EXTEND:
11277     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11278     if (Lowered)
11279       Results.push_back(Lowered);
11280     return;
11281   }
11282 }
11283 
11284 //===----------------------------------------------------------------------===//
11285 //  Other Lowering Code
11286 //===----------------------------------------------------------------------===//
11287 
11288 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11289   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11290   Function *Func = Intrinsic::getDeclaration(M, Id);
11291   return Builder.CreateCall(Func, {});
11292 }
11293 
11294 // The mappings for emitLeading/TrailingFence is taken from
11295 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11296 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11297                                                  Instruction *Inst,
11298                                                  AtomicOrdering Ord) const {
11299   if (Ord == AtomicOrdering::SequentiallyConsistent)
11300     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11301   if (isReleaseOrStronger(Ord))
11302     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11303   return nullptr;
11304 }
11305 
11306 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11307                                                   Instruction *Inst,
11308                                                   AtomicOrdering Ord) const {
11309   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11310     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11311     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11312     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11313     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11314       return Builder.CreateCall(
11315           Intrinsic::getDeclaration(
11316               Builder.GetInsertBlock()->getParent()->getParent(),
11317               Intrinsic::ppc_cfence, {Inst->getType()}),
11318           {Inst});
11319     // FIXME: Can use isync for rmw operation.
11320     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11321   }
11322   return nullptr;
11323 }
11324 
11325 MachineBasicBlock *
11326 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11327                                     unsigned AtomicSize,
11328                                     unsigned BinOpcode,
11329                                     unsigned CmpOpcode,
11330                                     unsigned CmpPred) const {
11331   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11332   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11333 
11334   auto LoadMnemonic = PPC::LDARX;
11335   auto StoreMnemonic = PPC::STDCX;
11336   switch (AtomicSize) {
11337   default:
11338     llvm_unreachable("Unexpected size of atomic entity");
11339   case 1:
11340     LoadMnemonic = PPC::LBARX;
11341     StoreMnemonic = PPC::STBCX;
11342     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11343     break;
11344   case 2:
11345     LoadMnemonic = PPC::LHARX;
11346     StoreMnemonic = PPC::STHCX;
11347     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11348     break;
11349   case 4:
11350     LoadMnemonic = PPC::LWARX;
11351     StoreMnemonic = PPC::STWCX;
11352     break;
11353   case 8:
11354     LoadMnemonic = PPC::LDARX;
11355     StoreMnemonic = PPC::STDCX;
11356     break;
11357   }
11358 
11359   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11360   MachineFunction *F = BB->getParent();
11361   MachineFunction::iterator It = ++BB->getIterator();
11362 
11363   Register dest = MI.getOperand(0).getReg();
11364   Register ptrA = MI.getOperand(1).getReg();
11365   Register ptrB = MI.getOperand(2).getReg();
11366   Register incr = MI.getOperand(3).getReg();
11367   DebugLoc dl = MI.getDebugLoc();
11368 
11369   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11370   MachineBasicBlock *loop2MBB =
11371     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11372   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11373   F->insert(It, loopMBB);
11374   if (CmpOpcode)
11375     F->insert(It, loop2MBB);
11376   F->insert(It, exitMBB);
11377   exitMBB->splice(exitMBB->begin(), BB,
11378                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11379   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11380 
11381   MachineRegisterInfo &RegInfo = F->getRegInfo();
11382   Register TmpReg = (!BinOpcode) ? incr :
11383     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11384                                            : &PPC::GPRCRegClass);
11385 
11386   //  thisMBB:
11387   //   ...
11388   //   fallthrough --> loopMBB
11389   BB->addSuccessor(loopMBB);
11390 
11391   //  loopMBB:
11392   //   l[wd]arx dest, ptr
11393   //   add r0, dest, incr
11394   //   st[wd]cx. r0, ptr
11395   //   bne- loopMBB
11396   //   fallthrough --> exitMBB
11397 
11398   // For max/min...
11399   //  loopMBB:
11400   //   l[wd]arx dest, ptr
11401   //   cmpl?[wd] incr, dest
11402   //   bgt exitMBB
11403   //  loop2MBB:
11404   //   st[wd]cx. dest, ptr
11405   //   bne- loopMBB
11406   //   fallthrough --> exitMBB
11407 
11408   BB = loopMBB;
11409   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11410     .addReg(ptrA).addReg(ptrB);
11411   if (BinOpcode)
11412     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11413   if (CmpOpcode) {
11414     // Signed comparisons of byte or halfword values must be sign-extended.
11415     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11416       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11417       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11418               ExtReg).addReg(dest);
11419       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11420         .addReg(incr).addReg(ExtReg);
11421     } else
11422       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11423         .addReg(incr).addReg(dest);
11424 
11425     BuildMI(BB, dl, TII->get(PPC::BCC))
11426       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11427     BB->addSuccessor(loop2MBB);
11428     BB->addSuccessor(exitMBB);
11429     BB = loop2MBB;
11430   }
11431   BuildMI(BB, dl, TII->get(StoreMnemonic))
11432     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11433   BuildMI(BB, dl, TII->get(PPC::BCC))
11434     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11435   BB->addSuccessor(loopMBB);
11436   BB->addSuccessor(exitMBB);
11437 
11438   //  exitMBB:
11439   //   ...
11440   BB = exitMBB;
11441   return BB;
11442 }
11443 
11444 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11445   switch(MI.getOpcode()) {
11446   default:
11447     return false;
11448   case PPC::COPY:
11449     return TII->isSignExtended(MI);
11450   case PPC::LHA:
11451   case PPC::LHA8:
11452   case PPC::LHAU:
11453   case PPC::LHAU8:
11454   case PPC::LHAUX:
11455   case PPC::LHAUX8:
11456   case PPC::LHAX:
11457   case PPC::LHAX8:
11458   case PPC::LWA:
11459   case PPC::LWAUX:
11460   case PPC::LWAX:
11461   case PPC::LWAX_32:
11462   case PPC::LWA_32:
11463   case PPC::PLHA:
11464   case PPC::PLHA8:
11465   case PPC::PLHA8pc:
11466   case PPC::PLHApc:
11467   case PPC::PLWA:
11468   case PPC::PLWA8:
11469   case PPC::PLWA8pc:
11470   case PPC::PLWApc:
11471   case PPC::EXTSB:
11472   case PPC::EXTSB8:
11473   case PPC::EXTSB8_32_64:
11474   case PPC::EXTSB8_rec:
11475   case PPC::EXTSB_rec:
11476   case PPC::EXTSH:
11477   case PPC::EXTSH8:
11478   case PPC::EXTSH8_32_64:
11479   case PPC::EXTSH8_rec:
11480   case PPC::EXTSH_rec:
11481   case PPC::EXTSW:
11482   case PPC::EXTSWSLI:
11483   case PPC::EXTSWSLI_32_64:
11484   case PPC::EXTSWSLI_32_64_rec:
11485   case PPC::EXTSWSLI_rec:
11486   case PPC::EXTSW_32:
11487   case PPC::EXTSW_32_64:
11488   case PPC::EXTSW_32_64_rec:
11489   case PPC::EXTSW_rec:
11490   case PPC::SRAW:
11491   case PPC::SRAWI:
11492   case PPC::SRAWI_rec:
11493   case PPC::SRAW_rec:
11494     return true;
11495   }
11496   return false;
11497 }
11498 
11499 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11500     MachineInstr &MI, MachineBasicBlock *BB,
11501     bool is8bit, // operation
11502     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11503   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11504   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11505 
11506   // If this is a signed comparison and the value being compared is not known
11507   // to be sign extended, sign extend it here.
11508   DebugLoc dl = MI.getDebugLoc();
11509   MachineFunction *F = BB->getParent();
11510   MachineRegisterInfo &RegInfo = F->getRegInfo();
11511   Register incr = MI.getOperand(3).getReg();
11512   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11513     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11514 
11515   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11516     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11517     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11518         .addReg(MI.getOperand(3).getReg());
11519     MI.getOperand(3).setReg(ValueReg);
11520   }
11521   // If we support part-word atomic mnemonics, just use them
11522   if (Subtarget.hasPartwordAtomics())
11523     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11524                             CmpPred);
11525 
11526   // In 64 bit mode we have to use 64 bits for addresses, even though the
11527   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11528   // registers without caring whether they're 32 or 64, but here we're
11529   // doing actual arithmetic on the addresses.
11530   bool is64bit = Subtarget.isPPC64();
11531   bool isLittleEndian = Subtarget.isLittleEndian();
11532   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11533 
11534   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11535   MachineFunction::iterator It = ++BB->getIterator();
11536 
11537   Register dest = MI.getOperand(0).getReg();
11538   Register ptrA = MI.getOperand(1).getReg();
11539   Register ptrB = MI.getOperand(2).getReg();
11540 
11541   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11542   MachineBasicBlock *loop2MBB =
11543       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11544   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11545   F->insert(It, loopMBB);
11546   if (CmpOpcode)
11547     F->insert(It, loop2MBB);
11548   F->insert(It, exitMBB);
11549   exitMBB->splice(exitMBB->begin(), BB,
11550                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11551   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11552 
11553   const TargetRegisterClass *RC =
11554       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11555   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11556 
11557   Register PtrReg = RegInfo.createVirtualRegister(RC);
11558   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11559   Register ShiftReg =
11560       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11561   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11562   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11563   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11564   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11565   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11566   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11567   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11568   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11569   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11570   Register Ptr1Reg;
11571   Register TmpReg =
11572       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11573 
11574   //  thisMBB:
11575   //   ...
11576   //   fallthrough --> loopMBB
11577   BB->addSuccessor(loopMBB);
11578 
11579   // The 4-byte load must be aligned, while a char or short may be
11580   // anywhere in the word.  Hence all this nasty bookkeeping code.
11581   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11582   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11583   //   xori shift, shift1, 24 [16]
11584   //   rlwinm ptr, ptr1, 0, 0, 29
11585   //   slw incr2, incr, shift
11586   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11587   //   slw mask, mask2, shift
11588   //  loopMBB:
11589   //   lwarx tmpDest, ptr
11590   //   add tmp, tmpDest, incr2
11591   //   andc tmp2, tmpDest, mask
11592   //   and tmp3, tmp, mask
11593   //   or tmp4, tmp3, tmp2
11594   //   stwcx. tmp4, ptr
11595   //   bne- loopMBB
11596   //   fallthrough --> exitMBB
11597   //   srw SrwDest, tmpDest, shift
11598   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11599   if (ptrA != ZeroReg) {
11600     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11601     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11602         .addReg(ptrA)
11603         .addReg(ptrB);
11604   } else {
11605     Ptr1Reg = ptrB;
11606   }
11607   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11608   // mode.
11609   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11610       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11611       .addImm(3)
11612       .addImm(27)
11613       .addImm(is8bit ? 28 : 27);
11614   if (!isLittleEndian)
11615     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11616         .addReg(Shift1Reg)
11617         .addImm(is8bit ? 24 : 16);
11618   if (is64bit)
11619     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11620         .addReg(Ptr1Reg)
11621         .addImm(0)
11622         .addImm(61);
11623   else
11624     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11625         .addReg(Ptr1Reg)
11626         .addImm(0)
11627         .addImm(0)
11628         .addImm(29);
11629   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11630   if (is8bit)
11631     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11632   else {
11633     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11634     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11635         .addReg(Mask3Reg)
11636         .addImm(65535);
11637   }
11638   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11639       .addReg(Mask2Reg)
11640       .addReg(ShiftReg);
11641 
11642   BB = loopMBB;
11643   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11644       .addReg(ZeroReg)
11645       .addReg(PtrReg);
11646   if (BinOpcode)
11647     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11648         .addReg(Incr2Reg)
11649         .addReg(TmpDestReg);
11650   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11651       .addReg(TmpDestReg)
11652       .addReg(MaskReg);
11653   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11654   if (CmpOpcode) {
11655     // For unsigned comparisons, we can directly compare the shifted values.
11656     // For signed comparisons we shift and sign extend.
11657     Register SReg = RegInfo.createVirtualRegister(GPRC);
11658     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11659         .addReg(TmpDestReg)
11660         .addReg(MaskReg);
11661     unsigned ValueReg = SReg;
11662     unsigned CmpReg = Incr2Reg;
11663     if (CmpOpcode == PPC::CMPW) {
11664       ValueReg = RegInfo.createVirtualRegister(GPRC);
11665       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11666           .addReg(SReg)
11667           .addReg(ShiftReg);
11668       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11669       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11670           .addReg(ValueReg);
11671       ValueReg = ValueSReg;
11672       CmpReg = incr;
11673     }
11674     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11675         .addReg(CmpReg)
11676         .addReg(ValueReg);
11677     BuildMI(BB, dl, TII->get(PPC::BCC))
11678         .addImm(CmpPred)
11679         .addReg(PPC::CR0)
11680         .addMBB(exitMBB);
11681     BB->addSuccessor(loop2MBB);
11682     BB->addSuccessor(exitMBB);
11683     BB = loop2MBB;
11684   }
11685   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11686   BuildMI(BB, dl, TII->get(PPC::STWCX))
11687       .addReg(Tmp4Reg)
11688       .addReg(ZeroReg)
11689       .addReg(PtrReg);
11690   BuildMI(BB, dl, TII->get(PPC::BCC))
11691       .addImm(PPC::PRED_NE)
11692       .addReg(PPC::CR0)
11693       .addMBB(loopMBB);
11694   BB->addSuccessor(loopMBB);
11695   BB->addSuccessor(exitMBB);
11696 
11697   //  exitMBB:
11698   //   ...
11699   BB = exitMBB;
11700   // Since the shift amount is not a constant, we need to clear
11701   // the upper bits with a separate RLWINM.
11702   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11703       .addReg(SrwDestReg)
11704       .addImm(0)
11705       .addImm(is8bit ? 24 : 16)
11706       .addImm(31);
11707   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11708       .addReg(TmpDestReg)
11709       .addReg(ShiftReg);
11710   return BB;
11711 }
11712 
11713 llvm::MachineBasicBlock *
11714 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11715                                     MachineBasicBlock *MBB) const {
11716   DebugLoc DL = MI.getDebugLoc();
11717   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11718   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11719 
11720   MachineFunction *MF = MBB->getParent();
11721   MachineRegisterInfo &MRI = MF->getRegInfo();
11722 
11723   const BasicBlock *BB = MBB->getBasicBlock();
11724   MachineFunction::iterator I = ++MBB->getIterator();
11725 
11726   Register DstReg = MI.getOperand(0).getReg();
11727   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11728   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11729   Register mainDstReg = MRI.createVirtualRegister(RC);
11730   Register restoreDstReg = MRI.createVirtualRegister(RC);
11731 
11732   MVT PVT = getPointerTy(MF->getDataLayout());
11733   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11734          "Invalid Pointer Size!");
11735   // For v = setjmp(buf), we generate
11736   //
11737   // thisMBB:
11738   //  SjLjSetup mainMBB
11739   //  bl mainMBB
11740   //  v_restore = 1
11741   //  b sinkMBB
11742   //
11743   // mainMBB:
11744   //  buf[LabelOffset] = LR
11745   //  v_main = 0
11746   //
11747   // sinkMBB:
11748   //  v = phi(main, restore)
11749   //
11750 
11751   MachineBasicBlock *thisMBB = MBB;
11752   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11753   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11754   MF->insert(I, mainMBB);
11755   MF->insert(I, sinkMBB);
11756 
11757   MachineInstrBuilder MIB;
11758 
11759   // Transfer the remainder of BB and its successor edges to sinkMBB.
11760   sinkMBB->splice(sinkMBB->begin(), MBB,
11761                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11762   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11763 
11764   // Note that the structure of the jmp_buf used here is not compatible
11765   // with that used by libc, and is not designed to be. Specifically, it
11766   // stores only those 'reserved' registers that LLVM does not otherwise
11767   // understand how to spill. Also, by convention, by the time this
11768   // intrinsic is called, Clang has already stored the frame address in the
11769   // first slot of the buffer and stack address in the third. Following the
11770   // X86 target code, we'll store the jump address in the second slot. We also
11771   // need to save the TOC pointer (R2) to handle jumps between shared
11772   // libraries, and that will be stored in the fourth slot. The thread
11773   // identifier (R13) is not affected.
11774 
11775   // thisMBB:
11776   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11777   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11778   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11779 
11780   // Prepare IP either in reg.
11781   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11782   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11783   Register BufReg = MI.getOperand(1).getReg();
11784 
11785   if (Subtarget.is64BitELFABI()) {
11786     setUsesTOCBasePtr(*MBB->getParent());
11787     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11788               .addReg(PPC::X2)
11789               .addImm(TOCOffset)
11790               .addReg(BufReg)
11791               .cloneMemRefs(MI);
11792   }
11793 
11794   // Naked functions never have a base pointer, and so we use r1. For all
11795   // other functions, this decision must be delayed until during PEI.
11796   unsigned BaseReg;
11797   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11798     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11799   else
11800     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11801 
11802   MIB = BuildMI(*thisMBB, MI, DL,
11803                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11804             .addReg(BaseReg)
11805             .addImm(BPOffset)
11806             .addReg(BufReg)
11807             .cloneMemRefs(MI);
11808 
11809   // Setup
11810   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11811   MIB.addRegMask(TRI->getNoPreservedMask());
11812 
11813   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11814 
11815   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11816           .addMBB(mainMBB);
11817   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11818 
11819   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11820   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11821 
11822   // mainMBB:
11823   //  mainDstReg = 0
11824   MIB =
11825       BuildMI(mainMBB, DL,
11826               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11827 
11828   // Store IP
11829   if (Subtarget.isPPC64()) {
11830     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11831             .addReg(LabelReg)
11832             .addImm(LabelOffset)
11833             .addReg(BufReg);
11834   } else {
11835     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11836             .addReg(LabelReg)
11837             .addImm(LabelOffset)
11838             .addReg(BufReg);
11839   }
11840   MIB.cloneMemRefs(MI);
11841 
11842   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11843   mainMBB->addSuccessor(sinkMBB);
11844 
11845   // sinkMBB:
11846   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11847           TII->get(PPC::PHI), DstReg)
11848     .addReg(mainDstReg).addMBB(mainMBB)
11849     .addReg(restoreDstReg).addMBB(thisMBB);
11850 
11851   MI.eraseFromParent();
11852   return sinkMBB;
11853 }
11854 
11855 MachineBasicBlock *
11856 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11857                                      MachineBasicBlock *MBB) const {
11858   DebugLoc DL = MI.getDebugLoc();
11859   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11860 
11861   MachineFunction *MF = MBB->getParent();
11862   MachineRegisterInfo &MRI = MF->getRegInfo();
11863 
11864   MVT PVT = getPointerTy(MF->getDataLayout());
11865   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11866          "Invalid Pointer Size!");
11867 
11868   const TargetRegisterClass *RC =
11869     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11870   Register Tmp = MRI.createVirtualRegister(RC);
11871   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11872   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11873   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11874   unsigned BP =
11875       (PVT == MVT::i64)
11876           ? PPC::X30
11877           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11878                                                               : PPC::R30);
11879 
11880   MachineInstrBuilder MIB;
11881 
11882   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11883   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11884   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11885   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11886 
11887   Register BufReg = MI.getOperand(0).getReg();
11888 
11889   // Reload FP (the jumped-to function may not have had a
11890   // frame pointer, and if so, then its r31 will be restored
11891   // as necessary).
11892   if (PVT == MVT::i64) {
11893     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11894             .addImm(0)
11895             .addReg(BufReg);
11896   } else {
11897     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11898             .addImm(0)
11899             .addReg(BufReg);
11900   }
11901   MIB.cloneMemRefs(MI);
11902 
11903   // Reload IP
11904   if (PVT == MVT::i64) {
11905     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11906             .addImm(LabelOffset)
11907             .addReg(BufReg);
11908   } else {
11909     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11910             .addImm(LabelOffset)
11911             .addReg(BufReg);
11912   }
11913   MIB.cloneMemRefs(MI);
11914 
11915   // Reload SP
11916   if (PVT == MVT::i64) {
11917     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11918             .addImm(SPOffset)
11919             .addReg(BufReg);
11920   } else {
11921     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11922             .addImm(SPOffset)
11923             .addReg(BufReg);
11924   }
11925   MIB.cloneMemRefs(MI);
11926 
11927   // Reload BP
11928   if (PVT == MVT::i64) {
11929     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11930             .addImm(BPOffset)
11931             .addReg(BufReg);
11932   } else {
11933     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11934             .addImm(BPOffset)
11935             .addReg(BufReg);
11936   }
11937   MIB.cloneMemRefs(MI);
11938 
11939   // Reload TOC
11940   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11941     setUsesTOCBasePtr(*MBB->getParent());
11942     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11943               .addImm(TOCOffset)
11944               .addReg(BufReg)
11945               .cloneMemRefs(MI);
11946   }
11947 
11948   // Jump
11949   BuildMI(*MBB, MI, DL,
11950           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11951   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11952 
11953   MI.eraseFromParent();
11954   return MBB;
11955 }
11956 
11957 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11958   // If the function specifically requests inline stack probes, emit them.
11959   if (MF.getFunction().hasFnAttribute("probe-stack"))
11960     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11961            "inline-asm";
11962   return false;
11963 }
11964 
11965 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11966   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11967   unsigned StackAlign = TFI->getStackAlignment();
11968   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11969          "Unexpected stack alignment");
11970   // The default stack probe size is 4096 if the function has no
11971   // stack-probe-size attribute.
11972   unsigned StackProbeSize = 4096;
11973   const Function &Fn = MF.getFunction();
11974   if (Fn.hasFnAttribute("stack-probe-size"))
11975     Fn.getFnAttribute("stack-probe-size")
11976         .getValueAsString()
11977         .getAsInteger(0, StackProbeSize);
11978   // Round down to the stack alignment.
11979   StackProbeSize &= ~(StackAlign - 1);
11980   return StackProbeSize ? StackProbeSize : StackAlign;
11981 }
11982 
11983 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11984 // into three phases. In the first phase, it uses pseudo instruction
11985 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11986 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11987 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11988 // MaxCallFrameSize so that it can calculate correct data area pointer.
11989 MachineBasicBlock *
11990 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11991                                     MachineBasicBlock *MBB) const {
11992   const bool isPPC64 = Subtarget.isPPC64();
11993   MachineFunction *MF = MBB->getParent();
11994   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11995   DebugLoc DL = MI.getDebugLoc();
11996   const unsigned ProbeSize = getStackProbeSize(*MF);
11997   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11998   MachineRegisterInfo &MRI = MF->getRegInfo();
11999   // The CFG of probing stack looks as
12000   //         +-----+
12001   //         | MBB |
12002   //         +--+--+
12003   //            |
12004   //       +----v----+
12005   //  +--->+ TestMBB +---+
12006   //  |    +----+----+   |
12007   //  |         |        |
12008   //  |   +-----v----+   |
12009   //  +---+ BlockMBB |   |
12010   //      +----------+   |
12011   //                     |
12012   //       +---------+   |
12013   //       | TailMBB +<--+
12014   //       +---------+
12015   // In MBB, calculate previous frame pointer and final stack pointer.
12016   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
12017   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
12018   // TailMBB is spliced via \p MI.
12019   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
12020   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
12021   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
12022 
12023   MachineFunction::iterator MBBIter = ++MBB->getIterator();
12024   MF->insert(MBBIter, TestMBB);
12025   MF->insert(MBBIter, BlockMBB);
12026   MF->insert(MBBIter, TailMBB);
12027 
12028   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
12029   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12030 
12031   Register DstReg = MI.getOperand(0).getReg();
12032   Register NegSizeReg = MI.getOperand(1).getReg();
12033   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12034   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12035   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12036   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12037 
12038   // Since value of NegSizeReg might be realigned in prologepilog, insert a
12039   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
12040   // NegSize.
12041   unsigned ProbeOpc;
12042   if (!MRI.hasOneNonDBGUse(NegSizeReg))
12043     ProbeOpc =
12044         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
12045   else
12046     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
12047     // and NegSizeReg will be allocated in the same phyreg to avoid
12048     // redundant copy when NegSizeReg has only one use which is current MI and
12049     // will be replaced by PREPARE_PROBED_ALLOCA then.
12050     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
12051                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
12052   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
12053       .addDef(ActualNegSizeReg)
12054       .addReg(NegSizeReg)
12055       .add(MI.getOperand(2))
12056       .add(MI.getOperand(3));
12057 
12058   // Calculate final stack pointer, which equals to SP + ActualNegSize.
12059   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12060           FinalStackPtr)
12061       .addReg(SPReg)
12062       .addReg(ActualNegSizeReg);
12063 
12064   // Materialize a scratch register for update.
12065   int64_t NegProbeSize = -(int64_t)ProbeSize;
12066   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
12067   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12068   if (!isInt<16>(NegProbeSize)) {
12069     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12070     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12071         .addImm(NegProbeSize >> 16);
12072     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12073             ScratchReg)
12074         .addReg(TempReg)
12075         .addImm(NegProbeSize & 0xFFFF);
12076   } else
12077     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12078         .addImm(NegProbeSize);
12079 
12080   {
12081     // Probing leading residual part.
12082     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12083     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12084         .addReg(ActualNegSizeReg)
12085         .addReg(ScratchReg);
12086     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12087     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12088         .addReg(Div)
12089         .addReg(ScratchReg);
12090     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12091     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12092         .addReg(Mul)
12093         .addReg(ActualNegSizeReg);
12094     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12095         .addReg(FramePointer)
12096         .addReg(SPReg)
12097         .addReg(NegMod);
12098   }
12099 
12100   {
12101     // Remaining part should be multiple of ProbeSize.
12102     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12103     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12104         .addReg(SPReg)
12105         .addReg(FinalStackPtr);
12106     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12107         .addImm(PPC::PRED_EQ)
12108         .addReg(CmpResult)
12109         .addMBB(TailMBB);
12110     TestMBB->addSuccessor(BlockMBB);
12111     TestMBB->addSuccessor(TailMBB);
12112   }
12113 
12114   {
12115     // Touch the block.
12116     // |P...|P...|P...
12117     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12118         .addReg(FramePointer)
12119         .addReg(SPReg)
12120         .addReg(ScratchReg);
12121     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12122     BlockMBB->addSuccessor(TestMBB);
12123   }
12124 
12125   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12126   // DYNAREAOFFSET pseudo instruction to get the future result.
12127   Register MaxCallFrameSizeReg =
12128       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12129   BuildMI(TailMBB, DL,
12130           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12131           MaxCallFrameSizeReg)
12132       .add(MI.getOperand(2))
12133       .add(MI.getOperand(3));
12134   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12135       .addReg(SPReg)
12136       .addReg(MaxCallFrameSizeReg);
12137 
12138   // Splice instructions after MI to TailMBB.
12139   TailMBB->splice(TailMBB->end(), MBB,
12140                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12141   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12142   MBB->addSuccessor(TestMBB);
12143 
12144   // Delete the pseudo instruction.
12145   MI.eraseFromParent();
12146 
12147   ++NumDynamicAllocaProbed;
12148   return TailMBB;
12149 }
12150 
12151 MachineBasicBlock *
12152 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12153                                                MachineBasicBlock *BB) const {
12154   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12155       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12156     if (Subtarget.is64BitELFABI() &&
12157         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12158         !Subtarget.isUsingPCRelativeCalls()) {
12159       // Call lowering should have added an r2 operand to indicate a dependence
12160       // on the TOC base pointer value. It can't however, because there is no
12161       // way to mark the dependence as implicit there, and so the stackmap code
12162       // will confuse it with a regular operand. Instead, add the dependence
12163       // here.
12164       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12165     }
12166 
12167     return emitPatchPoint(MI, BB);
12168   }
12169 
12170   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12171       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12172     return emitEHSjLjSetJmp(MI, BB);
12173   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12174              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12175     return emitEHSjLjLongJmp(MI, BB);
12176   }
12177 
12178   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12179 
12180   // To "insert" these instructions we actually have to insert their
12181   // control-flow patterns.
12182   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12183   MachineFunction::iterator It = ++BB->getIterator();
12184 
12185   MachineFunction *F = BB->getParent();
12186   MachineRegisterInfo &MRI = F->getRegInfo();
12187 
12188   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12189       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12190       MI.getOpcode() == PPC::SELECT_I8) {
12191     SmallVector<MachineOperand, 2> Cond;
12192     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12193         MI.getOpcode() == PPC::SELECT_CC_I8)
12194       Cond.push_back(MI.getOperand(4));
12195     else
12196       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12197     Cond.push_back(MI.getOperand(1));
12198 
12199     DebugLoc dl = MI.getDebugLoc();
12200     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12201                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12202   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12203              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12204              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12205              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12206              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12207              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12208              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12209              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12210              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12211              MI.getOpcode() == PPC::SELECT_F4 ||
12212              MI.getOpcode() == PPC::SELECT_F8 ||
12213              MI.getOpcode() == PPC::SELECT_F16 ||
12214              MI.getOpcode() == PPC::SELECT_SPE ||
12215              MI.getOpcode() == PPC::SELECT_SPE4 ||
12216              MI.getOpcode() == PPC::SELECT_VRRC ||
12217              MI.getOpcode() == PPC::SELECT_VSFRC ||
12218              MI.getOpcode() == PPC::SELECT_VSSRC ||
12219              MI.getOpcode() == PPC::SELECT_VSRC) {
12220     // The incoming instruction knows the destination vreg to set, the
12221     // condition code register to branch on, the true/false values to
12222     // select between, and a branch opcode to use.
12223 
12224     //  thisMBB:
12225     //  ...
12226     //   TrueVal = ...
12227     //   cmpTY ccX, r1, r2
12228     //   bCC copy1MBB
12229     //   fallthrough --> copy0MBB
12230     MachineBasicBlock *thisMBB = BB;
12231     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12232     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12233     DebugLoc dl = MI.getDebugLoc();
12234     F->insert(It, copy0MBB);
12235     F->insert(It, sinkMBB);
12236 
12237     // Transfer the remainder of BB and its successor edges to sinkMBB.
12238     sinkMBB->splice(sinkMBB->begin(), BB,
12239                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12240     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12241 
12242     // Next, add the true and fallthrough blocks as its successors.
12243     BB->addSuccessor(copy0MBB);
12244     BB->addSuccessor(sinkMBB);
12245 
12246     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12247         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12248         MI.getOpcode() == PPC::SELECT_F16 ||
12249         MI.getOpcode() == PPC::SELECT_SPE4 ||
12250         MI.getOpcode() == PPC::SELECT_SPE ||
12251         MI.getOpcode() == PPC::SELECT_VRRC ||
12252         MI.getOpcode() == PPC::SELECT_VSFRC ||
12253         MI.getOpcode() == PPC::SELECT_VSSRC ||
12254         MI.getOpcode() == PPC::SELECT_VSRC) {
12255       BuildMI(BB, dl, TII->get(PPC::BC))
12256           .addReg(MI.getOperand(1).getReg())
12257           .addMBB(sinkMBB);
12258     } else {
12259       unsigned SelectPred = MI.getOperand(4).getImm();
12260       BuildMI(BB, dl, TII->get(PPC::BCC))
12261           .addImm(SelectPred)
12262           .addReg(MI.getOperand(1).getReg())
12263           .addMBB(sinkMBB);
12264     }
12265 
12266     //  copy0MBB:
12267     //   %FalseValue = ...
12268     //   # fallthrough to sinkMBB
12269     BB = copy0MBB;
12270 
12271     // Update machine-CFG edges
12272     BB->addSuccessor(sinkMBB);
12273 
12274     //  sinkMBB:
12275     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12276     //  ...
12277     BB = sinkMBB;
12278     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12279         .addReg(MI.getOperand(3).getReg())
12280         .addMBB(copy0MBB)
12281         .addReg(MI.getOperand(2).getReg())
12282         .addMBB(thisMBB);
12283   } else if (MI.getOpcode() == PPC::ReadTB) {
12284     // To read the 64-bit time-base register on a 32-bit target, we read the
12285     // two halves. Should the counter have wrapped while it was being read, we
12286     // need to try again.
12287     // ...
12288     // readLoop:
12289     // mfspr Rx,TBU # load from TBU
12290     // mfspr Ry,TB  # load from TB
12291     // mfspr Rz,TBU # load from TBU
12292     // cmpw crX,Rx,Rz # check if 'old'='new'
12293     // bne readLoop   # branch if they're not equal
12294     // ...
12295 
12296     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12297     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12298     DebugLoc dl = MI.getDebugLoc();
12299     F->insert(It, readMBB);
12300     F->insert(It, sinkMBB);
12301 
12302     // Transfer the remainder of BB and its successor edges to sinkMBB.
12303     sinkMBB->splice(sinkMBB->begin(), BB,
12304                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12305     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12306 
12307     BB->addSuccessor(readMBB);
12308     BB = readMBB;
12309 
12310     MachineRegisterInfo &RegInfo = F->getRegInfo();
12311     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12312     Register LoReg = MI.getOperand(0).getReg();
12313     Register HiReg = MI.getOperand(1).getReg();
12314 
12315     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12316     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12317     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12318 
12319     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12320 
12321     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12322         .addReg(HiReg)
12323         .addReg(ReadAgainReg);
12324     BuildMI(BB, dl, TII->get(PPC::BCC))
12325         .addImm(PPC::PRED_NE)
12326         .addReg(CmpReg)
12327         .addMBB(readMBB);
12328 
12329     BB->addSuccessor(readMBB);
12330     BB->addSuccessor(sinkMBB);
12331   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12332     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12333   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12334     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12335   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12336     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12337   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12338     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12339 
12340   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12341     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12342   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12343     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12344   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12345     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12346   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12347     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12348 
12349   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12350     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12351   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12352     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12353   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12354     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12355   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12356     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12357 
12358   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12359     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12360   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12361     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12362   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12363     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12364   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12365     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12366 
12367   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12368     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12369   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12370     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12371   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12372     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12373   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12374     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12375 
12376   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12377     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12378   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12379     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12380   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12381     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12382   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12383     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12384 
12385   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12386     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12387   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12388     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12389   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12390     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12391   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12392     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12393 
12394   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12395     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12396   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12397     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12398   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12399     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12400   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12401     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12402 
12403   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12404     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12405   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12406     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12407   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12408     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12409   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12410     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12411 
12412   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12413     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12414   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12415     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12416   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12417     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12418   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12419     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12420 
12421   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12422     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12423   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12424     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12425   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12426     BB = EmitAtomicBinary(MI, BB, 4, 0);
12427   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12428     BB = EmitAtomicBinary(MI, BB, 8, 0);
12429   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12430            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12431            (Subtarget.hasPartwordAtomics() &&
12432             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12433            (Subtarget.hasPartwordAtomics() &&
12434             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12435     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12436 
12437     auto LoadMnemonic = PPC::LDARX;
12438     auto StoreMnemonic = PPC::STDCX;
12439     switch (MI.getOpcode()) {
12440     default:
12441       llvm_unreachable("Compare and swap of unknown size");
12442     case PPC::ATOMIC_CMP_SWAP_I8:
12443       LoadMnemonic = PPC::LBARX;
12444       StoreMnemonic = PPC::STBCX;
12445       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12446       break;
12447     case PPC::ATOMIC_CMP_SWAP_I16:
12448       LoadMnemonic = PPC::LHARX;
12449       StoreMnemonic = PPC::STHCX;
12450       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12451       break;
12452     case PPC::ATOMIC_CMP_SWAP_I32:
12453       LoadMnemonic = PPC::LWARX;
12454       StoreMnemonic = PPC::STWCX;
12455       break;
12456     case PPC::ATOMIC_CMP_SWAP_I64:
12457       LoadMnemonic = PPC::LDARX;
12458       StoreMnemonic = PPC::STDCX;
12459       break;
12460     }
12461     Register dest = MI.getOperand(0).getReg();
12462     Register ptrA = MI.getOperand(1).getReg();
12463     Register ptrB = MI.getOperand(2).getReg();
12464     Register oldval = MI.getOperand(3).getReg();
12465     Register newval = MI.getOperand(4).getReg();
12466     DebugLoc dl = MI.getDebugLoc();
12467 
12468     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12469     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12470     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12471     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12472     F->insert(It, loop1MBB);
12473     F->insert(It, loop2MBB);
12474     F->insert(It, midMBB);
12475     F->insert(It, exitMBB);
12476     exitMBB->splice(exitMBB->begin(), BB,
12477                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12478     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12479 
12480     //  thisMBB:
12481     //   ...
12482     //   fallthrough --> loopMBB
12483     BB->addSuccessor(loop1MBB);
12484 
12485     // loop1MBB:
12486     //   l[bhwd]arx dest, ptr
12487     //   cmp[wd] dest, oldval
12488     //   bne- midMBB
12489     // loop2MBB:
12490     //   st[bhwd]cx. newval, ptr
12491     //   bne- loopMBB
12492     //   b exitBB
12493     // midMBB:
12494     //   st[bhwd]cx. dest, ptr
12495     // exitBB:
12496     BB = loop1MBB;
12497     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12498     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12499         .addReg(oldval)
12500         .addReg(dest);
12501     BuildMI(BB, dl, TII->get(PPC::BCC))
12502         .addImm(PPC::PRED_NE)
12503         .addReg(PPC::CR0)
12504         .addMBB(midMBB);
12505     BB->addSuccessor(loop2MBB);
12506     BB->addSuccessor(midMBB);
12507 
12508     BB = loop2MBB;
12509     BuildMI(BB, dl, TII->get(StoreMnemonic))
12510         .addReg(newval)
12511         .addReg(ptrA)
12512         .addReg(ptrB);
12513     BuildMI(BB, dl, TII->get(PPC::BCC))
12514         .addImm(PPC::PRED_NE)
12515         .addReg(PPC::CR0)
12516         .addMBB(loop1MBB);
12517     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12518     BB->addSuccessor(loop1MBB);
12519     BB->addSuccessor(exitMBB);
12520 
12521     BB = midMBB;
12522     BuildMI(BB, dl, TII->get(StoreMnemonic))
12523         .addReg(dest)
12524         .addReg(ptrA)
12525         .addReg(ptrB);
12526     BB->addSuccessor(exitMBB);
12527 
12528     //  exitMBB:
12529     //   ...
12530     BB = exitMBB;
12531   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12532              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12533     // We must use 64-bit registers for addresses when targeting 64-bit,
12534     // since we're actually doing arithmetic on them.  Other registers
12535     // can be 32-bit.
12536     bool is64bit = Subtarget.isPPC64();
12537     bool isLittleEndian = Subtarget.isLittleEndian();
12538     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12539 
12540     Register dest = MI.getOperand(0).getReg();
12541     Register ptrA = MI.getOperand(1).getReg();
12542     Register ptrB = MI.getOperand(2).getReg();
12543     Register oldval = MI.getOperand(3).getReg();
12544     Register newval = MI.getOperand(4).getReg();
12545     DebugLoc dl = MI.getDebugLoc();
12546 
12547     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12548     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12549     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12550     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12551     F->insert(It, loop1MBB);
12552     F->insert(It, loop2MBB);
12553     F->insert(It, midMBB);
12554     F->insert(It, exitMBB);
12555     exitMBB->splice(exitMBB->begin(), BB,
12556                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12557     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12558 
12559     MachineRegisterInfo &RegInfo = F->getRegInfo();
12560     const TargetRegisterClass *RC =
12561         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12562     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12563 
12564     Register PtrReg = RegInfo.createVirtualRegister(RC);
12565     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12566     Register ShiftReg =
12567         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12568     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12569     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12570     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12571     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12572     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12573     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12574     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12575     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12576     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12577     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12578     Register Ptr1Reg;
12579     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12580     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12581     //  thisMBB:
12582     //   ...
12583     //   fallthrough --> loopMBB
12584     BB->addSuccessor(loop1MBB);
12585 
12586     // The 4-byte load must be aligned, while a char or short may be
12587     // anywhere in the word.  Hence all this nasty bookkeeping code.
12588     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12589     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12590     //   xori shift, shift1, 24 [16]
12591     //   rlwinm ptr, ptr1, 0, 0, 29
12592     //   slw newval2, newval, shift
12593     //   slw oldval2, oldval,shift
12594     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12595     //   slw mask, mask2, shift
12596     //   and newval3, newval2, mask
12597     //   and oldval3, oldval2, mask
12598     // loop1MBB:
12599     //   lwarx tmpDest, ptr
12600     //   and tmp, tmpDest, mask
12601     //   cmpw tmp, oldval3
12602     //   bne- midMBB
12603     // loop2MBB:
12604     //   andc tmp2, tmpDest, mask
12605     //   or tmp4, tmp2, newval3
12606     //   stwcx. tmp4, ptr
12607     //   bne- loop1MBB
12608     //   b exitBB
12609     // midMBB:
12610     //   stwcx. tmpDest, ptr
12611     // exitBB:
12612     //   srw dest, tmpDest, shift
12613     if (ptrA != ZeroReg) {
12614       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12615       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12616           .addReg(ptrA)
12617           .addReg(ptrB);
12618     } else {
12619       Ptr1Reg = ptrB;
12620     }
12621 
12622     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12623     // mode.
12624     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12625         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12626         .addImm(3)
12627         .addImm(27)
12628         .addImm(is8bit ? 28 : 27);
12629     if (!isLittleEndian)
12630       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12631           .addReg(Shift1Reg)
12632           .addImm(is8bit ? 24 : 16);
12633     if (is64bit)
12634       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12635           .addReg(Ptr1Reg)
12636           .addImm(0)
12637           .addImm(61);
12638     else
12639       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12640           .addReg(Ptr1Reg)
12641           .addImm(0)
12642           .addImm(0)
12643           .addImm(29);
12644     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12645         .addReg(newval)
12646         .addReg(ShiftReg);
12647     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12648         .addReg(oldval)
12649         .addReg(ShiftReg);
12650     if (is8bit)
12651       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12652     else {
12653       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12654       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12655           .addReg(Mask3Reg)
12656           .addImm(65535);
12657     }
12658     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12659         .addReg(Mask2Reg)
12660         .addReg(ShiftReg);
12661     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12662         .addReg(NewVal2Reg)
12663         .addReg(MaskReg);
12664     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12665         .addReg(OldVal2Reg)
12666         .addReg(MaskReg);
12667 
12668     BB = loop1MBB;
12669     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12670         .addReg(ZeroReg)
12671         .addReg(PtrReg);
12672     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12673         .addReg(TmpDestReg)
12674         .addReg(MaskReg);
12675     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12676         .addReg(TmpReg)
12677         .addReg(OldVal3Reg);
12678     BuildMI(BB, dl, TII->get(PPC::BCC))
12679         .addImm(PPC::PRED_NE)
12680         .addReg(PPC::CR0)
12681         .addMBB(midMBB);
12682     BB->addSuccessor(loop2MBB);
12683     BB->addSuccessor(midMBB);
12684 
12685     BB = loop2MBB;
12686     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12687         .addReg(TmpDestReg)
12688         .addReg(MaskReg);
12689     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12690         .addReg(Tmp2Reg)
12691         .addReg(NewVal3Reg);
12692     BuildMI(BB, dl, TII->get(PPC::STWCX))
12693         .addReg(Tmp4Reg)
12694         .addReg(ZeroReg)
12695         .addReg(PtrReg);
12696     BuildMI(BB, dl, TII->get(PPC::BCC))
12697         .addImm(PPC::PRED_NE)
12698         .addReg(PPC::CR0)
12699         .addMBB(loop1MBB);
12700     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12701     BB->addSuccessor(loop1MBB);
12702     BB->addSuccessor(exitMBB);
12703 
12704     BB = midMBB;
12705     BuildMI(BB, dl, TII->get(PPC::STWCX))
12706         .addReg(TmpDestReg)
12707         .addReg(ZeroReg)
12708         .addReg(PtrReg);
12709     BB->addSuccessor(exitMBB);
12710 
12711     //  exitMBB:
12712     //   ...
12713     BB = exitMBB;
12714     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12715         .addReg(TmpReg)
12716         .addReg(ShiftReg);
12717   } else if (MI.getOpcode() == PPC::FADDrtz) {
12718     // This pseudo performs an FADD with rounding mode temporarily forced
12719     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12720     // is not modeled at the SelectionDAG level.
12721     Register Dest = MI.getOperand(0).getReg();
12722     Register Src1 = MI.getOperand(1).getReg();
12723     Register Src2 = MI.getOperand(2).getReg();
12724     DebugLoc dl = MI.getDebugLoc();
12725 
12726     MachineRegisterInfo &RegInfo = F->getRegInfo();
12727     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12728 
12729     // Save FPSCR value.
12730     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12731 
12732     // Set rounding mode to round-to-zero.
12733     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12734         .addImm(31)
12735         .addReg(PPC::RM, RegState::ImplicitDefine);
12736 
12737     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12738         .addImm(30)
12739         .addReg(PPC::RM, RegState::ImplicitDefine);
12740 
12741     // Perform addition.
12742     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12743                    .addReg(Src1)
12744                    .addReg(Src2);
12745     if (MI.getFlag(MachineInstr::NoFPExcept))
12746       MIB.setMIFlag(MachineInstr::NoFPExcept);
12747 
12748     // Restore FPSCR value.
12749     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12750   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12751              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12752              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12753              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12754     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12755                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12756                           ? PPC::ANDI8_rec
12757                           : PPC::ANDI_rec;
12758     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12759                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12760 
12761     MachineRegisterInfo &RegInfo = F->getRegInfo();
12762     Register Dest = RegInfo.createVirtualRegister(
12763         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12764 
12765     DebugLoc Dl = MI.getDebugLoc();
12766     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12767         .addReg(MI.getOperand(1).getReg())
12768         .addImm(1);
12769     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12770             MI.getOperand(0).getReg())
12771         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12772   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12773     DebugLoc Dl = MI.getDebugLoc();
12774     MachineRegisterInfo &RegInfo = F->getRegInfo();
12775     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12776     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12777     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12778             MI.getOperand(0).getReg())
12779         .addReg(CRReg);
12780   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12781     DebugLoc Dl = MI.getDebugLoc();
12782     unsigned Imm = MI.getOperand(1).getImm();
12783     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12784     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12785             MI.getOperand(0).getReg())
12786         .addReg(PPC::CR0EQ);
12787   } else if (MI.getOpcode() == PPC::SETRNDi) {
12788     DebugLoc dl = MI.getDebugLoc();
12789     Register OldFPSCRReg = MI.getOperand(0).getReg();
12790 
12791     // Save FPSCR value.
12792     if (MRI.use_empty(OldFPSCRReg))
12793       BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12794     else
12795       BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12796 
12797     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12798     // the following settings:
12799     //   00 Round to nearest
12800     //   01 Round to 0
12801     //   10 Round to +inf
12802     //   11 Round to -inf
12803 
12804     // When the operand is immediate, using the two least significant bits of
12805     // the immediate to set the bits 62:63 of FPSCR.
12806     unsigned Mode = MI.getOperand(1).getImm();
12807     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12808         .addImm(31)
12809         .addReg(PPC::RM, RegState::ImplicitDefine);
12810 
12811     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12812         .addImm(30)
12813         .addReg(PPC::RM, RegState::ImplicitDefine);
12814   } else if (MI.getOpcode() == PPC::SETRND) {
12815     DebugLoc dl = MI.getDebugLoc();
12816 
12817     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12818     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12819     // If the target doesn't have DirectMove, we should use stack to do the
12820     // conversion, because the target doesn't have the instructions like mtvsrd
12821     // or mfvsrd to do this conversion directly.
12822     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12823       if (Subtarget.hasDirectMove()) {
12824         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12825           .addReg(SrcReg);
12826       } else {
12827         // Use stack to do the register copy.
12828         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12829         MachineRegisterInfo &RegInfo = F->getRegInfo();
12830         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12831         if (RC == &PPC::F8RCRegClass) {
12832           // Copy register from F8RCRegClass to G8RCRegclass.
12833           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12834                  "Unsupported RegClass.");
12835 
12836           StoreOp = PPC::STFD;
12837           LoadOp = PPC::LD;
12838         } else {
12839           // Copy register from G8RCRegClass to F8RCRegclass.
12840           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12841                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12842                  "Unsupported RegClass.");
12843         }
12844 
12845         MachineFrameInfo &MFI = F->getFrameInfo();
12846         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12847 
12848         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12849             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12850             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12851             MFI.getObjectAlign(FrameIdx));
12852 
12853         // Store the SrcReg into the stack.
12854         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12855           .addReg(SrcReg)
12856           .addImm(0)
12857           .addFrameIndex(FrameIdx)
12858           .addMemOperand(MMOStore);
12859 
12860         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12861             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12862             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12863             MFI.getObjectAlign(FrameIdx));
12864 
12865         // Load from the stack where SrcReg is stored, and save to DestReg,
12866         // so we have done the RegClass conversion from RegClass::SrcReg to
12867         // RegClass::DestReg.
12868         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12869           .addImm(0)
12870           .addFrameIndex(FrameIdx)
12871           .addMemOperand(MMOLoad);
12872       }
12873     };
12874 
12875     Register OldFPSCRReg = MI.getOperand(0).getReg();
12876 
12877     // Save FPSCR value.
12878     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12879 
12880     // When the operand is gprc register, use two least significant bits of the
12881     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12882     //
12883     // copy OldFPSCRTmpReg, OldFPSCRReg
12884     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12885     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12886     // copy NewFPSCRReg, NewFPSCRTmpReg
12887     // mtfsf 255, NewFPSCRReg
12888     MachineOperand SrcOp = MI.getOperand(1);
12889     MachineRegisterInfo &RegInfo = F->getRegInfo();
12890     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12891 
12892     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12893 
12894     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12895     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12896 
12897     // The first operand of INSERT_SUBREG should be a register which has
12898     // subregisters, we only care about its RegClass, so we should use an
12899     // IMPLICIT_DEF register.
12900     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12901     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12902       .addReg(ImDefReg)
12903       .add(SrcOp)
12904       .addImm(1);
12905 
12906     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12907     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12908       .addReg(OldFPSCRTmpReg)
12909       .addReg(ExtSrcReg)
12910       .addImm(0)
12911       .addImm(62);
12912 
12913     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12914     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12915 
12916     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12917     // bits of FPSCR.
12918     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12919       .addImm(255)
12920       .addReg(NewFPSCRReg)
12921       .addImm(0)
12922       .addImm(0);
12923   } else if (MI.getOpcode() == PPC::SETFLM) {
12924     DebugLoc Dl = MI.getDebugLoc();
12925 
12926     // Result of setflm is previous FPSCR content, so we need to save it first.
12927     Register OldFPSCRReg = MI.getOperand(0).getReg();
12928     if (MRI.use_empty(OldFPSCRReg))
12929       BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12930     else
12931       BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12932 
12933     // Put bits in 32:63 to FPSCR.
12934     Register NewFPSCRReg = MI.getOperand(1).getReg();
12935     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12936         .addImm(255)
12937         .addReg(NewFPSCRReg)
12938         .addImm(0)
12939         .addImm(0);
12940   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12941              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12942     return emitProbedAlloca(MI, BB);
12943   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12944     DebugLoc DL = MI.getDebugLoc();
12945     Register Src = MI.getOperand(2).getReg();
12946     Register Lo = MI.getOperand(0).getReg();
12947     Register Hi = MI.getOperand(1).getReg();
12948     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12949         .addDef(Lo)
12950         .addUse(Src, 0, PPC::sub_gp8_x1);
12951     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12952         .addDef(Hi)
12953         .addUse(Src, 0, PPC::sub_gp8_x0);
12954   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12955              MI.getOpcode() == PPC::STQX_PSEUDO) {
12956     DebugLoc DL = MI.getDebugLoc();
12957     // Ptr is used as the ptr_rc_no_r0 part
12958     // of LQ/STQ's memory operand and adding result of RA and RB,
12959     // so it has to be g8rc_and_g8rc_nox0.
12960     Register Ptr =
12961         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12962     Register Val = MI.getOperand(0).getReg();
12963     Register RA = MI.getOperand(1).getReg();
12964     Register RB = MI.getOperand(2).getReg();
12965     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12966     BuildMI(*BB, MI, DL,
12967             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12968                                               : TII->get(PPC::STQ))
12969         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12970         .addImm(0)
12971         .addReg(Ptr);
12972   } else {
12973     llvm_unreachable("Unexpected instr type to insert");
12974   }
12975 
12976   MI.eraseFromParent(); // The pseudo instruction is gone now.
12977   return BB;
12978 }
12979 
12980 //===----------------------------------------------------------------------===//
12981 // Target Optimization Hooks
12982 //===----------------------------------------------------------------------===//
12983 
12984 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12985   // For the estimates, convergence is quadratic, so we essentially double the
12986   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12987   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12988   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12989   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12990   if (VT.getScalarType() == MVT::f64)
12991     RefinementSteps++;
12992   return RefinementSteps;
12993 }
12994 
12995 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
12996                                             const DenormalMode &Mode) const {
12997   // We only have VSX Vector Test for software Square Root.
12998   EVT VT = Op.getValueType();
12999   if (!isTypeLegal(MVT::i1) ||
13000       (VT != MVT::f64 &&
13001        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
13002     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
13003 
13004   SDLoc DL(Op);
13005   // The output register of FTSQRT is CR field.
13006   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
13007   // ftsqrt BF,FRB
13008   // Let e_b be the unbiased exponent of the double-precision
13009   // floating-point operand in register FRB.
13010   // fe_flag is set to 1 if either of the following conditions occurs.
13011   //   - The double-precision floating-point operand in register FRB is a zero,
13012   //     a NaN, or an infinity, or a negative value.
13013   //   - e_b is less than or equal to -970.
13014   // Otherwise fe_flag is set to 0.
13015   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
13016   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
13017   // exponent is less than -970)
13018   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
13019   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
13020                                     FTSQRT, SRIdxVal),
13021                  0);
13022 }
13023 
13024 SDValue
13025 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
13026                                                SelectionDAG &DAG) const {
13027   // We only have VSX Vector Square Root.
13028   EVT VT = Op.getValueType();
13029   if (VT != MVT::f64 &&
13030       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
13031     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
13032 
13033   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
13034 }
13035 
13036 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
13037                                            int Enabled, int &RefinementSteps,
13038                                            bool &UseOneConstNR,
13039                                            bool Reciprocal) const {
13040   EVT VT = Operand.getValueType();
13041   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
13042       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
13043       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13044       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13045     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13046       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13047 
13048     // The Newton-Raphson computation with a single constant does not provide
13049     // enough accuracy on some CPUs.
13050     UseOneConstNR = !Subtarget.needsTwoConstNR();
13051     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
13052   }
13053   return SDValue();
13054 }
13055 
13056 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
13057                                             int Enabled,
13058                                             int &RefinementSteps) const {
13059   EVT VT = Operand.getValueType();
13060   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13061       (VT == MVT::f64 && Subtarget.hasFRE()) ||
13062       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13063       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13064     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13065       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13066     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13067   }
13068   return SDValue();
13069 }
13070 
13071 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13072   // Note: This functionality is used only when unsafe-fp-math is enabled, and
13073   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13074   // enabled for division), this functionality is redundant with the default
13075   // combiner logic (once the division -> reciprocal/multiply transformation
13076   // has taken place). As a result, this matters more for older cores than for
13077   // newer ones.
13078 
13079   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13080   // reciprocal if there are two or more FDIVs (for embedded cores with only
13081   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13082   switch (Subtarget.getCPUDirective()) {
13083   default:
13084     return 3;
13085   case PPC::DIR_440:
13086   case PPC::DIR_A2:
13087   case PPC::DIR_E500:
13088   case PPC::DIR_E500mc:
13089   case PPC::DIR_E5500:
13090     return 2;
13091   }
13092 }
13093 
13094 // isConsecutiveLSLoc needs to work even if all adds have not yet been
13095 // collapsed, and so we need to look through chains of them.
13096 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13097                                      int64_t& Offset, SelectionDAG &DAG) {
13098   if (DAG.isBaseWithConstantOffset(Loc)) {
13099     Base = Loc.getOperand(0);
13100     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13101 
13102     // The base might itself be a base plus an offset, and if so, accumulate
13103     // that as well.
13104     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13105   }
13106 }
13107 
13108 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13109                             unsigned Bytes, int Dist,
13110                             SelectionDAG &DAG) {
13111   if (VT.getSizeInBits() / 8 != Bytes)
13112     return false;
13113 
13114   SDValue BaseLoc = Base->getBasePtr();
13115   if (Loc.getOpcode() == ISD::FrameIndex) {
13116     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13117       return false;
13118     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13119     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13120     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13121     int FS  = MFI.getObjectSize(FI);
13122     int BFS = MFI.getObjectSize(BFI);
13123     if (FS != BFS || FS != (int)Bytes) return false;
13124     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13125   }
13126 
13127   SDValue Base1 = Loc, Base2 = BaseLoc;
13128   int64_t Offset1 = 0, Offset2 = 0;
13129   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13130   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13131   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13132     return true;
13133 
13134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13135   const GlobalValue *GV1 = nullptr;
13136   const GlobalValue *GV2 = nullptr;
13137   Offset1 = 0;
13138   Offset2 = 0;
13139   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13140   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13141   if (isGA1 && isGA2 && GV1 == GV2)
13142     return Offset1 == (Offset2 + Dist*Bytes);
13143   return false;
13144 }
13145 
13146 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13147 // not enforce equality of the chain operands.
13148 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13149                             unsigned Bytes, int Dist,
13150                             SelectionDAG &DAG) {
13151   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13152     EVT VT = LS->getMemoryVT();
13153     SDValue Loc = LS->getBasePtr();
13154     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13155   }
13156 
13157   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13158     EVT VT;
13159     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13160     default: return false;
13161     case Intrinsic::ppc_altivec_lvx:
13162     case Intrinsic::ppc_altivec_lvxl:
13163     case Intrinsic::ppc_vsx_lxvw4x:
13164     case Intrinsic::ppc_vsx_lxvw4x_be:
13165       VT = MVT::v4i32;
13166       break;
13167     case Intrinsic::ppc_vsx_lxvd2x:
13168     case Intrinsic::ppc_vsx_lxvd2x_be:
13169       VT = MVT::v2f64;
13170       break;
13171     case Intrinsic::ppc_altivec_lvebx:
13172       VT = MVT::i8;
13173       break;
13174     case Intrinsic::ppc_altivec_lvehx:
13175       VT = MVT::i16;
13176       break;
13177     case Intrinsic::ppc_altivec_lvewx:
13178       VT = MVT::i32;
13179       break;
13180     }
13181 
13182     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13183   }
13184 
13185   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13186     EVT VT;
13187     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13188     default: return false;
13189     case Intrinsic::ppc_altivec_stvx:
13190     case Intrinsic::ppc_altivec_stvxl:
13191     case Intrinsic::ppc_vsx_stxvw4x:
13192       VT = MVT::v4i32;
13193       break;
13194     case Intrinsic::ppc_vsx_stxvd2x:
13195       VT = MVT::v2f64;
13196       break;
13197     case Intrinsic::ppc_vsx_stxvw4x_be:
13198       VT = MVT::v4i32;
13199       break;
13200     case Intrinsic::ppc_vsx_stxvd2x_be:
13201       VT = MVT::v2f64;
13202       break;
13203     case Intrinsic::ppc_altivec_stvebx:
13204       VT = MVT::i8;
13205       break;
13206     case Intrinsic::ppc_altivec_stvehx:
13207       VT = MVT::i16;
13208       break;
13209     case Intrinsic::ppc_altivec_stvewx:
13210       VT = MVT::i32;
13211       break;
13212     }
13213 
13214     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13215   }
13216 
13217   return false;
13218 }
13219 
13220 // Return true is there is a nearyby consecutive load to the one provided
13221 // (regardless of alignment). We search up and down the chain, looking though
13222 // token factors and other loads (but nothing else). As a result, a true result
13223 // indicates that it is safe to create a new consecutive load adjacent to the
13224 // load provided.
13225 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13226   SDValue Chain = LD->getChain();
13227   EVT VT = LD->getMemoryVT();
13228 
13229   SmallSet<SDNode *, 16> LoadRoots;
13230   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13231   SmallSet<SDNode *, 16> Visited;
13232 
13233   // First, search up the chain, branching to follow all token-factor operands.
13234   // If we find a consecutive load, then we're done, otherwise, record all
13235   // nodes just above the top-level loads and token factors.
13236   while (!Queue.empty()) {
13237     SDNode *ChainNext = Queue.pop_back_val();
13238     if (!Visited.insert(ChainNext).second)
13239       continue;
13240 
13241     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13242       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13243         return true;
13244 
13245       if (!Visited.count(ChainLD->getChain().getNode()))
13246         Queue.push_back(ChainLD->getChain().getNode());
13247     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13248       for (const SDUse &O : ChainNext->ops())
13249         if (!Visited.count(O.getNode()))
13250           Queue.push_back(O.getNode());
13251     } else
13252       LoadRoots.insert(ChainNext);
13253   }
13254 
13255   // Second, search down the chain, starting from the top-level nodes recorded
13256   // in the first phase. These top-level nodes are the nodes just above all
13257   // loads and token factors. Starting with their uses, recursively look though
13258   // all loads (just the chain uses) and token factors to find a consecutive
13259   // load.
13260   Visited.clear();
13261   Queue.clear();
13262 
13263   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13264        IE = LoadRoots.end(); I != IE; ++I) {
13265     Queue.push_back(*I);
13266 
13267     while (!Queue.empty()) {
13268       SDNode *LoadRoot = Queue.pop_back_val();
13269       if (!Visited.insert(LoadRoot).second)
13270         continue;
13271 
13272       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13273         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13274           return true;
13275 
13276       for (SDNode *U : LoadRoot->uses())
13277         if (((isa<MemSDNode>(U) &&
13278               cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13279              U->getOpcode() == ISD::TokenFactor) &&
13280             !Visited.count(U))
13281           Queue.push_back(U);
13282     }
13283   }
13284 
13285   return false;
13286 }
13287 
13288 /// This function is called when we have proved that a SETCC node can be replaced
13289 /// by subtraction (and other supporting instructions) so that the result of
13290 /// comparison is kept in a GPR instead of CR. This function is purely for
13291 /// codegen purposes and has some flags to guide the codegen process.
13292 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13293                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13294   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13295 
13296   // Zero extend the operands to the largest legal integer. Originally, they
13297   // must be of a strictly smaller size.
13298   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13299                          DAG.getConstant(Size, DL, MVT::i32));
13300   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13301                          DAG.getConstant(Size, DL, MVT::i32));
13302 
13303   // Swap if needed. Depends on the condition code.
13304   if (Swap)
13305     std::swap(Op0, Op1);
13306 
13307   // Subtract extended integers.
13308   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13309 
13310   // Move the sign bit to the least significant position and zero out the rest.
13311   // Now the least significant bit carries the result of original comparison.
13312   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13313                              DAG.getConstant(Size - 1, DL, MVT::i32));
13314   auto Final = Shifted;
13315 
13316   // Complement the result if needed. Based on the condition code.
13317   if (Complement)
13318     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13319                         DAG.getConstant(1, DL, MVT::i64));
13320 
13321   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13322 }
13323 
13324 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13325                                                   DAGCombinerInfo &DCI) const {
13326   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13327 
13328   SelectionDAG &DAG = DCI.DAG;
13329   SDLoc DL(N);
13330 
13331   // Size of integers being compared has a critical role in the following
13332   // analysis, so we prefer to do this when all types are legal.
13333   if (!DCI.isAfterLegalizeDAG())
13334     return SDValue();
13335 
13336   // If all users of SETCC extend its value to a legal integer type
13337   // then we replace SETCC with a subtraction
13338   for (const SDNode *U : N->uses())
13339     if (U->getOpcode() != ISD::ZERO_EXTEND)
13340       return SDValue();
13341 
13342   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13343   auto OpSize = N->getOperand(0).getValueSizeInBits();
13344 
13345   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13346 
13347   if (OpSize < Size) {
13348     switch (CC) {
13349     default: break;
13350     case ISD::SETULT:
13351       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13352     case ISD::SETULE:
13353       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13354     case ISD::SETUGT:
13355       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13356     case ISD::SETUGE:
13357       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13358     }
13359   }
13360 
13361   return SDValue();
13362 }
13363 
13364 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13365                                                   DAGCombinerInfo &DCI) const {
13366   SelectionDAG &DAG = DCI.DAG;
13367   SDLoc dl(N);
13368 
13369   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13370   // If we're tracking CR bits, we need to be careful that we don't have:
13371   //   trunc(binary-ops(zext(x), zext(y)))
13372   // or
13373   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13374   // such that we're unnecessarily moving things into GPRs when it would be
13375   // better to keep them in CR bits.
13376 
13377   // Note that trunc here can be an actual i1 trunc, or can be the effective
13378   // truncation that comes from a setcc or select_cc.
13379   if (N->getOpcode() == ISD::TRUNCATE &&
13380       N->getValueType(0) != MVT::i1)
13381     return SDValue();
13382 
13383   if (N->getOperand(0).getValueType() != MVT::i32 &&
13384       N->getOperand(0).getValueType() != MVT::i64)
13385     return SDValue();
13386 
13387   if (N->getOpcode() == ISD::SETCC ||
13388       N->getOpcode() == ISD::SELECT_CC) {
13389     // If we're looking at a comparison, then we need to make sure that the
13390     // high bits (all except for the first) don't matter the result.
13391     ISD::CondCode CC =
13392       cast<CondCodeSDNode>(N->getOperand(
13393         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13394     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13395 
13396     if (ISD::isSignedIntSetCC(CC)) {
13397       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13398           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13399         return SDValue();
13400     } else if (ISD::isUnsignedIntSetCC(CC)) {
13401       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13402                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13403           !DAG.MaskedValueIsZero(N->getOperand(1),
13404                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13405         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13406                                              : SDValue());
13407     } else {
13408       // This is neither a signed nor an unsigned comparison, just make sure
13409       // that the high bits are equal.
13410       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13411       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13412 
13413       // We don't really care about what is known about the first bit (if
13414       // anything), so pretend that it is known zero for both to ensure they can
13415       // be compared as constants.
13416       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13417       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13418 
13419       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13420           Op1Known.getConstant() != Op2Known.getConstant())
13421         return SDValue();
13422     }
13423   }
13424 
13425   // We now know that the higher-order bits are irrelevant, we just need to
13426   // make sure that all of the intermediate operations are bit operations, and
13427   // all inputs are extensions.
13428   if (N->getOperand(0).getOpcode() != ISD::AND &&
13429       N->getOperand(0).getOpcode() != ISD::OR  &&
13430       N->getOperand(0).getOpcode() != ISD::XOR &&
13431       N->getOperand(0).getOpcode() != ISD::SELECT &&
13432       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13433       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13434       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13435       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13436       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13437     return SDValue();
13438 
13439   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13440       N->getOperand(1).getOpcode() != ISD::AND &&
13441       N->getOperand(1).getOpcode() != ISD::OR  &&
13442       N->getOperand(1).getOpcode() != ISD::XOR &&
13443       N->getOperand(1).getOpcode() != ISD::SELECT &&
13444       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13445       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13446       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13447       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13448       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13449     return SDValue();
13450 
13451   SmallVector<SDValue, 4> Inputs;
13452   SmallVector<SDValue, 8> BinOps, PromOps;
13453   SmallPtrSet<SDNode *, 16> Visited;
13454 
13455   for (unsigned i = 0; i < 2; ++i) {
13456     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13457           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13458           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13459           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13460         isa<ConstantSDNode>(N->getOperand(i)))
13461       Inputs.push_back(N->getOperand(i));
13462     else
13463       BinOps.push_back(N->getOperand(i));
13464 
13465     if (N->getOpcode() == ISD::TRUNCATE)
13466       break;
13467   }
13468 
13469   // Visit all inputs, collect all binary operations (and, or, xor and
13470   // select) that are all fed by extensions.
13471   while (!BinOps.empty()) {
13472     SDValue BinOp = BinOps.pop_back_val();
13473 
13474     if (!Visited.insert(BinOp.getNode()).second)
13475       continue;
13476 
13477     PromOps.push_back(BinOp);
13478 
13479     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13480       // The condition of the select is not promoted.
13481       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13482         continue;
13483       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13484         continue;
13485 
13486       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13487             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13488             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13489            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13490           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13491         Inputs.push_back(BinOp.getOperand(i));
13492       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13493                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13494                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13495                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13496                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13497                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13498                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13499                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13500                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13501         BinOps.push_back(BinOp.getOperand(i));
13502       } else {
13503         // We have an input that is not an extension or another binary
13504         // operation; we'll abort this transformation.
13505         return SDValue();
13506       }
13507     }
13508   }
13509 
13510   // Make sure that this is a self-contained cluster of operations (which
13511   // is not quite the same thing as saying that everything has only one
13512   // use).
13513   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13514     if (isa<ConstantSDNode>(Inputs[i]))
13515       continue;
13516 
13517     for (const SDNode *User : Inputs[i].getNode()->uses()) {
13518       if (User != N && !Visited.count(User))
13519         return SDValue();
13520 
13521       // Make sure that we're not going to promote the non-output-value
13522       // operand(s) or SELECT or SELECT_CC.
13523       // FIXME: Although we could sometimes handle this, and it does occur in
13524       // practice that one of the condition inputs to the select is also one of
13525       // the outputs, we currently can't deal with this.
13526       if (User->getOpcode() == ISD::SELECT) {
13527         if (User->getOperand(0) == Inputs[i])
13528           return SDValue();
13529       } else if (User->getOpcode() == ISD::SELECT_CC) {
13530         if (User->getOperand(0) == Inputs[i] ||
13531             User->getOperand(1) == Inputs[i])
13532           return SDValue();
13533       }
13534     }
13535   }
13536 
13537   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13538     for (const SDNode *User : PromOps[i].getNode()->uses()) {
13539       if (User != N && !Visited.count(User))
13540         return SDValue();
13541 
13542       // Make sure that we're not going to promote the non-output-value
13543       // operand(s) or SELECT or SELECT_CC.
13544       // FIXME: Although we could sometimes handle this, and it does occur in
13545       // practice that one of the condition inputs to the select is also one of
13546       // the outputs, we currently can't deal with this.
13547       if (User->getOpcode() == ISD::SELECT) {
13548         if (User->getOperand(0) == PromOps[i])
13549           return SDValue();
13550       } else if (User->getOpcode() == ISD::SELECT_CC) {
13551         if (User->getOperand(0) == PromOps[i] ||
13552             User->getOperand(1) == PromOps[i])
13553           return SDValue();
13554       }
13555     }
13556   }
13557 
13558   // Replace all inputs with the extension operand.
13559   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13560     // Constants may have users outside the cluster of to-be-promoted nodes,
13561     // and so we need to replace those as we do the promotions.
13562     if (isa<ConstantSDNode>(Inputs[i]))
13563       continue;
13564     else
13565       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13566   }
13567 
13568   std::list<HandleSDNode> PromOpHandles;
13569   for (auto &PromOp : PromOps)
13570     PromOpHandles.emplace_back(PromOp);
13571 
13572   // Replace all operations (these are all the same, but have a different
13573   // (i1) return type). DAG.getNode will validate that the types of
13574   // a binary operator match, so go through the list in reverse so that
13575   // we've likely promoted both operands first. Any intermediate truncations or
13576   // extensions disappear.
13577   while (!PromOpHandles.empty()) {
13578     SDValue PromOp = PromOpHandles.back().getValue();
13579     PromOpHandles.pop_back();
13580 
13581     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13582         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13583         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13584         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13585       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13586           PromOp.getOperand(0).getValueType() != MVT::i1) {
13587         // The operand is not yet ready (see comment below).
13588         PromOpHandles.emplace_front(PromOp);
13589         continue;
13590       }
13591 
13592       SDValue RepValue = PromOp.getOperand(0);
13593       if (isa<ConstantSDNode>(RepValue))
13594         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13595 
13596       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13597       continue;
13598     }
13599 
13600     unsigned C;
13601     switch (PromOp.getOpcode()) {
13602     default:             C = 0; break;
13603     case ISD::SELECT:    C = 1; break;
13604     case ISD::SELECT_CC: C = 2; break;
13605     }
13606 
13607     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13608          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13609         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13610          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13611       // The to-be-promoted operands of this node have not yet been
13612       // promoted (this should be rare because we're going through the
13613       // list backward, but if one of the operands has several users in
13614       // this cluster of to-be-promoted nodes, it is possible).
13615       PromOpHandles.emplace_front(PromOp);
13616       continue;
13617     }
13618 
13619     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13620                                 PromOp.getNode()->op_end());
13621 
13622     // If there are any constant inputs, make sure they're replaced now.
13623     for (unsigned i = 0; i < 2; ++i)
13624       if (isa<ConstantSDNode>(Ops[C+i]))
13625         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13626 
13627     DAG.ReplaceAllUsesOfValueWith(PromOp,
13628       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13629   }
13630 
13631   // Now we're left with the initial truncation itself.
13632   if (N->getOpcode() == ISD::TRUNCATE)
13633     return N->getOperand(0);
13634 
13635   // Otherwise, this is a comparison. The operands to be compared have just
13636   // changed type (to i1), but everything else is the same.
13637   return SDValue(N, 0);
13638 }
13639 
13640 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13641                                                   DAGCombinerInfo &DCI) const {
13642   SelectionDAG &DAG = DCI.DAG;
13643   SDLoc dl(N);
13644 
13645   // If we're tracking CR bits, we need to be careful that we don't have:
13646   //   zext(binary-ops(trunc(x), trunc(y)))
13647   // or
13648   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13649   // such that we're unnecessarily moving things into CR bits that can more
13650   // efficiently stay in GPRs. Note that if we're not certain that the high
13651   // bits are set as required by the final extension, we still may need to do
13652   // some masking to get the proper behavior.
13653 
13654   // This same functionality is important on PPC64 when dealing with
13655   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13656   // the return values of functions. Because it is so similar, it is handled
13657   // here as well.
13658 
13659   if (N->getValueType(0) != MVT::i32 &&
13660       N->getValueType(0) != MVT::i64)
13661     return SDValue();
13662 
13663   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13664         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13665     return SDValue();
13666 
13667   if (N->getOperand(0).getOpcode() != ISD::AND &&
13668       N->getOperand(0).getOpcode() != ISD::OR  &&
13669       N->getOperand(0).getOpcode() != ISD::XOR &&
13670       N->getOperand(0).getOpcode() != ISD::SELECT &&
13671       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13672     return SDValue();
13673 
13674   SmallVector<SDValue, 4> Inputs;
13675   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13676   SmallPtrSet<SDNode *, 16> Visited;
13677 
13678   // Visit all inputs, collect all binary operations (and, or, xor and
13679   // select) that are all fed by truncations.
13680   while (!BinOps.empty()) {
13681     SDValue BinOp = BinOps.pop_back_val();
13682 
13683     if (!Visited.insert(BinOp.getNode()).second)
13684       continue;
13685 
13686     PromOps.push_back(BinOp);
13687 
13688     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13689       // The condition of the select is not promoted.
13690       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13691         continue;
13692       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13693         continue;
13694 
13695       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13696           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13697         Inputs.push_back(BinOp.getOperand(i));
13698       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13699                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13700                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13701                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13702                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13703         BinOps.push_back(BinOp.getOperand(i));
13704       } else {
13705         // We have an input that is not a truncation or another binary
13706         // operation; we'll abort this transformation.
13707         return SDValue();
13708       }
13709     }
13710   }
13711 
13712   // The operands of a select that must be truncated when the select is
13713   // promoted because the operand is actually part of the to-be-promoted set.
13714   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13715 
13716   // Make sure that this is a self-contained cluster of operations (which
13717   // is not quite the same thing as saying that everything has only one
13718   // use).
13719   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13720     if (isa<ConstantSDNode>(Inputs[i]))
13721       continue;
13722 
13723     for (SDNode *User : Inputs[i].getNode()->uses()) {
13724       if (User != N && !Visited.count(User))
13725         return SDValue();
13726 
13727       // If we're going to promote the non-output-value operand(s) or SELECT or
13728       // SELECT_CC, record them for truncation.
13729       if (User->getOpcode() == ISD::SELECT) {
13730         if (User->getOperand(0) == Inputs[i])
13731           SelectTruncOp[0].insert(std::make_pair(User,
13732                                     User->getOperand(0).getValueType()));
13733       } else if (User->getOpcode() == ISD::SELECT_CC) {
13734         if (User->getOperand(0) == Inputs[i])
13735           SelectTruncOp[0].insert(std::make_pair(User,
13736                                     User->getOperand(0).getValueType()));
13737         if (User->getOperand(1) == Inputs[i])
13738           SelectTruncOp[1].insert(std::make_pair(User,
13739                                     User->getOperand(1).getValueType()));
13740       }
13741     }
13742   }
13743 
13744   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13745     for (SDNode *User : PromOps[i].getNode()->uses()) {
13746       if (User != N && !Visited.count(User))
13747         return SDValue();
13748 
13749       // If we're going to promote the non-output-value operand(s) or SELECT or
13750       // SELECT_CC, record them for truncation.
13751       if (User->getOpcode() == ISD::SELECT) {
13752         if (User->getOperand(0) == PromOps[i])
13753           SelectTruncOp[0].insert(std::make_pair(User,
13754                                     User->getOperand(0).getValueType()));
13755       } else if (User->getOpcode() == ISD::SELECT_CC) {
13756         if (User->getOperand(0) == PromOps[i])
13757           SelectTruncOp[0].insert(std::make_pair(User,
13758                                     User->getOperand(0).getValueType()));
13759         if (User->getOperand(1) == PromOps[i])
13760           SelectTruncOp[1].insert(std::make_pair(User,
13761                                     User->getOperand(1).getValueType()));
13762       }
13763     }
13764   }
13765 
13766   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13767   bool ReallyNeedsExt = false;
13768   if (N->getOpcode() != ISD::ANY_EXTEND) {
13769     // If all of the inputs are not already sign/zero extended, then
13770     // we'll still need to do that at the end.
13771     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13772       if (isa<ConstantSDNode>(Inputs[i]))
13773         continue;
13774 
13775       unsigned OpBits =
13776         Inputs[i].getOperand(0).getValueSizeInBits();
13777       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13778 
13779       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13780            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13781                                   APInt::getHighBitsSet(OpBits,
13782                                                         OpBits-PromBits))) ||
13783           (N->getOpcode() == ISD::SIGN_EXTEND &&
13784            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13785              (OpBits-(PromBits-1)))) {
13786         ReallyNeedsExt = true;
13787         break;
13788       }
13789     }
13790   }
13791 
13792   // Replace all inputs, either with the truncation operand, or a
13793   // truncation or extension to the final output type.
13794   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13795     // Constant inputs need to be replaced with the to-be-promoted nodes that
13796     // use them because they might have users outside of the cluster of
13797     // promoted nodes.
13798     if (isa<ConstantSDNode>(Inputs[i]))
13799       continue;
13800 
13801     SDValue InSrc = Inputs[i].getOperand(0);
13802     if (Inputs[i].getValueType() == N->getValueType(0))
13803       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13804     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13805       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13806         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13807     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13808       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13809         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13810     else
13811       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13812         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13813   }
13814 
13815   std::list<HandleSDNode> PromOpHandles;
13816   for (auto &PromOp : PromOps)
13817     PromOpHandles.emplace_back(PromOp);
13818 
13819   // Replace all operations (these are all the same, but have a different
13820   // (promoted) return type). DAG.getNode will validate that the types of
13821   // a binary operator match, so go through the list in reverse so that
13822   // we've likely promoted both operands first.
13823   while (!PromOpHandles.empty()) {
13824     SDValue PromOp = PromOpHandles.back().getValue();
13825     PromOpHandles.pop_back();
13826 
13827     unsigned C;
13828     switch (PromOp.getOpcode()) {
13829     default:             C = 0; break;
13830     case ISD::SELECT:    C = 1; break;
13831     case ISD::SELECT_CC: C = 2; break;
13832     }
13833 
13834     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13835          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13836         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13837          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13838       // The to-be-promoted operands of this node have not yet been
13839       // promoted (this should be rare because we're going through the
13840       // list backward, but if one of the operands has several users in
13841       // this cluster of to-be-promoted nodes, it is possible).
13842       PromOpHandles.emplace_front(PromOp);
13843       continue;
13844     }
13845 
13846     // For SELECT and SELECT_CC nodes, we do a similar check for any
13847     // to-be-promoted comparison inputs.
13848     if (PromOp.getOpcode() == ISD::SELECT ||
13849         PromOp.getOpcode() == ISD::SELECT_CC) {
13850       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13851            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13852           (SelectTruncOp[1].count(PromOp.getNode()) &&
13853            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13854         PromOpHandles.emplace_front(PromOp);
13855         continue;
13856       }
13857     }
13858 
13859     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13860                                 PromOp.getNode()->op_end());
13861 
13862     // If this node has constant inputs, then they'll need to be promoted here.
13863     for (unsigned i = 0; i < 2; ++i) {
13864       if (!isa<ConstantSDNode>(Ops[C+i]))
13865         continue;
13866       if (Ops[C+i].getValueType() == N->getValueType(0))
13867         continue;
13868 
13869       if (N->getOpcode() == ISD::SIGN_EXTEND)
13870         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13871       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13872         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13873       else
13874         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13875     }
13876 
13877     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13878     // truncate them again to the original value type.
13879     if (PromOp.getOpcode() == ISD::SELECT ||
13880         PromOp.getOpcode() == ISD::SELECT_CC) {
13881       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13882       if (SI0 != SelectTruncOp[0].end())
13883         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13884       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13885       if (SI1 != SelectTruncOp[1].end())
13886         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13887     }
13888 
13889     DAG.ReplaceAllUsesOfValueWith(PromOp,
13890       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13891   }
13892 
13893   // Now we're left with the initial extension itself.
13894   if (!ReallyNeedsExt)
13895     return N->getOperand(0);
13896 
13897   // To zero extend, just mask off everything except for the first bit (in the
13898   // i1 case).
13899   if (N->getOpcode() == ISD::ZERO_EXTEND)
13900     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13901                        DAG.getConstant(APInt::getLowBitsSet(
13902                                          N->getValueSizeInBits(0), PromBits),
13903                                        dl, N->getValueType(0)));
13904 
13905   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13906          "Invalid extension type");
13907   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13908   SDValue ShiftCst =
13909       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13910   return DAG.getNode(
13911       ISD::SRA, dl, N->getValueType(0),
13912       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13913       ShiftCst);
13914 }
13915 
13916 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13917                                         DAGCombinerInfo &DCI) const {
13918   assert(N->getOpcode() == ISD::SETCC &&
13919          "Should be called with a SETCC node");
13920 
13921   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13922   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13923     SDValue LHS = N->getOperand(0);
13924     SDValue RHS = N->getOperand(1);
13925 
13926     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13927     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13928         LHS.hasOneUse())
13929       std::swap(LHS, RHS);
13930 
13931     // x == 0-y --> x+y == 0
13932     // x != 0-y --> x+y != 0
13933     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13934         RHS.hasOneUse()) {
13935       SDLoc DL(N);
13936       SelectionDAG &DAG = DCI.DAG;
13937       EVT VT = N->getValueType(0);
13938       EVT OpVT = LHS.getValueType();
13939       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13940       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13941     }
13942   }
13943 
13944   return DAGCombineTruncBoolExt(N, DCI);
13945 }
13946 
13947 // Is this an extending load from an f32 to an f64?
13948 static bool isFPExtLoad(SDValue Op) {
13949   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13950     return LD->getExtensionType() == ISD::EXTLOAD &&
13951       Op.getValueType() == MVT::f64;
13952   return false;
13953 }
13954 
13955 /// Reduces the number of fp-to-int conversion when building a vector.
13956 ///
13957 /// If this vector is built out of floating to integer conversions,
13958 /// transform it to a vector built out of floating point values followed by a
13959 /// single floating to integer conversion of the vector.
13960 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13961 /// becomes (fptosi (build_vector ($A, $B, ...)))
13962 SDValue PPCTargetLowering::
13963 combineElementTruncationToVectorTruncation(SDNode *N,
13964                                            DAGCombinerInfo &DCI) const {
13965   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13966          "Should be called with a BUILD_VECTOR node");
13967 
13968   SelectionDAG &DAG = DCI.DAG;
13969   SDLoc dl(N);
13970 
13971   SDValue FirstInput = N->getOperand(0);
13972   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13973          "The input operand must be an fp-to-int conversion.");
13974 
13975   // This combine happens after legalization so the fp_to_[su]i nodes are
13976   // already converted to PPCSISD nodes.
13977   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13978   if (FirstConversion == PPCISD::FCTIDZ ||
13979       FirstConversion == PPCISD::FCTIDUZ ||
13980       FirstConversion == PPCISD::FCTIWZ ||
13981       FirstConversion == PPCISD::FCTIWUZ) {
13982     bool IsSplat = true;
13983     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13984       FirstConversion == PPCISD::FCTIWUZ;
13985     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13986     SmallVector<SDValue, 4> Ops;
13987     EVT TargetVT = N->getValueType(0);
13988     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13989       SDValue NextOp = N->getOperand(i);
13990       if (NextOp.getOpcode() != PPCISD::MFVSR)
13991         return SDValue();
13992       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13993       if (NextConversion != FirstConversion)
13994         return SDValue();
13995       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13996       // This is not valid if the input was originally double precision. It is
13997       // also not profitable to do unless this is an extending load in which
13998       // case doing this combine will allow us to combine consecutive loads.
13999       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
14000         return SDValue();
14001       if (N->getOperand(i) != FirstInput)
14002         IsSplat = false;
14003     }
14004 
14005     // If this is a splat, we leave it as-is since there will be only a single
14006     // fp-to-int conversion followed by a splat of the integer. This is better
14007     // for 32-bit and smaller ints and neutral for 64-bit ints.
14008     if (IsSplat)
14009       return SDValue();
14010 
14011     // Now that we know we have the right type of node, get its operands
14012     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14013       SDValue In = N->getOperand(i).getOperand(0);
14014       if (Is32Bit) {
14015         // For 32-bit values, we need to add an FP_ROUND node (if we made it
14016         // here, we know that all inputs are extending loads so this is safe).
14017         if (In.isUndef())
14018           Ops.push_back(DAG.getUNDEF(SrcVT));
14019         else {
14020           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
14021                                       MVT::f32, In.getOperand(0),
14022                                       DAG.getIntPtrConstant(1, dl));
14023           Ops.push_back(Trunc);
14024         }
14025       } else
14026         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
14027     }
14028 
14029     unsigned Opcode;
14030     if (FirstConversion == PPCISD::FCTIDZ ||
14031         FirstConversion == PPCISD::FCTIWZ)
14032       Opcode = ISD::FP_TO_SINT;
14033     else
14034       Opcode = ISD::FP_TO_UINT;
14035 
14036     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
14037     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
14038     return DAG.getNode(Opcode, dl, TargetVT, BV);
14039   }
14040   return SDValue();
14041 }
14042 
14043 /// Reduce the number of loads when building a vector.
14044 ///
14045 /// Building a vector out of multiple loads can be converted to a load
14046 /// of the vector type if the loads are consecutive. If the loads are
14047 /// consecutive but in descending order, a shuffle is added at the end
14048 /// to reorder the vector.
14049 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
14050   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14051          "Should be called with a BUILD_VECTOR node");
14052 
14053   SDLoc dl(N);
14054 
14055   // Return early for non byte-sized type, as they can't be consecutive.
14056   if (!N->getValueType(0).getVectorElementType().isByteSized())
14057     return SDValue();
14058 
14059   bool InputsAreConsecutiveLoads = true;
14060   bool InputsAreReverseConsecutive = true;
14061   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14062   SDValue FirstInput = N->getOperand(0);
14063   bool IsRoundOfExtLoad = false;
14064 
14065   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14066       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14067     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
14068     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
14069   }
14070   // Not a build vector of (possibly fp_rounded) loads.
14071   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14072       N->getNumOperands() == 1)
14073     return SDValue();
14074 
14075   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14076     // If any inputs are fp_round(extload), they all must be.
14077     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14078       return SDValue();
14079 
14080     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14081       N->getOperand(i);
14082     if (NextInput.getOpcode() != ISD::LOAD)
14083       return SDValue();
14084 
14085     SDValue PreviousInput =
14086       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14087     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
14088     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
14089 
14090     // If any inputs are fp_round(extload), they all must be.
14091     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14092       return SDValue();
14093 
14094     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
14095       InputsAreConsecutiveLoads = false;
14096     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14097       InputsAreReverseConsecutive = false;
14098 
14099     // Exit early if the loads are neither consecutive nor reverse consecutive.
14100     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14101       return SDValue();
14102   }
14103 
14104   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14105          "The loads cannot be both consecutive and reverse consecutive.");
14106 
14107   SDValue FirstLoadOp =
14108     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14109   SDValue LastLoadOp =
14110     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14111                        N->getOperand(N->getNumOperands()-1);
14112 
14113   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14114   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14115   if (InputsAreConsecutiveLoads) {
14116     assert(LD1 && "Input needs to be a LoadSDNode.");
14117     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14118                        LD1->getBasePtr(), LD1->getPointerInfo(),
14119                        LD1->getAlignment());
14120   }
14121   if (InputsAreReverseConsecutive) {
14122     assert(LDL && "Input needs to be a LoadSDNode.");
14123     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14124                                LDL->getBasePtr(), LDL->getPointerInfo(),
14125                                LDL->getAlignment());
14126     SmallVector<int, 16> Ops;
14127     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14128       Ops.push_back(i);
14129 
14130     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14131                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14132   }
14133   return SDValue();
14134 }
14135 
14136 // This function adds the required vector_shuffle needed to get
14137 // the elements of the vector extract in the correct position
14138 // as specified by the CorrectElems encoding.
14139 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14140                                       SDValue Input, uint64_t Elems,
14141                                       uint64_t CorrectElems) {
14142   SDLoc dl(N);
14143 
14144   unsigned NumElems = Input.getValueType().getVectorNumElements();
14145   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14146 
14147   // Knowing the element indices being extracted from the original
14148   // vector and the order in which they're being inserted, just put
14149   // them at element indices required for the instruction.
14150   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14151     if (DAG.getDataLayout().isLittleEndian())
14152       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14153     else
14154       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14155     CorrectElems = CorrectElems >> 8;
14156     Elems = Elems >> 8;
14157   }
14158 
14159   SDValue Shuffle =
14160       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14161                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14162 
14163   EVT VT = N->getValueType(0);
14164   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14165 
14166   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14167                                Input.getValueType().getVectorElementType(),
14168                                VT.getVectorNumElements());
14169   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14170                      DAG.getValueType(ExtVT));
14171 }
14172 
14173 // Look for build vector patterns where input operands come from sign
14174 // extended vector_extract elements of specific indices. If the correct indices
14175 // aren't used, add a vector shuffle to fix up the indices and create
14176 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14177 // during instruction selection.
14178 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14179   // This array encodes the indices that the vector sign extend instructions
14180   // extract from when extending from one type to another for both BE and LE.
14181   // The right nibble of each byte corresponds to the LE incides.
14182   // and the left nibble of each byte corresponds to the BE incides.
14183   // For example: 0x3074B8FC  byte->word
14184   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14185   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14186   // For example: 0x000070F8  byte->double word
14187   // For LE: the allowed indices are: 0x0,0x8
14188   // For BE: the allowed indices are: 0x7,0xF
14189   uint64_t TargetElems[] = {
14190       0x3074B8FC, // b->w
14191       0x000070F8, // b->d
14192       0x10325476, // h->w
14193       0x00003074, // h->d
14194       0x00001032, // w->d
14195   };
14196 
14197   uint64_t Elems = 0;
14198   int Index;
14199   SDValue Input;
14200 
14201   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14202     if (!Op)
14203       return false;
14204     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14205         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14206       return false;
14207 
14208     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14209     // of the right width.
14210     SDValue Extract = Op.getOperand(0);
14211     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14212       Extract = Extract.getOperand(0);
14213     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14214       return false;
14215 
14216     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14217     if (!ExtOp)
14218       return false;
14219 
14220     Index = ExtOp->getZExtValue();
14221     if (Input && Input != Extract.getOperand(0))
14222       return false;
14223 
14224     if (!Input)
14225       Input = Extract.getOperand(0);
14226 
14227     Elems = Elems << 8;
14228     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14229     Elems |= Index;
14230 
14231     return true;
14232   };
14233 
14234   // If the build vector operands aren't sign extended vector extracts,
14235   // of the same input vector, then return.
14236   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14237     if (!isSExtOfVecExtract(N->getOperand(i))) {
14238       return SDValue();
14239     }
14240   }
14241 
14242   // If the vector extract indicies are not correct, add the appropriate
14243   // vector_shuffle.
14244   int TgtElemArrayIdx;
14245   int InputSize = Input.getValueType().getScalarSizeInBits();
14246   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14247   if (InputSize + OutputSize == 40)
14248     TgtElemArrayIdx = 0;
14249   else if (InputSize + OutputSize == 72)
14250     TgtElemArrayIdx = 1;
14251   else if (InputSize + OutputSize == 48)
14252     TgtElemArrayIdx = 2;
14253   else if (InputSize + OutputSize == 80)
14254     TgtElemArrayIdx = 3;
14255   else if (InputSize + OutputSize == 96)
14256     TgtElemArrayIdx = 4;
14257   else
14258     return SDValue();
14259 
14260   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14261   CorrectElems = DAG.getDataLayout().isLittleEndian()
14262                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14263                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14264   if (Elems != CorrectElems) {
14265     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14266   }
14267 
14268   // Regular lowering will catch cases where a shuffle is not needed.
14269   return SDValue();
14270 }
14271 
14272 // Look for the pattern of a load from a narrow width to i128, feeding
14273 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14274 // (LXVRZX). This node represents a zero extending load that will be matched
14275 // to the Load VSX Vector Rightmost instructions.
14276 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14277   SDLoc DL(N);
14278 
14279   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14280   if (N->getValueType(0) != MVT::v1i128)
14281     return SDValue();
14282 
14283   SDValue Operand = N->getOperand(0);
14284   // Proceed with the transformation if the operand to the BUILD_VECTOR
14285   // is a load instruction.
14286   if (Operand.getOpcode() != ISD::LOAD)
14287     return SDValue();
14288 
14289   auto *LD = cast<LoadSDNode>(Operand);
14290   EVT MemoryType = LD->getMemoryVT();
14291 
14292   // This transformation is only valid if the we are loading either a byte,
14293   // halfword, word, or doubleword.
14294   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14295                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14296 
14297   // Ensure that the load from the narrow width is being zero extended to i128.
14298   if (!ValidLDType ||
14299       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14300        LD->getExtensionType() != ISD::EXTLOAD))
14301     return SDValue();
14302 
14303   SDValue LoadOps[] = {
14304       LD->getChain(), LD->getBasePtr(),
14305       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14306 
14307   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14308                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14309                                  LoadOps, MemoryType, LD->getMemOperand());
14310 }
14311 
14312 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14313                                                  DAGCombinerInfo &DCI) const {
14314   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14315          "Should be called with a BUILD_VECTOR node");
14316 
14317   SelectionDAG &DAG = DCI.DAG;
14318   SDLoc dl(N);
14319 
14320   if (!Subtarget.hasVSX())
14321     return SDValue();
14322 
14323   // The target independent DAG combiner will leave a build_vector of
14324   // float-to-int conversions intact. We can generate MUCH better code for
14325   // a float-to-int conversion of a vector of floats.
14326   SDValue FirstInput = N->getOperand(0);
14327   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14328     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14329     if (Reduced)
14330       return Reduced;
14331   }
14332 
14333   // If we're building a vector out of consecutive loads, just load that
14334   // vector type.
14335   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14336   if (Reduced)
14337     return Reduced;
14338 
14339   // If we're building a vector out of extended elements from another vector
14340   // we have P9 vector integer extend instructions. The code assumes legal
14341   // input types (i.e. it can't handle things like v4i16) so do not run before
14342   // legalization.
14343   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14344     Reduced = combineBVOfVecSExt(N, DAG);
14345     if (Reduced)
14346       return Reduced;
14347   }
14348 
14349   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14350   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14351   // is a load from <valid narrow width> to i128.
14352   if (Subtarget.isISA3_1()) {
14353     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14354     if (BVOfZLoad)
14355       return BVOfZLoad;
14356   }
14357 
14358   if (N->getValueType(0) != MVT::v2f64)
14359     return SDValue();
14360 
14361   // Looking for:
14362   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14363   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14364       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14365     return SDValue();
14366   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14367       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14368     return SDValue();
14369   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14370     return SDValue();
14371 
14372   SDValue Ext1 = FirstInput.getOperand(0);
14373   SDValue Ext2 = N->getOperand(1).getOperand(0);
14374   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14375      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14376     return SDValue();
14377 
14378   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14379   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14380   if (!Ext1Op || !Ext2Op)
14381     return SDValue();
14382   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14383       Ext1.getOperand(0) != Ext2.getOperand(0))
14384     return SDValue();
14385 
14386   int FirstElem = Ext1Op->getZExtValue();
14387   int SecondElem = Ext2Op->getZExtValue();
14388   int SubvecIdx;
14389   if (FirstElem == 0 && SecondElem == 1)
14390     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14391   else if (FirstElem == 2 && SecondElem == 3)
14392     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14393   else
14394     return SDValue();
14395 
14396   SDValue SrcVec = Ext1.getOperand(0);
14397   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14398     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14399   return DAG.getNode(NodeType, dl, MVT::v2f64,
14400                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14401 }
14402 
14403 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14404                                               DAGCombinerInfo &DCI) const {
14405   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14406           N->getOpcode() == ISD::UINT_TO_FP) &&
14407          "Need an int -> FP conversion node here");
14408 
14409   if (useSoftFloat() || !Subtarget.has64BitSupport())
14410     return SDValue();
14411 
14412   SelectionDAG &DAG = DCI.DAG;
14413   SDLoc dl(N);
14414   SDValue Op(N, 0);
14415 
14416   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14417   // from the hardware.
14418   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14419     return SDValue();
14420   if (!Op.getOperand(0).getValueType().isSimple())
14421     return SDValue();
14422   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14423       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14424     return SDValue();
14425 
14426   SDValue FirstOperand(Op.getOperand(0));
14427   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14428     (FirstOperand.getValueType() == MVT::i8 ||
14429      FirstOperand.getValueType() == MVT::i16);
14430   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14431     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14432     bool DstDouble = Op.getValueType() == MVT::f64;
14433     unsigned ConvOp = Signed ?
14434       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14435       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14436     SDValue WidthConst =
14437       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14438                             dl, false);
14439     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14440     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14441     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14442                                          DAG.getVTList(MVT::f64, MVT::Other),
14443                                          Ops, MVT::i8, LDN->getMemOperand());
14444 
14445     // For signed conversion, we need to sign-extend the value in the VSR
14446     if (Signed) {
14447       SDValue ExtOps[] = { Ld, WidthConst };
14448       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14449       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14450     } else
14451       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14452   }
14453 
14454 
14455   // For i32 intermediate values, unfortunately, the conversion functions
14456   // leave the upper 32 bits of the value are undefined. Within the set of
14457   // scalar instructions, we have no method for zero- or sign-extending the
14458   // value. Thus, we cannot handle i32 intermediate values here.
14459   if (Op.getOperand(0).getValueType() == MVT::i32)
14460     return SDValue();
14461 
14462   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14463          "UINT_TO_FP is supported only with FPCVT");
14464 
14465   // If we have FCFIDS, then use it when converting to single-precision.
14466   // Otherwise, convert to double-precision and then round.
14467   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14468                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14469                                                             : PPCISD::FCFIDS)
14470                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14471                                                             : PPCISD::FCFID);
14472   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14473                   ? MVT::f32
14474                   : MVT::f64;
14475 
14476   // If we're converting from a float, to an int, and back to a float again,
14477   // then we don't need the store/load pair at all.
14478   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14479        Subtarget.hasFPCVT()) ||
14480       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14481     SDValue Src = Op.getOperand(0).getOperand(0);
14482     if (Src.getValueType() == MVT::f32) {
14483       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14484       DCI.AddToWorklist(Src.getNode());
14485     } else if (Src.getValueType() != MVT::f64) {
14486       // Make sure that we don't pick up a ppc_fp128 source value.
14487       return SDValue();
14488     }
14489 
14490     unsigned FCTOp =
14491       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14492                                                         PPCISD::FCTIDUZ;
14493 
14494     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14495     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14496 
14497     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14498       FP = DAG.getNode(ISD::FP_ROUND, dl,
14499                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14500       DCI.AddToWorklist(FP.getNode());
14501     }
14502 
14503     return FP;
14504   }
14505 
14506   return SDValue();
14507 }
14508 
14509 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14510 // builtins) into loads with swaps.
14511 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14512                                               DAGCombinerInfo &DCI) const {
14513   SelectionDAG &DAG = DCI.DAG;
14514   SDLoc dl(N);
14515   SDValue Chain;
14516   SDValue Base;
14517   MachineMemOperand *MMO;
14518 
14519   switch (N->getOpcode()) {
14520   default:
14521     llvm_unreachable("Unexpected opcode for little endian VSX load");
14522   case ISD::LOAD: {
14523     LoadSDNode *LD = cast<LoadSDNode>(N);
14524     Chain = LD->getChain();
14525     Base = LD->getBasePtr();
14526     MMO = LD->getMemOperand();
14527     // If the MMO suggests this isn't a load of a full vector, leave
14528     // things alone.  For a built-in, we have to make the change for
14529     // correctness, so if there is a size problem that will be a bug.
14530     if (MMO->getSize() < 16)
14531       return SDValue();
14532     break;
14533   }
14534   case ISD::INTRINSIC_W_CHAIN: {
14535     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14536     Chain = Intrin->getChain();
14537     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14538     // us what we want. Get operand 2 instead.
14539     Base = Intrin->getOperand(2);
14540     MMO = Intrin->getMemOperand();
14541     break;
14542   }
14543   }
14544 
14545   MVT VecTy = N->getValueType(0).getSimpleVT();
14546 
14547   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14548   // aligned and the type is a vector with elements up to 4 bytes
14549   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14550       VecTy.getScalarSizeInBits() <= 32) {
14551     return SDValue();
14552   }
14553 
14554   SDValue LoadOps[] = { Chain, Base };
14555   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14556                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14557                                          LoadOps, MVT::v2f64, MMO);
14558 
14559   DCI.AddToWorklist(Load.getNode());
14560   Chain = Load.getValue(1);
14561   SDValue Swap = DAG.getNode(
14562       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14563   DCI.AddToWorklist(Swap.getNode());
14564 
14565   // Add a bitcast if the resulting load type doesn't match v2f64.
14566   if (VecTy != MVT::v2f64) {
14567     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14568     DCI.AddToWorklist(N.getNode());
14569     // Package {bitcast value, swap's chain} to match Load's shape.
14570     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14571                        N, Swap.getValue(1));
14572   }
14573 
14574   return Swap;
14575 }
14576 
14577 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14578 // builtins) into stores with swaps.
14579 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14580                                                DAGCombinerInfo &DCI) const {
14581   SelectionDAG &DAG = DCI.DAG;
14582   SDLoc dl(N);
14583   SDValue Chain;
14584   SDValue Base;
14585   unsigned SrcOpnd;
14586   MachineMemOperand *MMO;
14587 
14588   switch (N->getOpcode()) {
14589   default:
14590     llvm_unreachable("Unexpected opcode for little endian VSX store");
14591   case ISD::STORE: {
14592     StoreSDNode *ST = cast<StoreSDNode>(N);
14593     Chain = ST->getChain();
14594     Base = ST->getBasePtr();
14595     MMO = ST->getMemOperand();
14596     SrcOpnd = 1;
14597     // If the MMO suggests this isn't a store of a full vector, leave
14598     // things alone.  For a built-in, we have to make the change for
14599     // correctness, so if there is a size problem that will be a bug.
14600     if (MMO->getSize() < 16)
14601       return SDValue();
14602     break;
14603   }
14604   case ISD::INTRINSIC_VOID: {
14605     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14606     Chain = Intrin->getChain();
14607     // Intrin->getBasePtr() oddly does not get what we want.
14608     Base = Intrin->getOperand(3);
14609     MMO = Intrin->getMemOperand();
14610     SrcOpnd = 2;
14611     break;
14612   }
14613   }
14614 
14615   SDValue Src = N->getOperand(SrcOpnd);
14616   MVT VecTy = Src.getValueType().getSimpleVT();
14617 
14618   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14619   // aligned and the type is a vector with elements up to 4 bytes
14620   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14621       VecTy.getScalarSizeInBits() <= 32) {
14622     return SDValue();
14623   }
14624 
14625   // All stores are done as v2f64 and possible bit cast.
14626   if (VecTy != MVT::v2f64) {
14627     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14628     DCI.AddToWorklist(Src.getNode());
14629   }
14630 
14631   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14632                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14633   DCI.AddToWorklist(Swap.getNode());
14634   Chain = Swap.getValue(1);
14635   SDValue StoreOps[] = { Chain, Swap, Base };
14636   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14637                                           DAG.getVTList(MVT::Other),
14638                                           StoreOps, VecTy, MMO);
14639   DCI.AddToWorklist(Store.getNode());
14640   return Store;
14641 }
14642 
14643 // Handle DAG combine for STORE (FP_TO_INT F).
14644 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14645                                                DAGCombinerInfo &DCI) const {
14646 
14647   SelectionDAG &DAG = DCI.DAG;
14648   SDLoc dl(N);
14649   unsigned Opcode = N->getOperand(1).getOpcode();
14650 
14651   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14652          && "Not a FP_TO_INT Instruction!");
14653 
14654   SDValue Val = N->getOperand(1).getOperand(0);
14655   EVT Op1VT = N->getOperand(1).getValueType();
14656   EVT ResVT = Val.getValueType();
14657 
14658   if (!isTypeLegal(ResVT))
14659     return SDValue();
14660 
14661   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14662   bool ValidTypeForStoreFltAsInt =
14663         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14664          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14665 
14666   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14667     return SDValue();
14668 
14669   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14670       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14671     return SDValue();
14672 
14673   // Extend f32 values to f64
14674   if (ResVT.getScalarSizeInBits() == 32) {
14675     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14676     DCI.AddToWorklist(Val.getNode());
14677   }
14678 
14679   // Set signed or unsigned conversion opcode.
14680   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14681                           PPCISD::FP_TO_SINT_IN_VSR :
14682                           PPCISD::FP_TO_UINT_IN_VSR;
14683 
14684   Val = DAG.getNode(ConvOpcode,
14685                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14686   DCI.AddToWorklist(Val.getNode());
14687 
14688   // Set number of bytes being converted.
14689   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14690   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14691                     DAG.getIntPtrConstant(ByteSize, dl, false),
14692                     DAG.getValueType(Op1VT) };
14693 
14694   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14695           DAG.getVTList(MVT::Other), Ops,
14696           cast<StoreSDNode>(N)->getMemoryVT(),
14697           cast<StoreSDNode>(N)->getMemOperand());
14698 
14699   DCI.AddToWorklist(Val.getNode());
14700   return Val;
14701 }
14702 
14703 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14704   // Check that the source of the element keeps flipping
14705   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14706   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14707   for (int i = 1, e = Mask.size(); i < e; i++) {
14708     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14709       return false;
14710     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14711       return false;
14712     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14713   }
14714   return true;
14715 }
14716 
14717 static bool isSplatBV(SDValue Op) {
14718   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14719     return false;
14720   SDValue FirstOp;
14721 
14722   // Find first non-undef input.
14723   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14724     FirstOp = Op.getOperand(i);
14725     if (!FirstOp.isUndef())
14726       break;
14727   }
14728 
14729   // All inputs are undef or the same as the first non-undef input.
14730   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14731     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14732       return false;
14733   return true;
14734 }
14735 
14736 static SDValue isScalarToVec(SDValue Op) {
14737   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14738     return Op;
14739   if (Op.getOpcode() != ISD::BITCAST)
14740     return SDValue();
14741   Op = Op.getOperand(0);
14742   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14743     return Op;
14744   return SDValue();
14745 }
14746 
14747 // Fix up the shuffle mask to account for the fact that the result of
14748 // scalar_to_vector is not in lane zero. This just takes all values in
14749 // the ranges specified by the min/max indices and adds the number of
14750 // elements required to ensure each element comes from the respective
14751 // position in the valid lane.
14752 // On little endian, that's just the corresponding element in the other
14753 // half of the vector. On big endian, it is in the same half but right
14754 // justified rather than left justified in that half.
14755 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14756                                             int LHSMaxIdx, int RHSMinIdx,
14757                                             int RHSMaxIdx, int HalfVec,
14758                                             unsigned ValidLaneWidth,
14759                                             const PPCSubtarget &Subtarget) {
14760   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14761     int Idx = ShuffV[i];
14762     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14763       ShuffV[i] +=
14764           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14765   }
14766 }
14767 
14768 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14769 // the original is:
14770 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14771 // In such a case, just change the shuffle mask to extract the element
14772 // from the permuted index.
14773 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14774                                const PPCSubtarget &Subtarget) {
14775   SDLoc dl(OrigSToV);
14776   EVT VT = OrigSToV.getValueType();
14777   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14778          "Expecting a SCALAR_TO_VECTOR here");
14779   SDValue Input = OrigSToV.getOperand(0);
14780 
14781   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14782     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14783     SDValue OrigVector = Input.getOperand(0);
14784 
14785     // Can't handle non-const element indices or different vector types
14786     // for the input to the extract and the output of the scalar_to_vector.
14787     if (Idx && VT == OrigVector.getValueType()) {
14788       unsigned NumElts = VT.getVectorNumElements();
14789       assert(
14790           NumElts > 1 &&
14791           "Cannot produce a permuted scalar_to_vector for one element vector");
14792       SmallVector<int, 16> NewMask(NumElts, -1);
14793       unsigned ResultInElt = NumElts / 2;
14794       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14795       NewMask[ResultInElt] = Idx->getZExtValue();
14796       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14797     }
14798   }
14799   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14800                      OrigSToV.getOperand(0));
14801 }
14802 
14803 // On little endian subtargets, combine shuffles such as:
14804 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14805 // into:
14806 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14807 // because the latter can be matched to a single instruction merge.
14808 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14809 // to put the value into element zero. Adjust the shuffle mask so that the
14810 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14811 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14812 // nodes with elements smaller than doubleword because all the ways
14813 // of getting scalar data into a vector register put the value in the
14814 // rightmost element of the left half of the vector.
14815 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14816                                                 SelectionDAG &DAG) const {
14817   SDValue LHS = SVN->getOperand(0);
14818   SDValue RHS = SVN->getOperand(1);
14819   auto Mask = SVN->getMask();
14820   int NumElts = LHS.getValueType().getVectorNumElements();
14821   SDValue Res(SVN, 0);
14822   SDLoc dl(SVN);
14823   bool IsLittleEndian = Subtarget.isLittleEndian();
14824 
14825   // On big endian targets this is only useful for subtargets with direct moves.
14826   // On little endian targets it would be useful for all subtargets with VSX.
14827   // However adding special handling for LE subtargets without direct moves
14828   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14829   // which includes direct moves.
14830   if (!Subtarget.hasDirectMove())
14831     return Res;
14832 
14833   // If this is not a shuffle of a shuffle and the first element comes from
14834   // the second vector, canonicalize to the commuted form. This will make it
14835   // more likely to match one of the single instruction patterns.
14836   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14837       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14838     std::swap(LHS, RHS);
14839     Res = DAG.getCommutedVectorShuffle(*SVN);
14840     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14841   }
14842 
14843   // Adjust the shuffle mask if either input vector comes from a
14844   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14845   // form (to prevent the need for a swap).
14846   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14847   SDValue SToVLHS = isScalarToVec(LHS);
14848   SDValue SToVRHS = isScalarToVec(RHS);
14849   if (SToVLHS || SToVRHS) {
14850     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14851                             : SToVRHS.getValueType().getVectorNumElements();
14852     int NumEltsOut = ShuffV.size();
14853     // The width of the "valid lane" (i.e. the lane that contains the value that
14854     // is vectorized) needs to be expressed in terms of the number of elements
14855     // of the shuffle. It is thereby the ratio of the values before and after
14856     // any bitcast.
14857     unsigned ValidLaneWidth =
14858         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14859                       LHS.getValueType().getScalarSizeInBits()
14860                 : SToVRHS.getValueType().getScalarSizeInBits() /
14861                       RHS.getValueType().getScalarSizeInBits();
14862 
14863     // Initially assume that neither input is permuted. These will be adjusted
14864     // accordingly if either input is.
14865     int LHSMaxIdx = -1;
14866     int RHSMinIdx = -1;
14867     int RHSMaxIdx = -1;
14868     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14869 
14870     // Get the permuted scalar to vector nodes for the source(s) that come from
14871     // ISD::SCALAR_TO_VECTOR.
14872     // On big endian systems, this only makes sense for element sizes smaller
14873     // than 64 bits since for 64-bit elements, all instructions already put
14874     // the value into element zero. Since scalar size of LHS and RHS may differ
14875     // after isScalarToVec, this should be checked using their own sizes.
14876     if (SToVLHS) {
14877       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14878         return Res;
14879       // Set up the values for the shuffle vector fixup.
14880       LHSMaxIdx = NumEltsOut / NumEltsIn;
14881       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14882       if (SToVLHS.getValueType() != LHS.getValueType())
14883         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14884       LHS = SToVLHS;
14885     }
14886     if (SToVRHS) {
14887       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14888         return Res;
14889       RHSMinIdx = NumEltsOut;
14890       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14891       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14892       if (SToVRHS.getValueType() != RHS.getValueType())
14893         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14894       RHS = SToVRHS;
14895     }
14896 
14897     // Fix up the shuffle mask to reflect where the desired element actually is.
14898     // The minimum and maximum indices that correspond to element zero for both
14899     // the LHS and RHS are computed and will control which shuffle mask entries
14900     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14901     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14902     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14903                                     HalfVec, ValidLaneWidth, Subtarget);
14904     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14905 
14906     // We may have simplified away the shuffle. We won't be able to do anything
14907     // further with it here.
14908     if (!isa<ShuffleVectorSDNode>(Res))
14909       return Res;
14910     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14911   }
14912 
14913   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14914   // The common case after we commuted the shuffle is that the RHS is a splat
14915   // and we have elements coming in from the splat at indices that are not
14916   // conducive to using a merge.
14917   // Example:
14918   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14919   if (!isSplatBV(TheSplat))
14920     return Res;
14921 
14922   // We are looking for a mask such that all even elements are from
14923   // one vector and all odd elements from the other.
14924   if (!isAlternatingShuffMask(Mask, NumElts))
14925     return Res;
14926 
14927   // Adjust the mask so we are pulling in the same index from the splat
14928   // as the index from the interesting vector in consecutive elements.
14929   if (IsLittleEndian) {
14930     // Example (even elements from first vector):
14931     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14932     if (Mask[0] < NumElts)
14933       for (int i = 1, e = Mask.size(); i < e; i += 2)
14934         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14935     // Example (odd elements from first vector):
14936     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14937     else
14938       for (int i = 0, e = Mask.size(); i < e; i += 2)
14939         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14940   } else {
14941     // Example (even elements from first vector):
14942     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14943     if (Mask[0] < NumElts)
14944       for (int i = 0, e = Mask.size(); i < e; i += 2)
14945         ShuffV[i] = ShuffV[i + 1] - NumElts;
14946     // Example (odd elements from first vector):
14947     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14948     else
14949       for (int i = 1, e = Mask.size(); i < e; i += 2)
14950         ShuffV[i] = ShuffV[i - 1] - NumElts;
14951   }
14952 
14953   // If the RHS has undefs, we need to remove them since we may have created
14954   // a shuffle that adds those instead of the splat value.
14955   SDValue SplatVal =
14956       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14957   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14958 
14959   if (IsLittleEndian)
14960     RHS = TheSplat;
14961   else
14962     LHS = TheSplat;
14963   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14964 }
14965 
14966 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14967                                                 LSBaseSDNode *LSBase,
14968                                                 DAGCombinerInfo &DCI) const {
14969   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14970         "Not a reverse memop pattern!");
14971 
14972   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14973     auto Mask = SVN->getMask();
14974     int i = 0;
14975     auto I = Mask.rbegin();
14976     auto E = Mask.rend();
14977 
14978     for (; I != E; ++I) {
14979       if (*I != i)
14980         return false;
14981       i++;
14982     }
14983     return true;
14984   };
14985 
14986   SelectionDAG &DAG = DCI.DAG;
14987   EVT VT = SVN->getValueType(0);
14988 
14989   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14990     return SDValue();
14991 
14992   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14993   // See comment in PPCVSXSwapRemoval.cpp.
14994   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14995   if (!Subtarget.hasP9Vector())
14996     return SDValue();
14997 
14998   if(!IsElementReverse(SVN))
14999     return SDValue();
15000 
15001   if (LSBase->getOpcode() == ISD::LOAD) {
15002     // If the load return value 0 has more than one user except the
15003     // shufflevector instruction, it is not profitable to replace the
15004     // shufflevector with a reverse load.
15005     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
15006          UI != UE; ++UI)
15007       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
15008         return SDValue();
15009 
15010     SDLoc dl(LSBase);
15011     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
15012     return DAG.getMemIntrinsicNode(
15013         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
15014         LSBase->getMemoryVT(), LSBase->getMemOperand());
15015   }
15016 
15017   if (LSBase->getOpcode() == ISD::STORE) {
15018     // If there are other uses of the shuffle, the swap cannot be avoided.
15019     // Forcing the use of an X-Form (since swapped stores only have
15020     // X-Forms) without removing the swap is unprofitable.
15021     if (!SVN->hasOneUse())
15022       return SDValue();
15023 
15024     SDLoc dl(LSBase);
15025     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
15026                           LSBase->getBasePtr()};
15027     return DAG.getMemIntrinsicNode(
15028         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
15029         LSBase->getMemoryVT(), LSBase->getMemOperand());
15030   }
15031 
15032   llvm_unreachable("Expected a load or store node here");
15033 }
15034 
15035 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
15036                                              DAGCombinerInfo &DCI) const {
15037   SelectionDAG &DAG = DCI.DAG;
15038   SDLoc dl(N);
15039   switch (N->getOpcode()) {
15040   default: break;
15041   case ISD::ADD:
15042     return combineADD(N, DCI);
15043   case ISD::SHL:
15044     return combineSHL(N, DCI);
15045   case ISD::SRA:
15046     return combineSRA(N, DCI);
15047   case ISD::SRL:
15048     return combineSRL(N, DCI);
15049   case ISD::MUL:
15050     return combineMUL(N, DCI);
15051   case ISD::FMA:
15052   case PPCISD::FNMSUB:
15053     return combineFMALike(N, DCI);
15054   case PPCISD::SHL:
15055     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
15056         return N->getOperand(0);
15057     break;
15058   case PPCISD::SRL:
15059     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15060         return N->getOperand(0);
15061     break;
15062   case PPCISD::SRA:
15063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15064       if (C->isZero() ||  //  0 >>s V -> 0.
15065           C->isAllOnes()) // -1 >>s V -> -1.
15066         return N->getOperand(0);
15067     }
15068     break;
15069   case ISD::SIGN_EXTEND:
15070   case ISD::ZERO_EXTEND:
15071   case ISD::ANY_EXTEND:
15072     return DAGCombineExtBoolTrunc(N, DCI);
15073   case ISD::TRUNCATE:
15074     return combineTRUNCATE(N, DCI);
15075   case ISD::SETCC:
15076     if (SDValue CSCC = combineSetCC(N, DCI))
15077       return CSCC;
15078     LLVM_FALLTHROUGH;
15079   case ISD::SELECT_CC:
15080     return DAGCombineTruncBoolExt(N, DCI);
15081   case ISD::SINT_TO_FP:
15082   case ISD::UINT_TO_FP:
15083     return combineFPToIntToFP(N, DCI);
15084   case ISD::VECTOR_SHUFFLE:
15085     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15086       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15087       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15088     }
15089     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15090   case ISD::STORE: {
15091 
15092     EVT Op1VT = N->getOperand(1).getValueType();
15093     unsigned Opcode = N->getOperand(1).getOpcode();
15094 
15095     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15096       SDValue Val= combineStoreFPToInt(N, DCI);
15097       if (Val)
15098         return Val;
15099     }
15100 
15101     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15102       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15103       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15104       if (Val)
15105         return Val;
15106     }
15107 
15108     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15109     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15110         N->getOperand(1).getNode()->hasOneUse() &&
15111         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15112          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15113 
15114       // STBRX can only handle simple types and it makes no sense to store less
15115       // two bytes in byte-reversed order.
15116       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15117       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15118         break;
15119 
15120       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15121       // Do an any-extend to 32-bits if this is a half-word input.
15122       if (BSwapOp.getValueType() == MVT::i16)
15123         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15124 
15125       // If the type of BSWAP operand is wider than stored memory width
15126       // it need to be shifted to the right side before STBRX.
15127       if (Op1VT.bitsGT(mVT)) {
15128         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15129         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15130                               DAG.getConstant(Shift, dl, MVT::i32));
15131         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15132         if (Op1VT == MVT::i64)
15133           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15134       }
15135 
15136       SDValue Ops[] = {
15137         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15138       };
15139       return
15140         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15141                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15142                                 cast<StoreSDNode>(N)->getMemOperand());
15143     }
15144 
15145     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15146     // So it can increase the chance of CSE constant construction.
15147     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15148         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15149       // Need to sign-extended to 64-bits to handle negative values.
15150       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15151       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15152                                     MemVT.getSizeInBits());
15153       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15154 
15155       // DAG.getTruncStore() can't be used here because it doesn't accept
15156       // the general (base + offset) addressing mode.
15157       // So we use UpdateNodeOperands and setTruncatingStore instead.
15158       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15159                              N->getOperand(3));
15160       cast<StoreSDNode>(N)->setTruncatingStore(true);
15161       return SDValue(N, 0);
15162     }
15163 
15164     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15165     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15166     if (Op1VT.isSimple()) {
15167       MVT StoreVT = Op1VT.getSimpleVT();
15168       if (Subtarget.needsSwapsForVSXMemOps() &&
15169           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15170            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15171         return expandVSXStoreForLE(N, DCI);
15172     }
15173     break;
15174   }
15175   case ISD::LOAD: {
15176     LoadSDNode *LD = cast<LoadSDNode>(N);
15177     EVT VT = LD->getValueType(0);
15178 
15179     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15180     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15181     if (VT.isSimple()) {
15182       MVT LoadVT = VT.getSimpleVT();
15183       if (Subtarget.needsSwapsForVSXMemOps() &&
15184           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15185            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15186         return expandVSXLoadForLE(N, DCI);
15187     }
15188 
15189     // We sometimes end up with a 64-bit integer load, from which we extract
15190     // two single-precision floating-point numbers. This happens with
15191     // std::complex<float>, and other similar structures, because of the way we
15192     // canonicalize structure copies. However, if we lack direct moves,
15193     // then the final bitcasts from the extracted integer values to the
15194     // floating-point numbers turn into store/load pairs. Even with direct moves,
15195     // just loading the two floating-point numbers is likely better.
15196     auto ReplaceTwoFloatLoad = [&]() {
15197       if (VT != MVT::i64)
15198         return false;
15199 
15200       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15201           LD->isVolatile())
15202         return false;
15203 
15204       //  We're looking for a sequence like this:
15205       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15206       //      t16: i64 = srl t13, Constant:i32<32>
15207       //    t17: i32 = truncate t16
15208       //  t18: f32 = bitcast t17
15209       //    t19: i32 = truncate t13
15210       //  t20: f32 = bitcast t19
15211 
15212       if (!LD->hasNUsesOfValue(2, 0))
15213         return false;
15214 
15215       auto UI = LD->use_begin();
15216       while (UI.getUse().getResNo() != 0) ++UI;
15217       SDNode *Trunc = *UI++;
15218       while (UI.getUse().getResNo() != 0) ++UI;
15219       SDNode *RightShift = *UI;
15220       if (Trunc->getOpcode() != ISD::TRUNCATE)
15221         std::swap(Trunc, RightShift);
15222 
15223       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15224           Trunc->getValueType(0) != MVT::i32 ||
15225           !Trunc->hasOneUse())
15226         return false;
15227       if (RightShift->getOpcode() != ISD::SRL ||
15228           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15229           RightShift->getConstantOperandVal(1) != 32 ||
15230           !RightShift->hasOneUse())
15231         return false;
15232 
15233       SDNode *Trunc2 = *RightShift->use_begin();
15234       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15235           Trunc2->getValueType(0) != MVT::i32 ||
15236           !Trunc2->hasOneUse())
15237         return false;
15238 
15239       SDNode *Bitcast = *Trunc->use_begin();
15240       SDNode *Bitcast2 = *Trunc2->use_begin();
15241 
15242       if (Bitcast->getOpcode() != ISD::BITCAST ||
15243           Bitcast->getValueType(0) != MVT::f32)
15244         return false;
15245       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15246           Bitcast2->getValueType(0) != MVT::f32)
15247         return false;
15248 
15249       if (Subtarget.isLittleEndian())
15250         std::swap(Bitcast, Bitcast2);
15251 
15252       // Bitcast has the second float (in memory-layout order) and Bitcast2
15253       // has the first one.
15254 
15255       SDValue BasePtr = LD->getBasePtr();
15256       if (LD->isIndexed()) {
15257         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15258                "Non-pre-inc AM on PPC?");
15259         BasePtr =
15260           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15261                       LD->getOffset());
15262       }
15263 
15264       auto MMOFlags =
15265           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15266       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15267                                       LD->getPointerInfo(), LD->getAlignment(),
15268                                       MMOFlags, LD->getAAInfo());
15269       SDValue AddPtr =
15270         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15271                     BasePtr, DAG.getIntPtrConstant(4, dl));
15272       SDValue FloatLoad2 = DAG.getLoad(
15273           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15274           LD->getPointerInfo().getWithOffset(4),
15275           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15276 
15277       if (LD->isIndexed()) {
15278         // Note that DAGCombine should re-form any pre-increment load(s) from
15279         // what is produced here if that makes sense.
15280         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15281       }
15282 
15283       DCI.CombineTo(Bitcast2, FloatLoad);
15284       DCI.CombineTo(Bitcast, FloatLoad2);
15285 
15286       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15287                                     SDValue(FloatLoad2.getNode(), 1));
15288       return true;
15289     };
15290 
15291     if (ReplaceTwoFloatLoad())
15292       return SDValue(N, 0);
15293 
15294     EVT MemVT = LD->getMemoryVT();
15295     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15296     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15297     if (LD->isUnindexed() && VT.isVector() &&
15298         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15299           // P8 and later hardware should just use LOAD.
15300           !Subtarget.hasP8Vector() &&
15301           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15302            VT == MVT::v4f32))) &&
15303         LD->getAlign() < ABIAlignment) {
15304       // This is a type-legal unaligned Altivec load.
15305       SDValue Chain = LD->getChain();
15306       SDValue Ptr = LD->getBasePtr();
15307       bool isLittleEndian = Subtarget.isLittleEndian();
15308 
15309       // This implements the loading of unaligned vectors as described in
15310       // the venerable Apple Velocity Engine overview. Specifically:
15311       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15312       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15313       //
15314       // The general idea is to expand a sequence of one or more unaligned
15315       // loads into an alignment-based permutation-control instruction (lvsl
15316       // or lvsr), a series of regular vector loads (which always truncate
15317       // their input address to an aligned address), and a series of
15318       // permutations.  The results of these permutations are the requested
15319       // loaded values.  The trick is that the last "extra" load is not taken
15320       // from the address you might suspect (sizeof(vector) bytes after the
15321       // last requested load), but rather sizeof(vector) - 1 bytes after the
15322       // last requested vector. The point of this is to avoid a page fault if
15323       // the base address happened to be aligned. This works because if the
15324       // base address is aligned, then adding less than a full vector length
15325       // will cause the last vector in the sequence to be (re)loaded.
15326       // Otherwise, the next vector will be fetched as you might suspect was
15327       // necessary.
15328 
15329       // We might be able to reuse the permutation generation from
15330       // a different base address offset from this one by an aligned amount.
15331       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15332       // optimization later.
15333       Intrinsic::ID Intr, IntrLD, IntrPerm;
15334       MVT PermCntlTy, PermTy, LDTy;
15335       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15336                             : Intrinsic::ppc_altivec_lvsl;
15337       IntrLD = Intrinsic::ppc_altivec_lvx;
15338       IntrPerm = Intrinsic::ppc_altivec_vperm;
15339       PermCntlTy = MVT::v16i8;
15340       PermTy = MVT::v4i32;
15341       LDTy = MVT::v4i32;
15342 
15343       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15344 
15345       // Create the new MMO for the new base load. It is like the original MMO,
15346       // but represents an area in memory almost twice the vector size centered
15347       // on the original address. If the address is unaligned, we might start
15348       // reading up to (sizeof(vector)-1) bytes below the address of the
15349       // original unaligned load.
15350       MachineFunction &MF = DAG.getMachineFunction();
15351       MachineMemOperand *BaseMMO =
15352         MF.getMachineMemOperand(LD->getMemOperand(),
15353                                 -(long)MemVT.getStoreSize()+1,
15354                                 2*MemVT.getStoreSize()-1);
15355 
15356       // Create the new base load.
15357       SDValue LDXIntID =
15358           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15359       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15360       SDValue BaseLoad =
15361         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15362                                 DAG.getVTList(PermTy, MVT::Other),
15363                                 BaseLoadOps, LDTy, BaseMMO);
15364 
15365       // Note that the value of IncOffset (which is provided to the next
15366       // load's pointer info offset value, and thus used to calculate the
15367       // alignment), and the value of IncValue (which is actually used to
15368       // increment the pointer value) are different! This is because we
15369       // require the next load to appear to be aligned, even though it
15370       // is actually offset from the base pointer by a lesser amount.
15371       int IncOffset = VT.getSizeInBits() / 8;
15372       int IncValue = IncOffset;
15373 
15374       // Walk (both up and down) the chain looking for another load at the real
15375       // (aligned) offset (the alignment of the other load does not matter in
15376       // this case). If found, then do not use the offset reduction trick, as
15377       // that will prevent the loads from being later combined (as they would
15378       // otherwise be duplicates).
15379       if (!findConsecutiveLoad(LD, DAG))
15380         --IncValue;
15381 
15382       SDValue Increment =
15383           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15384       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15385 
15386       MachineMemOperand *ExtraMMO =
15387         MF.getMachineMemOperand(LD->getMemOperand(),
15388                                 1, 2*MemVT.getStoreSize()-1);
15389       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15390       SDValue ExtraLoad =
15391         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15392                                 DAG.getVTList(PermTy, MVT::Other),
15393                                 ExtraLoadOps, LDTy, ExtraMMO);
15394 
15395       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15396         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15397 
15398       // Because vperm has a big-endian bias, we must reverse the order
15399       // of the input vectors and complement the permute control vector
15400       // when generating little endian code.  We have already handled the
15401       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15402       // and ExtraLoad here.
15403       SDValue Perm;
15404       if (isLittleEndian)
15405         Perm = BuildIntrinsicOp(IntrPerm,
15406                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15407       else
15408         Perm = BuildIntrinsicOp(IntrPerm,
15409                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15410 
15411       if (VT != PermTy)
15412         Perm = Subtarget.hasAltivec()
15413                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15414                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15415                                  DAG.getTargetConstant(1, dl, MVT::i64));
15416                                // second argument is 1 because this rounding
15417                                // is always exact.
15418 
15419       // The output of the permutation is our loaded result, the TokenFactor is
15420       // our new chain.
15421       DCI.CombineTo(N, Perm, TF);
15422       return SDValue(N, 0);
15423     }
15424     }
15425     break;
15426     case ISD::INTRINSIC_WO_CHAIN: {
15427       bool isLittleEndian = Subtarget.isLittleEndian();
15428       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15429       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15430                                            : Intrinsic::ppc_altivec_lvsl);
15431       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15432         SDValue Add = N->getOperand(1);
15433 
15434         int Bits = 4 /* 16 byte alignment */;
15435 
15436         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15437                                   APInt::getAllOnes(Bits /* alignment */)
15438                                       .zext(Add.getScalarValueSizeInBits()))) {
15439           SDNode *BasePtr = Add->getOperand(0).getNode();
15440           for (SDNode *U : BasePtr->uses()) {
15441             if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15442                 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15443               // We've found another LVSL/LVSR, and this address is an aligned
15444               // multiple of that one. The results will be the same, so use the
15445               // one we've just found instead.
15446 
15447               return SDValue(U, 0);
15448             }
15449           }
15450         }
15451 
15452         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15453           SDNode *BasePtr = Add->getOperand(0).getNode();
15454           for (SDNode *U : BasePtr->uses()) {
15455             if (U->getOpcode() == ISD::ADD &&
15456                 isa<ConstantSDNode>(U->getOperand(1)) &&
15457                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15458                  cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15459                         (1ULL << Bits) ==
15460                     0) {
15461               SDNode *OtherAdd = U;
15462               for (SDNode *V : OtherAdd->uses()) {
15463                 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15464                     cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15465                         IID) {
15466                   return SDValue(V, 0);
15467                 }
15468               }
15469             }
15470           }
15471         }
15472       }
15473 
15474       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15475       // Expose the vabsduw/h/b opportunity for down stream
15476       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15477           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15478            IID == Intrinsic::ppc_altivec_vmaxsh ||
15479            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15480         SDValue V1 = N->getOperand(1);
15481         SDValue V2 = N->getOperand(2);
15482         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15483              V1.getSimpleValueType() == MVT::v8i16 ||
15484              V1.getSimpleValueType() == MVT::v16i8) &&
15485             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15486           // (0-a, a)
15487           if (V1.getOpcode() == ISD::SUB &&
15488               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15489               V1.getOperand(1) == V2) {
15490             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15491           }
15492           // (a, 0-a)
15493           if (V2.getOpcode() == ISD::SUB &&
15494               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15495               V2.getOperand(1) == V1) {
15496             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15497           }
15498           // (x-y, y-x)
15499           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15500               V1.getOperand(0) == V2.getOperand(1) &&
15501               V1.getOperand(1) == V2.getOperand(0)) {
15502             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15503           }
15504         }
15505       }
15506     }
15507 
15508     break;
15509   case ISD::INTRINSIC_W_CHAIN:
15510     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15511     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15512     if (Subtarget.needsSwapsForVSXMemOps()) {
15513       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15514       default:
15515         break;
15516       case Intrinsic::ppc_vsx_lxvw4x:
15517       case Intrinsic::ppc_vsx_lxvd2x:
15518         return expandVSXLoadForLE(N, DCI);
15519       }
15520     }
15521     break;
15522   case ISD::INTRINSIC_VOID:
15523     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15524     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15525     if (Subtarget.needsSwapsForVSXMemOps()) {
15526       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15527       default:
15528         break;
15529       case Intrinsic::ppc_vsx_stxvw4x:
15530       case Intrinsic::ppc_vsx_stxvd2x:
15531         return expandVSXStoreForLE(N, DCI);
15532       }
15533     }
15534     break;
15535   case ISD::BSWAP: {
15536     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15537     // For subtargets without LDBRX, we can still do better than the default
15538     // expansion even for 64-bit BSWAP (LOAD).
15539     bool Is64BitBswapOn64BitTgt =
15540         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15541     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15542                                N->getOperand(0).hasOneUse();
15543     if (IsSingleUseNormalLd &&
15544         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15545          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15546       SDValue Load = N->getOperand(0);
15547       LoadSDNode *LD = cast<LoadSDNode>(Load);
15548       // Create the byte-swapping load.
15549       SDValue Ops[] = {
15550         LD->getChain(),    // Chain
15551         LD->getBasePtr(),  // Ptr
15552         DAG.getValueType(N->getValueType(0)) // VT
15553       };
15554       SDValue BSLoad =
15555         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15556                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15557                                               MVT::i64 : MVT::i32, MVT::Other),
15558                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15559 
15560       // If this is an i16 load, insert the truncate.
15561       SDValue ResVal = BSLoad;
15562       if (N->getValueType(0) == MVT::i16)
15563         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15564 
15565       // First, combine the bswap away.  This makes the value produced by the
15566       // load dead.
15567       DCI.CombineTo(N, ResVal);
15568 
15569       // Next, combine the load away, we give it a bogus result value but a real
15570       // chain result.  The result value is dead because the bswap is dead.
15571       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15572 
15573       // Return N so it doesn't get rechecked!
15574       return SDValue(N, 0);
15575     }
15576     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15577     // before legalization so that the BUILD_PAIR is handled correctly.
15578     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15579         !IsSingleUseNormalLd)
15580       return SDValue();
15581     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15582 
15583     // Can't split volatile or atomic loads.
15584     if (!LD->isSimple())
15585       return SDValue();
15586     SDValue BasePtr = LD->getBasePtr();
15587     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15588                              LD->getPointerInfo(), LD->getAlignment());
15589     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15590     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15591                           DAG.getIntPtrConstant(4, dl));
15592     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15593         LD->getMemOperand(), 4, 4);
15594     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15595     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15596     SDValue Res;
15597     if (Subtarget.isLittleEndian())
15598       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15599     else
15600       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15601     SDValue TF =
15602         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15603                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15604     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15605     return Res;
15606   }
15607   case PPCISD::VCMP:
15608     // If a VCMP_rec node already exists with exactly the same operands as this
15609     // node, use its result instead of this node (VCMP_rec computes both a CR6
15610     // and a normal output).
15611     //
15612     if (!N->getOperand(0).hasOneUse() &&
15613         !N->getOperand(1).hasOneUse() &&
15614         !N->getOperand(2).hasOneUse()) {
15615 
15616       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15617       SDNode *VCMPrecNode = nullptr;
15618 
15619       SDNode *LHSN = N->getOperand(0).getNode();
15620       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15621            UI != E; ++UI)
15622         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15623             UI->getOperand(1) == N->getOperand(1) &&
15624             UI->getOperand(2) == N->getOperand(2) &&
15625             UI->getOperand(0) == N->getOperand(0)) {
15626           VCMPrecNode = *UI;
15627           break;
15628         }
15629 
15630       // If there is no VCMP_rec node, or if the flag value has a single use,
15631       // don't transform this.
15632       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15633         break;
15634 
15635       // Look at the (necessarily single) use of the flag value.  If it has a
15636       // chain, this transformation is more complex.  Note that multiple things
15637       // could use the value result, which we should ignore.
15638       SDNode *FlagUser = nullptr;
15639       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15640            FlagUser == nullptr; ++UI) {
15641         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15642         SDNode *User = *UI;
15643         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15644           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15645             FlagUser = User;
15646             break;
15647           }
15648         }
15649       }
15650 
15651       // If the user is a MFOCRF instruction, we know this is safe.
15652       // Otherwise we give up for right now.
15653       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15654         return SDValue(VCMPrecNode, 0);
15655     }
15656     break;
15657   case ISD::BRCOND: {
15658     SDValue Cond = N->getOperand(1);
15659     SDValue Target = N->getOperand(2);
15660 
15661     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15662         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15663           Intrinsic::loop_decrement) {
15664 
15665       // We now need to make the intrinsic dead (it cannot be instruction
15666       // selected).
15667       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15668       assert(Cond.getNode()->hasOneUse() &&
15669              "Counter decrement has more than one use");
15670 
15671       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15672                          N->getOperand(0), Target);
15673     }
15674   }
15675   break;
15676   case ISD::BR_CC: {
15677     // If this is a branch on an altivec predicate comparison, lower this so
15678     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15679     // lowering is done pre-legalize, because the legalizer lowers the predicate
15680     // compare down to code that is difficult to reassemble.
15681     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15682     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15683 
15684     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15685     // value. If so, pass-through the AND to get to the intrinsic.
15686     if (LHS.getOpcode() == ISD::AND &&
15687         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15688         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15689           Intrinsic::loop_decrement &&
15690         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15691         !isNullConstant(LHS.getOperand(1)))
15692       LHS = LHS.getOperand(0);
15693 
15694     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15695         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15696           Intrinsic::loop_decrement &&
15697         isa<ConstantSDNode>(RHS)) {
15698       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15699              "Counter decrement comparison is not EQ or NE");
15700 
15701       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15702       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15703                     (CC == ISD::SETNE && !Val);
15704 
15705       // We now need to make the intrinsic dead (it cannot be instruction
15706       // selected).
15707       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15708       assert(LHS.getNode()->hasOneUse() &&
15709              "Counter decrement has more than one use");
15710 
15711       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15712                          N->getOperand(0), N->getOperand(4));
15713     }
15714 
15715     int CompareOpc;
15716     bool isDot;
15717 
15718     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15719         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15720         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15721       assert(isDot && "Can't compare against a vector result!");
15722 
15723       // If this is a comparison against something other than 0/1, then we know
15724       // that the condition is never/always true.
15725       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15726       if (Val != 0 && Val != 1) {
15727         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15728           return N->getOperand(0);
15729         // Always !=, turn it into an unconditional branch.
15730         return DAG.getNode(ISD::BR, dl, MVT::Other,
15731                            N->getOperand(0), N->getOperand(4));
15732       }
15733 
15734       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15735 
15736       // Create the PPCISD altivec 'dot' comparison node.
15737       SDValue Ops[] = {
15738         LHS.getOperand(2),  // LHS of compare
15739         LHS.getOperand(3),  // RHS of compare
15740         DAG.getConstant(CompareOpc, dl, MVT::i32)
15741       };
15742       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15743       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15744 
15745       // Unpack the result based on how the target uses it.
15746       PPC::Predicate CompOpc;
15747       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15748       default:  // Can't happen, don't crash on invalid number though.
15749       case 0:   // Branch on the value of the EQ bit of CR6.
15750         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15751         break;
15752       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15753         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15754         break;
15755       case 2:   // Branch on the value of the LT bit of CR6.
15756         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15757         break;
15758       case 3:   // Branch on the inverted value of the LT bit of CR6.
15759         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15760         break;
15761       }
15762 
15763       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15764                          DAG.getConstant(CompOpc, dl, MVT::i32),
15765                          DAG.getRegister(PPC::CR6, MVT::i32),
15766                          N->getOperand(4), CompNode.getValue(1));
15767     }
15768     break;
15769   }
15770   case ISD::BUILD_VECTOR:
15771     return DAGCombineBuildVector(N, DCI);
15772   case ISD::ABS:
15773     return combineABS(N, DCI);
15774   case ISD::VSELECT:
15775     return combineVSelect(N, DCI);
15776   }
15777 
15778   return SDValue();
15779 }
15780 
15781 SDValue
15782 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15783                                  SelectionDAG &DAG,
15784                                  SmallVectorImpl<SDNode *> &Created) const {
15785   // fold (sdiv X, pow2)
15786   EVT VT = N->getValueType(0);
15787   if (VT == MVT::i64 && !Subtarget.isPPC64())
15788     return SDValue();
15789   if ((VT != MVT::i32 && VT != MVT::i64) ||
15790       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15791     return SDValue();
15792 
15793   SDLoc DL(N);
15794   SDValue N0 = N->getOperand(0);
15795 
15796   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15797   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15798   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15799 
15800   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15801   Created.push_back(Op.getNode());
15802 
15803   if (IsNegPow2) {
15804     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15805     Created.push_back(Op.getNode());
15806   }
15807 
15808   return Op;
15809 }
15810 
15811 //===----------------------------------------------------------------------===//
15812 // Inline Assembly Support
15813 //===----------------------------------------------------------------------===//
15814 
15815 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15816                                                       KnownBits &Known,
15817                                                       const APInt &DemandedElts,
15818                                                       const SelectionDAG &DAG,
15819                                                       unsigned Depth) const {
15820   Known.resetAll();
15821   switch (Op.getOpcode()) {
15822   default: break;
15823   case PPCISD::LBRX: {
15824     // lhbrx is known to have the top bits cleared out.
15825     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15826       Known.Zero = 0xFFFF0000;
15827     break;
15828   }
15829   case ISD::INTRINSIC_WO_CHAIN: {
15830     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15831     default: break;
15832     case Intrinsic::ppc_altivec_vcmpbfp_p:
15833     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15834     case Intrinsic::ppc_altivec_vcmpequb_p:
15835     case Intrinsic::ppc_altivec_vcmpequh_p:
15836     case Intrinsic::ppc_altivec_vcmpequw_p:
15837     case Intrinsic::ppc_altivec_vcmpequd_p:
15838     case Intrinsic::ppc_altivec_vcmpequq_p:
15839     case Intrinsic::ppc_altivec_vcmpgefp_p:
15840     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15841     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15842     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15843     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15844     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15845     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15846     case Intrinsic::ppc_altivec_vcmpgtub_p:
15847     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15848     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15849     case Intrinsic::ppc_altivec_vcmpgtud_p:
15850     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15851       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15852       break;
15853     }
15854     break;
15855   }
15856   case ISD::INTRINSIC_W_CHAIN: {
15857     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15858     default:
15859       break;
15860     case Intrinsic::ppc_load2r:
15861       // Top bits are cleared for load2r (which is the same as lhbrx).
15862       Known.Zero = 0xFFFF0000;
15863       break;
15864     }
15865     break;
15866   }
15867   }
15868 }
15869 
15870 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15871   switch (Subtarget.getCPUDirective()) {
15872   default: break;
15873   case PPC::DIR_970:
15874   case PPC::DIR_PWR4:
15875   case PPC::DIR_PWR5:
15876   case PPC::DIR_PWR5X:
15877   case PPC::DIR_PWR6:
15878   case PPC::DIR_PWR6X:
15879   case PPC::DIR_PWR7:
15880   case PPC::DIR_PWR8:
15881   case PPC::DIR_PWR9:
15882   case PPC::DIR_PWR10:
15883   case PPC::DIR_PWR_FUTURE: {
15884     if (!ML)
15885       break;
15886 
15887     if (!DisableInnermostLoopAlign32) {
15888       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15889       // so that we can decrease cache misses and branch-prediction misses.
15890       // Actual alignment of the loop will depend on the hotness check and other
15891       // logic in alignBlocks.
15892       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15893         return Align(32);
15894     }
15895 
15896     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15897 
15898     // For small loops (between 5 and 8 instructions), align to a 32-byte
15899     // boundary so that the entire loop fits in one instruction-cache line.
15900     uint64_t LoopSize = 0;
15901     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15902       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15903         LoopSize += TII->getInstSizeInBytes(*J);
15904         if (LoopSize > 32)
15905           break;
15906       }
15907 
15908     if (LoopSize > 16 && LoopSize <= 32)
15909       return Align(32);
15910 
15911     break;
15912   }
15913   }
15914 
15915   return TargetLowering::getPrefLoopAlignment(ML);
15916 }
15917 
15918 /// getConstraintType - Given a constraint, return the type of
15919 /// constraint it is for this target.
15920 PPCTargetLowering::ConstraintType
15921 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15922   if (Constraint.size() == 1) {
15923     switch (Constraint[0]) {
15924     default: break;
15925     case 'b':
15926     case 'r':
15927     case 'f':
15928     case 'd':
15929     case 'v':
15930     case 'y':
15931       return C_RegisterClass;
15932     case 'Z':
15933       // FIXME: While Z does indicate a memory constraint, it specifically
15934       // indicates an r+r address (used in conjunction with the 'y' modifier
15935       // in the replacement string). Currently, we're forcing the base
15936       // register to be r0 in the asm printer (which is interpreted as zero)
15937       // and forming the complete address in the second register. This is
15938       // suboptimal.
15939       return C_Memory;
15940     }
15941   } else if (Constraint == "wc") { // individual CR bits.
15942     return C_RegisterClass;
15943   } else if (Constraint == "wa" || Constraint == "wd" ||
15944              Constraint == "wf" || Constraint == "ws" ||
15945              Constraint == "wi" || Constraint == "ww") {
15946     return C_RegisterClass; // VSX registers.
15947   }
15948   return TargetLowering::getConstraintType(Constraint);
15949 }
15950 
15951 /// Examine constraint type and operand type and determine a weight value.
15952 /// This object must already have been set up with the operand type
15953 /// and the current alternative constraint selected.
15954 TargetLowering::ConstraintWeight
15955 PPCTargetLowering::getSingleConstraintMatchWeight(
15956     AsmOperandInfo &info, const char *constraint) const {
15957   ConstraintWeight weight = CW_Invalid;
15958   Value *CallOperandVal = info.CallOperandVal;
15959     // If we don't have a value, we can't do a match,
15960     // but allow it at the lowest weight.
15961   if (!CallOperandVal)
15962     return CW_Default;
15963   Type *type = CallOperandVal->getType();
15964 
15965   // Look at the constraint type.
15966   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15967     return CW_Register; // an individual CR bit.
15968   else if ((StringRef(constraint) == "wa" ||
15969             StringRef(constraint) == "wd" ||
15970             StringRef(constraint) == "wf") &&
15971            type->isVectorTy())
15972     return CW_Register;
15973   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15974     return CW_Register; // just hold 64-bit integers data.
15975   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15976     return CW_Register;
15977   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15978     return CW_Register;
15979 
15980   switch (*constraint) {
15981   default:
15982     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15983     break;
15984   case 'b':
15985     if (type->isIntegerTy())
15986       weight = CW_Register;
15987     break;
15988   case 'f':
15989     if (type->isFloatTy())
15990       weight = CW_Register;
15991     break;
15992   case 'd':
15993     if (type->isDoubleTy())
15994       weight = CW_Register;
15995     break;
15996   case 'v':
15997     if (type->isVectorTy())
15998       weight = CW_Register;
15999     break;
16000   case 'y':
16001     weight = CW_Register;
16002     break;
16003   case 'Z':
16004     weight = CW_Memory;
16005     break;
16006   }
16007   return weight;
16008 }
16009 
16010 std::pair<unsigned, const TargetRegisterClass *>
16011 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
16012                                                 StringRef Constraint,
16013                                                 MVT VT) const {
16014   if (Constraint.size() == 1) {
16015     // GCC RS6000 Constraint Letters
16016     switch (Constraint[0]) {
16017     case 'b':   // R1-R31
16018       if (VT == MVT::i64 && Subtarget.isPPC64())
16019         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
16020       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
16021     case 'r':   // R0-R31
16022       if (VT == MVT::i64 && Subtarget.isPPC64())
16023         return std::make_pair(0U, &PPC::G8RCRegClass);
16024       return std::make_pair(0U, &PPC::GPRCRegClass);
16025     // 'd' and 'f' constraints are both defined to be "the floating point
16026     // registers", where one is for 32-bit and the other for 64-bit. We don't
16027     // really care overly much here so just give them all the same reg classes.
16028     case 'd':
16029     case 'f':
16030       if (Subtarget.hasSPE()) {
16031         if (VT == MVT::f32 || VT == MVT::i32)
16032           return std::make_pair(0U, &PPC::GPRCRegClass);
16033         if (VT == MVT::f64 || VT == MVT::i64)
16034           return std::make_pair(0U, &PPC::SPERCRegClass);
16035       } else {
16036         if (VT == MVT::f32 || VT == MVT::i32)
16037           return std::make_pair(0U, &PPC::F4RCRegClass);
16038         if (VT == MVT::f64 || VT == MVT::i64)
16039           return std::make_pair(0U, &PPC::F8RCRegClass);
16040       }
16041       break;
16042     case 'v':
16043       if (Subtarget.hasAltivec() && VT.isVector())
16044         return std::make_pair(0U, &PPC::VRRCRegClass);
16045       else if (Subtarget.hasVSX())
16046         // Scalars in Altivec registers only make sense with VSX.
16047         return std::make_pair(0U, &PPC::VFRCRegClass);
16048       break;
16049     case 'y':   // crrc
16050       return std::make_pair(0U, &PPC::CRRCRegClass);
16051     }
16052   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
16053     // An individual CR bit.
16054     return std::make_pair(0U, &PPC::CRBITRCRegClass);
16055   } else if ((Constraint == "wa" || Constraint == "wd" ||
16056              Constraint == "wf" || Constraint == "wi") &&
16057              Subtarget.hasVSX()) {
16058     // A VSX register for either a scalar (FP) or vector. There is no
16059     // support for single precision scalars on subtargets prior to Power8.
16060     if (VT.isVector())
16061       return std::make_pair(0U, &PPC::VSRCRegClass);
16062     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16063       return std::make_pair(0U, &PPC::VSSRCRegClass);
16064     return std::make_pair(0U, &PPC::VSFRCRegClass);
16065   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16066     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16067       return std::make_pair(0U, &PPC::VSSRCRegClass);
16068     else
16069       return std::make_pair(0U, &PPC::VSFRCRegClass);
16070   } else if (Constraint == "lr") {
16071     if (VT == MVT::i64)
16072       return std::make_pair(0U, &PPC::LR8RCRegClass);
16073     else
16074       return std::make_pair(0U, &PPC::LRRCRegClass);
16075   }
16076 
16077   // Handle special cases of physical registers that are not properly handled
16078   // by the base class.
16079   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16080     // If we name a VSX register, we can't defer to the base class because it
16081     // will not recognize the correct register (their names will be VSL{0-31}
16082     // and V{0-31} so they won't match). So we match them here.
16083     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16084       int VSNum = atoi(Constraint.data() + 3);
16085       assert(VSNum >= 0 && VSNum <= 63 &&
16086              "Attempted to access a vsr out of range");
16087       if (VSNum < 32)
16088         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16089       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16090     }
16091 
16092     // For float registers, we can't defer to the base class as it will match
16093     // the SPILLTOVSRRC class.
16094     if (Constraint.size() > 3 && Constraint[1] == 'f') {
16095       int RegNum = atoi(Constraint.data() + 2);
16096       if (RegNum > 31 || RegNum < 0)
16097         report_fatal_error("Invalid floating point register number");
16098       if (VT == MVT::f32 || VT == MVT::i32)
16099         return Subtarget.hasSPE()
16100                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16101                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16102       if (VT == MVT::f64 || VT == MVT::i64)
16103         return Subtarget.hasSPE()
16104                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16105                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16106     }
16107   }
16108 
16109   std::pair<unsigned, const TargetRegisterClass *> R =
16110       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16111 
16112   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16113   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16114   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16115   // register.
16116   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16117   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16118   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16119       PPC::GPRCRegClass.contains(R.first))
16120     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16121                             PPC::sub_32, &PPC::G8RCRegClass),
16122                           &PPC::G8RCRegClass);
16123 
16124   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16125   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16126     R.first = PPC::CR0;
16127     R.second = &PPC::CRRCRegClass;
16128   }
16129   // FIXME: This warning should ideally be emitted in the front end.
16130   const auto &TM = getTargetMachine();
16131   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16132     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16133          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16134         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16135       errs() << "warning: vector registers 20 to 32 are reserved in the "
16136                 "default AIX AltiVec ABI and cannot be used\n";
16137   }
16138 
16139   return R;
16140 }
16141 
16142 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16143 /// vector.  If it is invalid, don't add anything to Ops.
16144 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16145                                                      std::string &Constraint,
16146                                                      std::vector<SDValue>&Ops,
16147                                                      SelectionDAG &DAG) const {
16148   SDValue Result;
16149 
16150   // Only support length 1 constraints.
16151   if (Constraint.length() > 1) return;
16152 
16153   char Letter = Constraint[0];
16154   switch (Letter) {
16155   default: break;
16156   case 'I':
16157   case 'J':
16158   case 'K':
16159   case 'L':
16160   case 'M':
16161   case 'N':
16162   case 'O':
16163   case 'P': {
16164     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16165     if (!CST) return; // Must be an immediate to match.
16166     SDLoc dl(Op);
16167     int64_t Value = CST->getSExtValue();
16168     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16169                          // numbers are printed as such.
16170     switch (Letter) {
16171     default: llvm_unreachable("Unknown constraint letter!");
16172     case 'I':  // "I" is a signed 16-bit constant.
16173       if (isInt<16>(Value))
16174         Result = DAG.getTargetConstant(Value, dl, TCVT);
16175       break;
16176     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16177       if (isShiftedUInt<16, 16>(Value))
16178         Result = DAG.getTargetConstant(Value, dl, TCVT);
16179       break;
16180     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16181       if (isShiftedInt<16, 16>(Value))
16182         Result = DAG.getTargetConstant(Value, dl, TCVT);
16183       break;
16184     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16185       if (isUInt<16>(Value))
16186         Result = DAG.getTargetConstant(Value, dl, TCVT);
16187       break;
16188     case 'M':  // "M" is a constant that is greater than 31.
16189       if (Value > 31)
16190         Result = DAG.getTargetConstant(Value, dl, TCVT);
16191       break;
16192     case 'N':  // "N" is a positive constant that is an exact power of two.
16193       if (Value > 0 && isPowerOf2_64(Value))
16194         Result = DAG.getTargetConstant(Value, dl, TCVT);
16195       break;
16196     case 'O':  // "O" is the constant zero.
16197       if (Value == 0)
16198         Result = DAG.getTargetConstant(Value, dl, TCVT);
16199       break;
16200     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16201       if (isInt<16>(-Value))
16202         Result = DAG.getTargetConstant(Value, dl, TCVT);
16203       break;
16204     }
16205     break;
16206   }
16207   }
16208 
16209   if (Result.getNode()) {
16210     Ops.push_back(Result);
16211     return;
16212   }
16213 
16214   // Handle standard constraint letters.
16215   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16216 }
16217 
16218 // isLegalAddressingMode - Return true if the addressing mode represented
16219 // by AM is legal for this target, for a load/store of the specified type.
16220 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16221                                               const AddrMode &AM, Type *Ty,
16222                                               unsigned AS,
16223                                               Instruction *I) const {
16224   // Vector type r+i form is supported since power9 as DQ form. We don't check
16225   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16226   // imm form is preferred and the offset can be adjusted to use imm form later
16227   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16228   // max offset to check legal addressing mode, we should be a little aggressive
16229   // to contain other offsets for that LSRUse.
16230   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16231     return false;
16232 
16233   // PPC allows a sign-extended 16-bit immediate field.
16234   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16235     return false;
16236 
16237   // No global is ever allowed as a base.
16238   if (AM.BaseGV)
16239     return false;
16240 
16241   // PPC only support r+r,
16242   switch (AM.Scale) {
16243   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16244     break;
16245   case 1:
16246     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16247       return false;
16248     // Otherwise we have r+r or r+i.
16249     break;
16250   case 2:
16251     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16252       return false;
16253     // Allow 2*r as r+r.
16254     break;
16255   default:
16256     // No other scales are supported.
16257     return false;
16258   }
16259 
16260   return true;
16261 }
16262 
16263 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16264                                            SelectionDAG &DAG) const {
16265   MachineFunction &MF = DAG.getMachineFunction();
16266   MachineFrameInfo &MFI = MF.getFrameInfo();
16267   MFI.setReturnAddressIsTaken(true);
16268 
16269   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16270     return SDValue();
16271 
16272   SDLoc dl(Op);
16273   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16274 
16275   // Make sure the function does not optimize away the store of the RA to
16276   // the stack.
16277   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16278   FuncInfo->setLRStoreRequired();
16279   bool isPPC64 = Subtarget.isPPC64();
16280   auto PtrVT = getPointerTy(MF.getDataLayout());
16281 
16282   if (Depth > 0) {
16283     // The link register (return address) is saved in the caller's frame
16284     // not the callee's stack frame. So we must get the caller's frame
16285     // address and load the return address at the LR offset from there.
16286     SDValue FrameAddr =
16287         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16288                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16289     SDValue Offset =
16290         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16291                         isPPC64 ? MVT::i64 : MVT::i32);
16292     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16293                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16294                        MachinePointerInfo());
16295   }
16296 
16297   // Just load the return address off the stack.
16298   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16299   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16300                      MachinePointerInfo());
16301 }
16302 
16303 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16304                                           SelectionDAG &DAG) const {
16305   SDLoc dl(Op);
16306   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16307 
16308   MachineFunction &MF = DAG.getMachineFunction();
16309   MachineFrameInfo &MFI = MF.getFrameInfo();
16310   MFI.setFrameAddressIsTaken(true);
16311 
16312   EVT PtrVT = getPointerTy(MF.getDataLayout());
16313   bool isPPC64 = PtrVT == MVT::i64;
16314 
16315   // Naked functions never have a frame pointer, and so we use r1. For all
16316   // other functions, this decision must be delayed until during PEI.
16317   unsigned FrameReg;
16318   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16319     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16320   else
16321     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16322 
16323   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16324                                          PtrVT);
16325   while (Depth--)
16326     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16327                             FrameAddr, MachinePointerInfo());
16328   return FrameAddr;
16329 }
16330 
16331 // FIXME? Maybe this could be a TableGen attribute on some registers and
16332 // this table could be generated automatically from RegInfo.
16333 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16334                                               const MachineFunction &MF) const {
16335   bool isPPC64 = Subtarget.isPPC64();
16336 
16337   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16338   if (!is64Bit && VT != LLT::scalar(32))
16339     report_fatal_error("Invalid register global variable type");
16340 
16341   Register Reg = StringSwitch<Register>(RegName)
16342                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16343                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16344                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16345                      .Default(Register());
16346 
16347   if (Reg)
16348     return Reg;
16349   report_fatal_error("Invalid register name global variable");
16350 }
16351 
16352 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16353   // 32-bit SVR4 ABI access everything as got-indirect.
16354   if (Subtarget.is32BitELFABI())
16355     return true;
16356 
16357   // AIX accesses everything indirectly through the TOC, which is similar to
16358   // the GOT.
16359   if (Subtarget.isAIXABI())
16360     return true;
16361 
16362   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16363   // If it is small or large code model, module locals are accessed
16364   // indirectly by loading their address from .toc/.got.
16365   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16366     return true;
16367 
16368   // JumpTable and BlockAddress are accessed as got-indirect.
16369   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16370     return true;
16371 
16372   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16373     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16374 
16375   return false;
16376 }
16377 
16378 bool
16379 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16380   // The PowerPC target isn't yet aware of offsets.
16381   return false;
16382 }
16383 
16384 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16385                                            const CallInst &I,
16386                                            MachineFunction &MF,
16387                                            unsigned Intrinsic) const {
16388   switch (Intrinsic) {
16389   case Intrinsic::ppc_atomicrmw_xchg_i128:
16390   case Intrinsic::ppc_atomicrmw_add_i128:
16391   case Intrinsic::ppc_atomicrmw_sub_i128:
16392   case Intrinsic::ppc_atomicrmw_nand_i128:
16393   case Intrinsic::ppc_atomicrmw_and_i128:
16394   case Intrinsic::ppc_atomicrmw_or_i128:
16395   case Intrinsic::ppc_atomicrmw_xor_i128:
16396   case Intrinsic::ppc_cmpxchg_i128:
16397     Info.opc = ISD::INTRINSIC_W_CHAIN;
16398     Info.memVT = MVT::i128;
16399     Info.ptrVal = I.getArgOperand(0);
16400     Info.offset = 0;
16401     Info.align = Align(16);
16402     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16403                  MachineMemOperand::MOVolatile;
16404     return true;
16405   case Intrinsic::ppc_atomic_load_i128:
16406     Info.opc = ISD::INTRINSIC_W_CHAIN;
16407     Info.memVT = MVT::i128;
16408     Info.ptrVal = I.getArgOperand(0);
16409     Info.offset = 0;
16410     Info.align = Align(16);
16411     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16412     return true;
16413   case Intrinsic::ppc_atomic_store_i128:
16414     Info.opc = ISD::INTRINSIC_VOID;
16415     Info.memVT = MVT::i128;
16416     Info.ptrVal = I.getArgOperand(2);
16417     Info.offset = 0;
16418     Info.align = Align(16);
16419     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16420     return true;
16421   case Intrinsic::ppc_altivec_lvx:
16422   case Intrinsic::ppc_altivec_lvxl:
16423   case Intrinsic::ppc_altivec_lvebx:
16424   case Intrinsic::ppc_altivec_lvehx:
16425   case Intrinsic::ppc_altivec_lvewx:
16426   case Intrinsic::ppc_vsx_lxvd2x:
16427   case Intrinsic::ppc_vsx_lxvw4x:
16428   case Intrinsic::ppc_vsx_lxvd2x_be:
16429   case Intrinsic::ppc_vsx_lxvw4x_be:
16430   case Intrinsic::ppc_vsx_lxvl:
16431   case Intrinsic::ppc_vsx_lxvll: {
16432     EVT VT;
16433     switch (Intrinsic) {
16434     case Intrinsic::ppc_altivec_lvebx:
16435       VT = MVT::i8;
16436       break;
16437     case Intrinsic::ppc_altivec_lvehx:
16438       VT = MVT::i16;
16439       break;
16440     case Intrinsic::ppc_altivec_lvewx:
16441       VT = MVT::i32;
16442       break;
16443     case Intrinsic::ppc_vsx_lxvd2x:
16444     case Intrinsic::ppc_vsx_lxvd2x_be:
16445       VT = MVT::v2f64;
16446       break;
16447     default:
16448       VT = MVT::v4i32;
16449       break;
16450     }
16451 
16452     Info.opc = ISD::INTRINSIC_W_CHAIN;
16453     Info.memVT = VT;
16454     Info.ptrVal = I.getArgOperand(0);
16455     Info.offset = -VT.getStoreSize()+1;
16456     Info.size = 2*VT.getStoreSize()-1;
16457     Info.align = Align(1);
16458     Info.flags = MachineMemOperand::MOLoad;
16459     return true;
16460   }
16461   case Intrinsic::ppc_altivec_stvx:
16462   case Intrinsic::ppc_altivec_stvxl:
16463   case Intrinsic::ppc_altivec_stvebx:
16464   case Intrinsic::ppc_altivec_stvehx:
16465   case Intrinsic::ppc_altivec_stvewx:
16466   case Intrinsic::ppc_vsx_stxvd2x:
16467   case Intrinsic::ppc_vsx_stxvw4x:
16468   case Intrinsic::ppc_vsx_stxvd2x_be:
16469   case Intrinsic::ppc_vsx_stxvw4x_be:
16470   case Intrinsic::ppc_vsx_stxvl:
16471   case Intrinsic::ppc_vsx_stxvll: {
16472     EVT VT;
16473     switch (Intrinsic) {
16474     case Intrinsic::ppc_altivec_stvebx:
16475       VT = MVT::i8;
16476       break;
16477     case Intrinsic::ppc_altivec_stvehx:
16478       VT = MVT::i16;
16479       break;
16480     case Intrinsic::ppc_altivec_stvewx:
16481       VT = MVT::i32;
16482       break;
16483     case Intrinsic::ppc_vsx_stxvd2x:
16484     case Intrinsic::ppc_vsx_stxvd2x_be:
16485       VT = MVT::v2f64;
16486       break;
16487     default:
16488       VT = MVT::v4i32;
16489       break;
16490     }
16491 
16492     Info.opc = ISD::INTRINSIC_VOID;
16493     Info.memVT = VT;
16494     Info.ptrVal = I.getArgOperand(1);
16495     Info.offset = -VT.getStoreSize()+1;
16496     Info.size = 2*VT.getStoreSize()-1;
16497     Info.align = Align(1);
16498     Info.flags = MachineMemOperand::MOStore;
16499     return true;
16500   }
16501   default:
16502     break;
16503   }
16504 
16505   return false;
16506 }
16507 
16508 /// It returns EVT::Other if the type should be determined using generic
16509 /// target-independent logic.
16510 EVT PPCTargetLowering::getOptimalMemOpType(
16511     const MemOp &Op, const AttributeList &FuncAttributes) const {
16512   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16513     // We should use Altivec/VSX loads and stores when available. For unaligned
16514     // addresses, unaligned VSX loads are only fast starting with the P8.
16515     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16516         (Op.isAligned(Align(16)) ||
16517          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16518       return MVT::v4i32;
16519   }
16520 
16521   if (Subtarget.isPPC64()) {
16522     return MVT::i64;
16523   }
16524 
16525   return MVT::i32;
16526 }
16527 
16528 /// Returns true if it is beneficial to convert a load of a constant
16529 /// to just the constant itself.
16530 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16531                                                           Type *Ty) const {
16532   assert(Ty->isIntegerTy());
16533 
16534   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16535   return !(BitSize == 0 || BitSize > 64);
16536 }
16537 
16538 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16539   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16540     return false;
16541   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16542   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16543   return NumBits1 == 64 && NumBits2 == 32;
16544 }
16545 
16546 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16547   if (!VT1.isInteger() || !VT2.isInteger())
16548     return false;
16549   unsigned NumBits1 = VT1.getSizeInBits();
16550   unsigned NumBits2 = VT2.getSizeInBits();
16551   return NumBits1 == 64 && NumBits2 == 32;
16552 }
16553 
16554 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16555   // Generally speaking, zexts are not free, but they are free when they can be
16556   // folded with other operations.
16557   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16558     EVT MemVT = LD->getMemoryVT();
16559     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16560          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16561         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16562          LD->getExtensionType() == ISD::ZEXTLOAD))
16563       return true;
16564   }
16565 
16566   // FIXME: Add other cases...
16567   //  - 32-bit shifts with a zext to i64
16568   //  - zext after ctlz, bswap, etc.
16569   //  - zext after and by a constant mask
16570 
16571   return TargetLowering::isZExtFree(Val, VT2);
16572 }
16573 
16574 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16575   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16576          "invalid fpext types");
16577   // Extending to float128 is not free.
16578   if (DestVT == MVT::f128)
16579     return false;
16580   return true;
16581 }
16582 
16583 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16584   return isInt<16>(Imm) || isUInt<16>(Imm);
16585 }
16586 
16587 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16588   return isInt<16>(Imm) || isUInt<16>(Imm);
16589 }
16590 
16591 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16592                                                        MachineMemOperand::Flags,
16593                                                        bool *Fast) const {
16594   if (DisablePPCUnaligned)
16595     return false;
16596 
16597   // PowerPC supports unaligned memory access for simple non-vector types.
16598   // Although accessing unaligned addresses is not as efficient as accessing
16599   // aligned addresses, it is generally more efficient than manual expansion,
16600   // and generally only traps for software emulation when crossing page
16601   // boundaries.
16602 
16603   if (!VT.isSimple())
16604     return false;
16605 
16606   if (VT.isFloatingPoint() && !VT.isVector() &&
16607       !Subtarget.allowsUnalignedFPAccess())
16608     return false;
16609 
16610   if (VT.getSimpleVT().isVector()) {
16611     if (Subtarget.hasVSX()) {
16612       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16613           VT != MVT::v4f32 && VT != MVT::v4i32)
16614         return false;
16615     } else {
16616       return false;
16617     }
16618   }
16619 
16620   if (VT == MVT::ppcf128)
16621     return false;
16622 
16623   if (Fast)
16624     *Fast = true;
16625 
16626   return true;
16627 }
16628 
16629 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16630                                                SDValue C) const {
16631   // Check integral scalar types.
16632   if (!VT.isScalarInteger())
16633     return false;
16634   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16635     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16636       return false;
16637     // This transformation will generate >= 2 operations. But the following
16638     // cases will generate <= 2 instructions during ISEL. So exclude them.
16639     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16640     // HW instruction, ie. MULLI
16641     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16642     // instruction is needed than case 1, ie. MULLI and RLDICR
16643     int64_t Imm = ConstNode->getSExtValue();
16644     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16645     Imm >>= Shift;
16646     if (isInt<16>(Imm))
16647       return false;
16648     uint64_t UImm = static_cast<uint64_t>(Imm);
16649     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16650         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16651       return true;
16652   }
16653   return false;
16654 }
16655 
16656 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16657                                                    EVT VT) const {
16658   return isFMAFasterThanFMulAndFAdd(
16659       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16660 }
16661 
16662 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16663                                                    Type *Ty) const {
16664   switch (Ty->getScalarType()->getTypeID()) {
16665   case Type::FloatTyID:
16666   case Type::DoubleTyID:
16667     return true;
16668   case Type::FP128TyID:
16669     return Subtarget.hasP9Vector();
16670   default:
16671     return false;
16672   }
16673 }
16674 
16675 // FIXME: add more patterns which are not profitable to hoist.
16676 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16677   if (!I->hasOneUse())
16678     return true;
16679 
16680   Instruction *User = I->user_back();
16681   assert(User && "A single use instruction with no uses.");
16682 
16683   switch (I->getOpcode()) {
16684   case Instruction::FMul: {
16685     // Don't break FMA, PowerPC prefers FMA.
16686     if (User->getOpcode() != Instruction::FSub &&
16687         User->getOpcode() != Instruction::FAdd)
16688       return true;
16689 
16690     const TargetOptions &Options = getTargetMachine().Options;
16691     const Function *F = I->getFunction();
16692     const DataLayout &DL = F->getParent()->getDataLayout();
16693     Type *Ty = User->getOperand(0)->getType();
16694 
16695     return !(
16696         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16697         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16698         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16699   }
16700   case Instruction::Load: {
16701     // Don't break "store (load float*)" pattern, this pattern will be combined
16702     // to "store (load int32)" in later InstCombine pass. See function
16703     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16704     // cycles than loading a 32 bit integer.
16705     LoadInst *LI = cast<LoadInst>(I);
16706     // For the loads that combineLoadToOperationType does nothing, like
16707     // ordered load, it should be profitable to hoist them.
16708     // For swifterror load, it can only be used for pointer to pointer type, so
16709     // later type check should get rid of this case.
16710     if (!LI->isUnordered())
16711       return true;
16712 
16713     if (User->getOpcode() != Instruction::Store)
16714       return true;
16715 
16716     if (I->getType()->getTypeID() != Type::FloatTyID)
16717       return true;
16718 
16719     return false;
16720   }
16721   default:
16722     return true;
16723   }
16724   return true;
16725 }
16726 
16727 const MCPhysReg *
16728 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16729   // LR is a callee-save register, but we must treat it as clobbered by any call
16730   // site. Hence we include LR in the scratch registers, which are in turn added
16731   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16732   // to CTR, which is used by any indirect call.
16733   static const MCPhysReg ScratchRegs[] = {
16734     PPC::X12, PPC::LR8, PPC::CTR8, 0
16735   };
16736 
16737   return ScratchRegs;
16738 }
16739 
16740 Register PPCTargetLowering::getExceptionPointerRegister(
16741     const Constant *PersonalityFn) const {
16742   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16743 }
16744 
16745 Register PPCTargetLowering::getExceptionSelectorRegister(
16746     const Constant *PersonalityFn) const {
16747   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16748 }
16749 
16750 bool
16751 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16752                      EVT VT , unsigned DefinedValues) const {
16753   if (VT == MVT::v2i64)
16754     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16755 
16756   if (Subtarget.hasVSX())
16757     return true;
16758 
16759   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16760 }
16761 
16762 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16763   if (DisableILPPref || Subtarget.enableMachineScheduler())
16764     return TargetLowering::getSchedulingPreference(N);
16765 
16766   return Sched::ILP;
16767 }
16768 
16769 // Create a fast isel object.
16770 FastISel *
16771 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16772                                   const TargetLibraryInfo *LibInfo) const {
16773   return PPC::createFastISel(FuncInfo, LibInfo);
16774 }
16775 
16776 // 'Inverted' means the FMA opcode after negating one multiplicand.
16777 // For example, (fma -a b c) = (fnmsub a b c)
16778 static unsigned invertFMAOpcode(unsigned Opc) {
16779   switch (Opc) {
16780   default:
16781     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16782   case ISD::FMA:
16783     return PPCISD::FNMSUB;
16784   case PPCISD::FNMSUB:
16785     return ISD::FMA;
16786   }
16787 }
16788 
16789 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16790                                                 bool LegalOps, bool OptForSize,
16791                                                 NegatibleCost &Cost,
16792                                                 unsigned Depth) const {
16793   if (Depth > SelectionDAG::MaxRecursionDepth)
16794     return SDValue();
16795 
16796   unsigned Opc = Op.getOpcode();
16797   EVT VT = Op.getValueType();
16798   SDNodeFlags Flags = Op.getNode()->getFlags();
16799 
16800   switch (Opc) {
16801   case PPCISD::FNMSUB:
16802     if (!Op.hasOneUse() || !isTypeLegal(VT))
16803       break;
16804 
16805     const TargetOptions &Options = getTargetMachine().Options;
16806     SDValue N0 = Op.getOperand(0);
16807     SDValue N1 = Op.getOperand(1);
16808     SDValue N2 = Op.getOperand(2);
16809     SDLoc Loc(Op);
16810 
16811     NegatibleCost N2Cost = NegatibleCost::Expensive;
16812     SDValue NegN2 =
16813         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16814 
16815     if (!NegN2)
16816       return SDValue();
16817 
16818     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16819     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16820     // These transformations may change sign of zeroes. For example,
16821     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16822     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16823       // Try and choose the cheaper one to negate.
16824       NegatibleCost N0Cost = NegatibleCost::Expensive;
16825       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16826                                            N0Cost, Depth + 1);
16827 
16828       NegatibleCost N1Cost = NegatibleCost::Expensive;
16829       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16830                                            N1Cost, Depth + 1);
16831 
16832       if (NegN0 && N0Cost <= N1Cost) {
16833         Cost = std::min(N0Cost, N2Cost);
16834         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16835       } else if (NegN1) {
16836         Cost = std::min(N1Cost, N2Cost);
16837         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16838       }
16839     }
16840 
16841     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16842     if (isOperationLegal(ISD::FMA, VT)) {
16843       Cost = N2Cost;
16844       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16845     }
16846 
16847     break;
16848   }
16849 
16850   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16851                                               Cost, Depth);
16852 }
16853 
16854 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16855 bool PPCTargetLowering::useLoadStackGuardNode() const {
16856   if (!Subtarget.isTargetLinux())
16857     return TargetLowering::useLoadStackGuardNode();
16858   return true;
16859 }
16860 
16861 // Override to disable global variable loading on Linux and insert AIX canary
16862 // word declaration.
16863 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16864   if (Subtarget.isAIXABI()) {
16865     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16866                         Type::getInt8PtrTy(M.getContext()));
16867     return;
16868   }
16869   if (!Subtarget.isTargetLinux())
16870     return TargetLowering::insertSSPDeclarations(M);
16871 }
16872 
16873 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16874   if (Subtarget.isAIXABI())
16875     return M.getGlobalVariable(AIXSSPCanaryWordName);
16876   return TargetLowering::getSDagStackGuard(M);
16877 }
16878 
16879 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16880                                      bool ForCodeSize) const {
16881   if (!VT.isSimple() || !Subtarget.hasVSX())
16882     return false;
16883 
16884   switch(VT.getSimpleVT().SimpleTy) {
16885   default:
16886     // For FP types that are currently not supported by PPC backend, return
16887     // false. Examples: f16, f80.
16888     return false;
16889   case MVT::f32:
16890   case MVT::f64:
16891     if (Subtarget.hasPrefixInstrs()) {
16892       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16893       return true;
16894     }
16895     LLVM_FALLTHROUGH;
16896   case MVT::ppcf128:
16897     return Imm.isPosZero();
16898   }
16899 }
16900 
16901 // For vector shift operation op, fold
16902 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16903 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16904                                   SelectionDAG &DAG) {
16905   SDValue N0 = N->getOperand(0);
16906   SDValue N1 = N->getOperand(1);
16907   EVT VT = N0.getValueType();
16908   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16909   unsigned Opcode = N->getOpcode();
16910   unsigned TargetOpcode;
16911 
16912   switch (Opcode) {
16913   default:
16914     llvm_unreachable("Unexpected shift operation");
16915   case ISD::SHL:
16916     TargetOpcode = PPCISD::SHL;
16917     break;
16918   case ISD::SRL:
16919     TargetOpcode = PPCISD::SRL;
16920     break;
16921   case ISD::SRA:
16922     TargetOpcode = PPCISD::SRA;
16923     break;
16924   }
16925 
16926   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16927       N1->getOpcode() == ISD::AND)
16928     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16929       if (Mask->getZExtValue() == OpSizeInBits - 1)
16930         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16931 
16932   return SDValue();
16933 }
16934 
16935 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16936   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16937     return Value;
16938 
16939   SDValue N0 = N->getOperand(0);
16940   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16941   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16942       N0.getOpcode() != ISD::SIGN_EXTEND ||
16943       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16944       N->getValueType(0) != MVT::i64)
16945     return SDValue();
16946 
16947   // We can't save an operation here if the value is already extended, and
16948   // the existing shift is easier to combine.
16949   SDValue ExtsSrc = N0.getOperand(0);
16950   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16951       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16952     return SDValue();
16953 
16954   SDLoc DL(N0);
16955   SDValue ShiftBy = SDValue(CN1, 0);
16956   // We want the shift amount to be i32 on the extswli, but the shift could
16957   // have an i64.
16958   if (ShiftBy.getValueType() == MVT::i64)
16959     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16960 
16961   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16962                          ShiftBy);
16963 }
16964 
16965 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16966   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16967     return Value;
16968 
16969   return SDValue();
16970 }
16971 
16972 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16973   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16974     return Value;
16975 
16976   return SDValue();
16977 }
16978 
16979 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16980 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16981 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16982 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16983 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16984                                  const PPCSubtarget &Subtarget) {
16985   if (!Subtarget.isPPC64())
16986     return SDValue();
16987 
16988   SDValue LHS = N->getOperand(0);
16989   SDValue RHS = N->getOperand(1);
16990 
16991   auto isZextOfCompareWithConstant = [](SDValue Op) {
16992     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16993         Op.getValueType() != MVT::i64)
16994       return false;
16995 
16996     SDValue Cmp = Op.getOperand(0);
16997     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16998         Cmp.getOperand(0).getValueType() != MVT::i64)
16999       return false;
17000 
17001     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
17002       int64_t NegConstant = 0 - Constant->getSExtValue();
17003       // Due to the limitations of the addi instruction,
17004       // -C is required to be [-32768, 32767].
17005       return isInt<16>(NegConstant);
17006     }
17007 
17008     return false;
17009   };
17010 
17011   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
17012   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
17013 
17014   // If there is a pattern, canonicalize a zext operand to the RHS.
17015   if (LHSHasPattern && !RHSHasPattern)
17016     std::swap(LHS, RHS);
17017   else if (!LHSHasPattern && !RHSHasPattern)
17018     return SDValue();
17019 
17020   SDLoc DL(N);
17021   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
17022   SDValue Cmp = RHS.getOperand(0);
17023   SDValue Z = Cmp.getOperand(0);
17024   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
17025   int64_t NegConstant = 0 - Constant->getSExtValue();
17026 
17027   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
17028   default: break;
17029   case ISD::SETNE: {
17030     //                                 when C == 0
17031     //                             --> addze X, (addic Z, -1).carry
17032     //                            /
17033     // add X, (zext(setne Z, C))--
17034     //                            \    when -32768 <= -C <= 32767 && C != 0
17035     //                             --> addze X, (addic (addi Z, -C), -1).carry
17036     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17037                               DAG.getConstant(NegConstant, DL, MVT::i64));
17038     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17039     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17040                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
17041     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17042                        SDValue(Addc.getNode(), 1));
17043     }
17044   case ISD::SETEQ: {
17045     //                                 when C == 0
17046     //                             --> addze X, (subfic Z, 0).carry
17047     //                            /
17048     // add X, (zext(sete  Z, C))--
17049     //                            \    when -32768 <= -C <= 32767 && C != 0
17050     //                             --> addze X, (subfic (addi Z, -C), 0).carry
17051     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17052                               DAG.getConstant(NegConstant, DL, MVT::i64));
17053     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17054     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17055                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
17056     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17057                        SDValue(Subc.getNode(), 1));
17058     }
17059   }
17060 
17061   return SDValue();
17062 }
17063 
17064 // Transform
17065 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17066 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17067 // In this case both C1 and C2 must be known constants.
17068 // C1+C2 must fit into a 34 bit signed integer.
17069 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17070                                           const PPCSubtarget &Subtarget) {
17071   if (!Subtarget.isUsingPCRelativeCalls())
17072     return SDValue();
17073 
17074   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17075   // If we find that node try to cast the Global Address and the Constant.
17076   SDValue LHS = N->getOperand(0);
17077   SDValue RHS = N->getOperand(1);
17078 
17079   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17080     std::swap(LHS, RHS);
17081 
17082   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17083     return SDValue();
17084 
17085   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17086   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17087   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17088 
17089   // Check that both casts succeeded.
17090   if (!GSDN || !ConstNode)
17091     return SDValue();
17092 
17093   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17094   SDLoc DL(GSDN);
17095 
17096   // The signed int offset needs to fit in 34 bits.
17097   if (!isInt<34>(NewOffset))
17098     return SDValue();
17099 
17100   // The new global address is a copy of the old global address except
17101   // that it has the updated Offset.
17102   SDValue GA =
17103       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17104                                  NewOffset, GSDN->getTargetFlags());
17105   SDValue MatPCRel =
17106       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17107   return MatPCRel;
17108 }
17109 
17110 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17111   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17112     return Value;
17113 
17114   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17115     return Value;
17116 
17117   return SDValue();
17118 }
17119 
17120 // Detect TRUNCATE operations on bitcasts of float128 values.
17121 // What we are looking for here is the situtation where we extract a subset
17122 // of bits from a 128 bit float.
17123 // This can be of two forms:
17124 // 1) BITCAST of f128 feeding TRUNCATE
17125 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17126 // The reason this is required is because we do not have a legal i128 type
17127 // and so we want to prevent having to store the f128 and then reload part
17128 // of it.
17129 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17130                                            DAGCombinerInfo &DCI) const {
17131   // If we are using CRBits then try that first.
17132   if (Subtarget.useCRBits()) {
17133     // Check if CRBits did anything and return that if it did.
17134     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17135       return CRTruncValue;
17136   }
17137 
17138   SDLoc dl(N);
17139   SDValue Op0 = N->getOperand(0);
17140 
17141   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17142   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17143     EVT VT = N->getValueType(0);
17144     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17145       return SDValue();
17146     SDValue Sub = Op0.getOperand(0);
17147     if (Sub.getOpcode() == ISD::SUB) {
17148       SDValue SubOp0 = Sub.getOperand(0);
17149       SDValue SubOp1 = Sub.getOperand(1);
17150       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17151           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17152         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17153                                SubOp1.getOperand(0),
17154                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17155       }
17156     }
17157   }
17158 
17159   // Looking for a truncate of i128 to i64.
17160   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17161     return SDValue();
17162 
17163   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17164 
17165   // SRL feeding TRUNCATE.
17166   if (Op0.getOpcode() == ISD::SRL) {
17167     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17168     // The right shift has to be by 64 bits.
17169     if (!ConstNode || ConstNode->getZExtValue() != 64)
17170       return SDValue();
17171 
17172     // Switch the element number to extract.
17173     EltToExtract = EltToExtract ? 0 : 1;
17174     // Update Op0 past the SRL.
17175     Op0 = Op0.getOperand(0);
17176   }
17177 
17178   // BITCAST feeding a TRUNCATE possibly via SRL.
17179   if (Op0.getOpcode() == ISD::BITCAST &&
17180       Op0.getValueType() == MVT::i128 &&
17181       Op0.getOperand(0).getValueType() == MVT::f128) {
17182     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17183     return DCI.DAG.getNode(
17184         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17185         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17186   }
17187   return SDValue();
17188 }
17189 
17190 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17191   SelectionDAG &DAG = DCI.DAG;
17192 
17193   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17194   if (!ConstOpOrElement)
17195     return SDValue();
17196 
17197   // An imul is usually smaller than the alternative sequence for legal type.
17198   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17199       isOperationLegal(ISD::MUL, N->getValueType(0)))
17200     return SDValue();
17201 
17202   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17203     switch (this->Subtarget.getCPUDirective()) {
17204     default:
17205       // TODO: enhance the condition for subtarget before pwr8
17206       return false;
17207     case PPC::DIR_PWR8:
17208       //  type        mul     add    shl
17209       // scalar        4       1      1
17210       // vector        7       2      2
17211       return true;
17212     case PPC::DIR_PWR9:
17213     case PPC::DIR_PWR10:
17214     case PPC::DIR_PWR_FUTURE:
17215       //  type        mul     add    shl
17216       // scalar        5       2      2
17217       // vector        7       2      2
17218 
17219       // The cycle RATIO of related operations are showed as a table above.
17220       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17221       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17222       // are 4, it is always profitable; but for 3 instrs patterns
17223       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17224       // So we should only do it for vector type.
17225       return IsAddOne && IsNeg ? VT.isVector() : true;
17226     }
17227   };
17228 
17229   EVT VT = N->getValueType(0);
17230   SDLoc DL(N);
17231 
17232   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17233   bool IsNeg = MulAmt.isNegative();
17234   APInt MulAmtAbs = MulAmt.abs();
17235 
17236   if ((MulAmtAbs - 1).isPowerOf2()) {
17237     // (mul x, 2^N + 1) => (add (shl x, N), x)
17238     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17239 
17240     if (!IsProfitable(IsNeg, true, VT))
17241       return SDValue();
17242 
17243     SDValue Op0 = N->getOperand(0);
17244     SDValue Op1 =
17245         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17246                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17247     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17248 
17249     if (!IsNeg)
17250       return Res;
17251 
17252     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17253   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17254     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17255     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17256 
17257     if (!IsProfitable(IsNeg, false, VT))
17258       return SDValue();
17259 
17260     SDValue Op0 = N->getOperand(0);
17261     SDValue Op1 =
17262         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17263                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17264 
17265     if (!IsNeg)
17266       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17267     else
17268       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17269 
17270   } else {
17271     return SDValue();
17272   }
17273 }
17274 
17275 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17276 // in combiner since we need to check SD flags and other subtarget features.
17277 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17278                                           DAGCombinerInfo &DCI) const {
17279   SDValue N0 = N->getOperand(0);
17280   SDValue N1 = N->getOperand(1);
17281   SDValue N2 = N->getOperand(2);
17282   SDNodeFlags Flags = N->getFlags();
17283   EVT VT = N->getValueType(0);
17284   SelectionDAG &DAG = DCI.DAG;
17285   const TargetOptions &Options = getTargetMachine().Options;
17286   unsigned Opc = N->getOpcode();
17287   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17288   bool LegalOps = !DCI.isBeforeLegalizeOps();
17289   SDLoc Loc(N);
17290 
17291   if (!isOperationLegal(ISD::FMA, VT))
17292     return SDValue();
17293 
17294   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17295   // since (fnmsub a b c)=-0 while c-ab=+0.
17296   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17297     return SDValue();
17298 
17299   // (fma (fneg a) b c) => (fnmsub a b c)
17300   // (fnmsub (fneg a) b c) => (fma a b c)
17301   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17302     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17303 
17304   // (fma a (fneg b) c) => (fnmsub a b c)
17305   // (fnmsub a (fneg b) c) => (fma a b c)
17306   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17307     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17308 
17309   return SDValue();
17310 }
17311 
17312 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17313   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17314   if (!Subtarget.is64BitELFABI())
17315     return false;
17316 
17317   // If not a tail call then no need to proceed.
17318   if (!CI->isTailCall())
17319     return false;
17320 
17321   // If sibling calls have been disabled and tail-calls aren't guaranteed
17322   // there is no reason to duplicate.
17323   auto &TM = getTargetMachine();
17324   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17325     return false;
17326 
17327   // Can't tail call a function called indirectly, or if it has variadic args.
17328   const Function *Callee = CI->getCalledFunction();
17329   if (!Callee || Callee->isVarArg())
17330     return false;
17331 
17332   // Make sure the callee and caller calling conventions are eligible for tco.
17333   const Function *Caller = CI->getParent()->getParent();
17334   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17335                                            CI->getCallingConv()))
17336       return false;
17337 
17338   // If the function is local then we have a good chance at tail-calling it
17339   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17340 }
17341 
17342 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17343   if (!Subtarget.hasVSX())
17344     return false;
17345   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17346     return true;
17347   return VT == MVT::f32 || VT == MVT::f64 ||
17348     VT == MVT::v4f32 || VT == MVT::v2f64;
17349 }
17350 
17351 bool PPCTargetLowering::
17352 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17353   const Value *Mask = AndI.getOperand(1);
17354   // If the mask is suitable for andi. or andis. we should sink the and.
17355   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17356     // Can't handle constants wider than 64-bits.
17357     if (CI->getBitWidth() > 64)
17358       return false;
17359     int64_t ConstVal = CI->getZExtValue();
17360     return isUInt<16>(ConstVal) ||
17361       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17362   }
17363 
17364   // For non-constant masks, we can always use the record-form and.
17365   return true;
17366 }
17367 
17368 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17369 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17370 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17371 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17372 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17373 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17374   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17375   assert(Subtarget.hasP9Altivec() &&
17376          "Only combine this when P9 altivec supported!");
17377   EVT VT = N->getValueType(0);
17378   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17379     return SDValue();
17380 
17381   SelectionDAG &DAG = DCI.DAG;
17382   SDLoc dl(N);
17383   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17384     // Even for signed integers, if it's known to be positive (as signed
17385     // integer) due to zero-extended inputs.
17386     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17387     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17388     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17389          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17390         (SubOpcd1 == ISD::ZERO_EXTEND ||
17391          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17392       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17393                          N->getOperand(0)->getOperand(0),
17394                          N->getOperand(0)->getOperand(1),
17395                          DAG.getTargetConstant(0, dl, MVT::i32));
17396     }
17397 
17398     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17399     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17400         N->getOperand(0).hasOneUse()) {
17401       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17402                          N->getOperand(0)->getOperand(0),
17403                          N->getOperand(0)->getOperand(1),
17404                          DAG.getTargetConstant(1, dl, MVT::i32));
17405     }
17406   }
17407 
17408   return SDValue();
17409 }
17410 
17411 // For type v4i32/v8ii16/v16i8, transform
17412 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17413 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17414 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17415 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17416 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17417                                           DAGCombinerInfo &DCI) const {
17418   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17419   assert(Subtarget.hasP9Altivec() &&
17420          "Only combine this when P9 altivec supported!");
17421 
17422   SelectionDAG &DAG = DCI.DAG;
17423   SDLoc dl(N);
17424   SDValue Cond = N->getOperand(0);
17425   SDValue TrueOpnd = N->getOperand(1);
17426   SDValue FalseOpnd = N->getOperand(2);
17427   EVT VT = N->getOperand(1).getValueType();
17428 
17429   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17430       FalseOpnd.getOpcode() != ISD::SUB)
17431     return SDValue();
17432 
17433   // ABSD only available for type v4i32/v8i16/v16i8
17434   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17435     return SDValue();
17436 
17437   // At least to save one more dependent computation
17438   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17439     return SDValue();
17440 
17441   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17442 
17443   // Can only handle unsigned comparison here
17444   switch (CC) {
17445   default:
17446     return SDValue();
17447   case ISD::SETUGT:
17448   case ISD::SETUGE:
17449     break;
17450   case ISD::SETULT:
17451   case ISD::SETULE:
17452     std::swap(TrueOpnd, FalseOpnd);
17453     break;
17454   }
17455 
17456   SDValue CmpOpnd1 = Cond.getOperand(0);
17457   SDValue CmpOpnd2 = Cond.getOperand(1);
17458 
17459   // SETCC CmpOpnd1 CmpOpnd2 cond
17460   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17461   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17462   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17463       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17464       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17465       FalseOpnd.getOperand(1) == CmpOpnd1) {
17466     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17467                        CmpOpnd1, CmpOpnd2,
17468                        DAG.getTargetConstant(0, dl, MVT::i32));
17469   }
17470 
17471   return SDValue();
17472 }
17473 
17474 /// getAddrModeForFlags - Based on the set of address flags, select the most
17475 /// optimal instruction format to match by.
17476 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17477   // This is not a node we should be handling here.
17478   if (Flags == PPC::MOF_None)
17479     return PPC::AM_None;
17480   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17481   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17482     if ((Flags & FlagSet) == FlagSet)
17483       return PPC::AM_DForm;
17484   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17485     if ((Flags & FlagSet) == FlagSet)
17486       return PPC::AM_DSForm;
17487   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17488     if ((Flags & FlagSet) == FlagSet)
17489       return PPC::AM_DQForm;
17490   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17491     if ((Flags & FlagSet) == FlagSet)
17492       return PPC::AM_PrefixDForm;
17493   // If no other forms are selected, return an X-Form as it is the most
17494   // general addressing mode.
17495   return PPC::AM_XForm;
17496 }
17497 
17498 /// Set alignment flags based on whether or not the Frame Index is aligned.
17499 /// Utilized when computing flags for address computation when selecting
17500 /// load and store instructions.
17501 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17502                                SelectionDAG &DAG) {
17503   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17504   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17505   if (!FI)
17506     return;
17507   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17508   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17509   // If this is (add $FI, $S16Imm), the alignment flags are already set
17510   // based on the immediate. We just need to clear the alignment flags
17511   // if the FI alignment is weaker.
17512   if ((FrameIndexAlign % 4) != 0)
17513     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17514   if ((FrameIndexAlign % 16) != 0)
17515     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17516   // If the address is a plain FrameIndex, set alignment flags based on
17517   // FI alignment.
17518   if (!IsAdd) {
17519     if ((FrameIndexAlign % 4) == 0)
17520       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17521     if ((FrameIndexAlign % 16) == 0)
17522       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17523   }
17524 }
17525 
17526 /// Given a node, compute flags that are used for address computation when
17527 /// selecting load and store instructions. The flags computed are stored in
17528 /// FlagSet. This function takes into account whether the node is a constant,
17529 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17530 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17531                                               SelectionDAG &DAG) {
17532   // Set the alignment flags for the node depending on if the node is
17533   // 4-byte or 16-byte aligned.
17534   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17535     if ((Imm & 0x3) == 0)
17536       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17537     if ((Imm & 0xf) == 0)
17538       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17539   };
17540 
17541   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17542     // All 32-bit constants can be computed as LIS + Disp.
17543     const APInt &ConstImm = CN->getAPIntValue();
17544     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17545       FlagSet |= PPC::MOF_AddrIsSImm32;
17546       SetAlignFlagsForImm(ConstImm.getZExtValue());
17547       setAlignFlagsForFI(N, FlagSet, DAG);
17548     }
17549     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17550       FlagSet |= PPC::MOF_RPlusSImm34;
17551     else // Let constant materialization handle large constants.
17552       FlagSet |= PPC::MOF_NotAddNorCst;
17553   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17554     // This address can be represented as an addition of:
17555     // - Register + Imm16 (possibly a multiple of 4/16)
17556     // - Register + Imm34
17557     // - Register + PPCISD::Lo
17558     // - Register + Register
17559     // In any case, we won't have to match this as Base + Zero.
17560     SDValue RHS = N.getOperand(1);
17561     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17562       const APInt &ConstImm = CN->getAPIntValue();
17563       if (ConstImm.isSignedIntN(16)) {
17564         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17565         SetAlignFlagsForImm(ConstImm.getZExtValue());
17566         setAlignFlagsForFI(N, FlagSet, DAG);
17567       }
17568       if (ConstImm.isSignedIntN(34))
17569         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17570       else
17571         FlagSet |= PPC::MOF_RPlusR; // Register.
17572     } else if (RHS.getOpcode() == PPCISD::Lo &&
17573                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17574       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17575     else
17576       FlagSet |= PPC::MOF_RPlusR;
17577   } else { // The address computation is not a constant or an addition.
17578     setAlignFlagsForFI(N, FlagSet, DAG);
17579     FlagSet |= PPC::MOF_NotAddNorCst;
17580   }
17581 }
17582 
17583 static bool isPCRelNode(SDValue N) {
17584   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17585       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17586       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17587       isValidPCRelNode<JumpTableSDNode>(N) ||
17588       isValidPCRelNode<BlockAddressSDNode>(N));
17589 }
17590 
17591 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17592 /// the address flags of the load/store instruction that is to be matched.
17593 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17594                                            SelectionDAG &DAG) const {
17595   unsigned FlagSet = PPC::MOF_None;
17596 
17597   // Compute subtarget flags.
17598   if (!Subtarget.hasP9Vector())
17599     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17600   else {
17601     FlagSet |= PPC::MOF_SubtargetP9;
17602     if (Subtarget.hasPrefixInstrs())
17603       FlagSet |= PPC::MOF_SubtargetP10;
17604   }
17605   if (Subtarget.hasSPE())
17606     FlagSet |= PPC::MOF_SubtargetSPE;
17607 
17608   // Check if we have a PCRel node and return early.
17609   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17610     return FlagSet;
17611 
17612   // If the node is the paired load/store intrinsics, compute flags for
17613   // address computation and return early.
17614   unsigned ParentOp = Parent->getOpcode();
17615   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17616                                (ParentOp == ISD::INTRINSIC_VOID))) {
17617     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17618     if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
17619       SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
17620                              ? Parent->getOperand(2)
17621                              : Parent->getOperand(3);
17622       computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17623       FlagSet |= PPC::MOF_Vector;
17624       return FlagSet;
17625     }
17626   }
17627 
17628   // Mark this as something we don't want to handle here if it is atomic
17629   // or pre-increment instruction.
17630   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17631     if (LSB->isIndexed())
17632       return PPC::MOF_None;
17633 
17634   // Compute in-memory type flags. This is based on if there are scalars,
17635   // floats or vectors.
17636   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17637   assert(MN && "Parent should be a MemSDNode!");
17638   EVT MemVT = MN->getMemoryVT();
17639   unsigned Size = MemVT.getSizeInBits();
17640   if (MemVT.isScalarInteger()) {
17641     assert(Size <= 128 &&
17642            "Not expecting scalar integers larger than 16 bytes!");
17643     if (Size < 32)
17644       FlagSet |= PPC::MOF_SubWordInt;
17645     else if (Size == 32)
17646       FlagSet |= PPC::MOF_WordInt;
17647     else
17648       FlagSet |= PPC::MOF_DoubleWordInt;
17649   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17650     if (Size == 128)
17651       FlagSet |= PPC::MOF_Vector;
17652     else if (Size == 256) {
17653       assert(Subtarget.pairedVectorMemops() &&
17654              "256-bit vectors are only available when paired vector memops is "
17655              "enabled!");
17656       FlagSet |= PPC::MOF_Vector;
17657     } else
17658       llvm_unreachable("Not expecting illegal vectors!");
17659   } else { // Floating point type: can be scalar, f128 or vector types.
17660     if (Size == 32 || Size == 64)
17661       FlagSet |= PPC::MOF_ScalarFloat;
17662     else if (MemVT == MVT::f128 || MemVT.isVector())
17663       FlagSet |= PPC::MOF_Vector;
17664     else
17665       llvm_unreachable("Not expecting illegal scalar floats!");
17666   }
17667 
17668   // Compute flags for address computation.
17669   computeFlagsForAddressComputation(N, FlagSet, DAG);
17670 
17671   // Compute type extension flags.
17672   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17673     switch (LN->getExtensionType()) {
17674     case ISD::SEXTLOAD:
17675       FlagSet |= PPC::MOF_SExt;
17676       break;
17677     case ISD::EXTLOAD:
17678     case ISD::ZEXTLOAD:
17679       FlagSet |= PPC::MOF_ZExt;
17680       break;
17681     case ISD::NON_EXTLOAD:
17682       FlagSet |= PPC::MOF_NoExt;
17683       break;
17684     }
17685   } else
17686     FlagSet |= PPC::MOF_NoExt;
17687 
17688   // For integers, no extension is the same as zero extension.
17689   // We set the extension mode to zero extension so we don't have
17690   // to add separate entries in AddrModesMap for loads and stores.
17691   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17692     FlagSet |= PPC::MOF_ZExt;
17693     FlagSet &= ~PPC::MOF_NoExt;
17694   }
17695 
17696   // If we don't have prefixed instructions, 34-bit constants should be
17697   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17698   bool IsNonP1034BitConst =
17699       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17700        FlagSet) == PPC::MOF_RPlusSImm34;
17701   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17702       IsNonP1034BitConst)
17703     FlagSet |= PPC::MOF_NotAddNorCst;
17704 
17705   return FlagSet;
17706 }
17707 
17708 /// SelectForceXFormMode - Given the specified address, force it to be
17709 /// represented as an indexed [r+r] operation (an XForm instruction).
17710 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17711                                                       SDValue &Base,
17712                                                       SelectionDAG &DAG) const {
17713 
17714   PPC::AddrMode Mode = PPC::AM_XForm;
17715   int16_t ForceXFormImm = 0;
17716   if (provablyDisjointOr(DAG, N) &&
17717       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17718     Disp = N.getOperand(0);
17719     Base = N.getOperand(1);
17720     return Mode;
17721   }
17722 
17723   // If the address is the result of an add, we will utilize the fact that the
17724   // address calculation includes an implicit add.  However, we can reduce
17725   // register pressure if we do not materialize a constant just for use as the
17726   // index register.  We only get rid of the add if it is not an add of a
17727   // value and a 16-bit signed constant and both have a single use.
17728   if (N.getOpcode() == ISD::ADD &&
17729       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17730        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17731     Disp = N.getOperand(0);
17732     Base = N.getOperand(1);
17733     return Mode;
17734   }
17735 
17736   // Otherwise, use R0 as the base register.
17737   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17738                          N.getValueType());
17739   Base = N;
17740 
17741   return Mode;
17742 }
17743 
17744 bool PPCTargetLowering::splitValueIntoRegisterParts(
17745     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
17746     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
17747   EVT ValVT = Val.getValueType();
17748   // If we are splitting a scalar integer into f64 parts (i.e. so they
17749   // can be placed into VFRC registers), we need to zero extend and
17750   // bitcast the values. This will ensure the value is placed into a
17751   // VSR using direct moves or stack operations as needed.
17752   if (PartVT == MVT::f64 &&
17753       (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
17754     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
17755     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
17756     Parts[0] = Val;
17757     return true;
17758   }
17759   return false;
17760 }
17761 
17762 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
17763                                           SelectionDAG &DAG) const {
17764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17765   TargetLowering::CallLoweringInfo CLI(DAG);
17766   EVT RetVT = Op.getValueType();
17767   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
17768   SDValue Callee =
17769       DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
17770   bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
17771   TargetLowering::ArgListTy Args;
17772   TargetLowering::ArgListEntry Entry;
17773   for (const SDValue &N : Op->op_values()) {
17774     EVT ArgVT = N.getValueType();
17775     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17776     Entry.Node = N;
17777     Entry.Ty = ArgTy;
17778     Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
17779     Entry.IsZExt = !Entry.IsSExt;
17780     Args.push_back(Entry);
17781   }
17782 
17783   SDValue InChain = DAG.getEntryNode();
17784   SDValue TCChain = InChain;
17785   const Function &F = DAG.getMachineFunction().getFunction();
17786   bool isTailCall =
17787       TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
17788       (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
17789   if (isTailCall)
17790     InChain = TCChain;
17791   CLI.setDebugLoc(SDLoc(Op))
17792       .setChain(InChain)
17793       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
17794       .setTailCall(isTailCall)
17795       .setSExtResult(SignExtend)
17796       .setZExtResult(!SignExtend)
17797       .setIsPostTypeLegalization(true);
17798   return TLI.LowerCallTo(CLI).first;
17799 }
17800 
17801 SDValue PPCTargetLowering::lowerLibCallBasedOnType(
17802     const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
17803     SelectionDAG &DAG) const {
17804   if (Op.getValueType() == MVT::f32)
17805     return lowerToLibCall(LibCallFloatName, Op, DAG);
17806 
17807   if (Op.getValueType() == MVT::f64)
17808     return lowerToLibCall(LibCallDoubleName, Op, DAG);
17809 
17810   return SDValue();
17811 }
17812 
17813 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
17814   SDNodeFlags Flags = Op.getNode()->getFlags();
17815   return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
17816          Flags.hasNoNaNs() && Flags.hasNoInfs();
17817 }
17818 
17819 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
17820   return Op.getNode()->getFlags().hasApproximateFuncs();
17821 }
17822 
17823 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
17824                                             const char *LibCallFloatName,
17825                                             const char *LibCallDoubleNameFinite,
17826                                             const char *LibCallFloatNameFinite,
17827                                             SDValue Op,
17828                                             SelectionDAG &DAG) const {
17829   if (!isLowringToMASSSafe(Op))
17830     return SDValue();
17831 
17832   if (!isLowringToMASSFiniteSafe(Op))
17833     return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
17834                                    DAG);
17835 
17836   return lowerLibCallBasedOnType(LibCallFloatNameFinite,
17837                                  LibCallDoubleNameFinite, Op, DAG);
17838 }
17839 
17840 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
17841   return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
17842                           "__xl_powf_finite", Op, DAG);
17843 }
17844 
17845 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
17846   return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
17847                           "__xl_sinf_finite", Op, DAG);
17848 }
17849 
17850 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
17851   return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
17852                           "__xl_cosf_finite", Op, DAG);
17853 }
17854 
17855 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
17856   return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
17857                           "__xl_logf_finite", Op, DAG);
17858 }
17859 
17860 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
17861   return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
17862                           "__xl_log10f_finite", Op, DAG);
17863 }
17864 
17865 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
17866   return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
17867                           "__xl_expf_finite", Op, DAG);
17868 }
17869 
17870 // If we happen to match to an aligned D-Form, check if the Frame Index is
17871 // adequately aligned. If it is not, reset the mode to match to X-Form.
17872 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17873                                    PPC::AddrMode &Mode) {
17874   if (!isa<FrameIndexSDNode>(N))
17875     return;
17876   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17877       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17878     Mode = PPC::AM_XForm;
17879 }
17880 
17881 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17882 /// compute the address flags of the node, get the optimal address mode based
17883 /// on the flags, and set the Base and Disp based on the address mode.
17884 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17885                                                        SDValue N, SDValue &Disp,
17886                                                        SDValue &Base,
17887                                                        SelectionDAG &DAG,
17888                                                        MaybeAlign Align) const {
17889   SDLoc DL(Parent);
17890 
17891   // Compute the address flags.
17892   unsigned Flags = computeMOFlags(Parent, N, DAG);
17893 
17894   // Get the optimal address mode based on the Flags.
17895   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17896 
17897   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17898   // Select an X-Form load if it is not.
17899   setXFormForUnalignedFI(N, Flags, Mode);
17900 
17901   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17902   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17903     assert(Subtarget.isUsingPCRelativeCalls() &&
17904            "Must be using PC-Relative calls when a valid PC-Relative node is "
17905            "present!");
17906     Mode = PPC::AM_PCRel;
17907   }
17908 
17909   // Set Base and Disp accordingly depending on the address mode.
17910   switch (Mode) {
17911   case PPC::AM_DForm:
17912   case PPC::AM_DSForm:
17913   case PPC::AM_DQForm: {
17914     // This is a register plus a 16-bit immediate. The base will be the
17915     // register and the displacement will be the immediate unless it
17916     // isn't sufficiently aligned.
17917     if (Flags & PPC::MOF_RPlusSImm16) {
17918       SDValue Op0 = N.getOperand(0);
17919       SDValue Op1 = N.getOperand(1);
17920       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17921       if (!Align || isAligned(*Align, Imm)) {
17922         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17923         Base = Op0;
17924         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17925           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17926           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17927         }
17928         break;
17929       }
17930     }
17931     // This is a register plus the @lo relocation. The base is the register
17932     // and the displacement is the global address.
17933     else if (Flags & PPC::MOF_RPlusLo) {
17934       Disp = N.getOperand(1).getOperand(0); // The global address.
17935       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17936              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17937              Disp.getOpcode() == ISD::TargetConstantPool ||
17938              Disp.getOpcode() == ISD::TargetJumpTable);
17939       Base = N.getOperand(0);
17940       break;
17941     }
17942     // This is a constant address at most 32 bits. The base will be
17943     // zero or load-immediate-shifted and the displacement will be
17944     // the low 16 bits of the address.
17945     else if (Flags & PPC::MOF_AddrIsSImm32) {
17946       auto *CN = cast<ConstantSDNode>(N);
17947       EVT CNType = CN->getValueType(0);
17948       uint64_t CNImm = CN->getZExtValue();
17949       // If this address fits entirely in a 16-bit sext immediate field, codegen
17950       // this as "d, 0".
17951       int16_t Imm;
17952       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17953         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17954         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17955                                CNType);
17956         break;
17957       }
17958       // Handle 32-bit sext immediate with LIS + Addr mode.
17959       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17960           (!Align || isAligned(*Align, CNImm))) {
17961         int32_t Addr = (int32_t)CNImm;
17962         // Otherwise, break this down into LIS + Disp.
17963         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17964         Base =
17965             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17966         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17967         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17968         break;
17969       }
17970     }
17971     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17972     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17973     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17974       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17975       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17976     } else
17977       Base = N;
17978     break;
17979   }
17980   case PPC::AM_PrefixDForm: {
17981     int64_t Imm34 = 0;
17982     unsigned Opcode = N.getOpcode();
17983     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17984         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17985       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17986       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17987       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17988         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17989       else
17990         Base = N.getOperand(0);
17991     } else if (isIntS34Immediate(N, Imm34)) {
17992       // The address is a 34-bit signed immediate.
17993       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17994       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
17995     }
17996     break;
17997   }
17998   case PPC::AM_PCRel: {
17999     // When selecting PC-Relative instructions, "Base" is not utilized as
18000     // we select the address as [PC+imm].
18001     Disp = N;
18002     break;
18003   }
18004   case PPC::AM_None:
18005     break;
18006   default: { // By default, X-Form is always available to be selected.
18007     // When a frame index is not aligned, we also match by XForm.
18008     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
18009     Base = FI ? N : N.getOperand(1);
18010     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18011                                 N.getValueType())
18012               : N.getOperand(0);
18013     break;
18014   }
18015   }
18016   return Mode;
18017 }
18018 
18019 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
18020                                                  bool Return,
18021                                                  bool IsVarArg) const {
18022   switch (CC) {
18023   case CallingConv::Cold:
18024     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
18025   default:
18026     return CC_PPC64_ELF_FIS;
18027   }
18028 }
18029 
18030 TargetLowering::AtomicExpansionKind
18031 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18032   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18033   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18034     return AtomicExpansionKind::MaskedIntrinsic;
18035   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
18036 }
18037 
18038 TargetLowering::AtomicExpansionKind
18039 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18040   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
18041   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18042     return AtomicExpansionKind::MaskedIntrinsic;
18043   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
18044 }
18045 
18046 static Intrinsic::ID
18047 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
18048   switch (BinOp) {
18049   default:
18050     llvm_unreachable("Unexpected AtomicRMW BinOp");
18051   case AtomicRMWInst::Xchg:
18052     return Intrinsic::ppc_atomicrmw_xchg_i128;
18053   case AtomicRMWInst::Add:
18054     return Intrinsic::ppc_atomicrmw_add_i128;
18055   case AtomicRMWInst::Sub:
18056     return Intrinsic::ppc_atomicrmw_sub_i128;
18057   case AtomicRMWInst::And:
18058     return Intrinsic::ppc_atomicrmw_and_i128;
18059   case AtomicRMWInst::Or:
18060     return Intrinsic::ppc_atomicrmw_or_i128;
18061   case AtomicRMWInst::Xor:
18062     return Intrinsic::ppc_atomicrmw_xor_i128;
18063   case AtomicRMWInst::Nand:
18064     return Intrinsic::ppc_atomicrmw_nand_i128;
18065   }
18066 }
18067 
18068 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
18069     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
18070     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
18071   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18072          "Only support quadword now");
18073   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18074   Type *ValTy = Incr->getType();
18075   assert(ValTy->getPrimitiveSizeInBits() == 128);
18076   Function *RMW = Intrinsic::getDeclaration(
18077       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
18078   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18079   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
18080   Value *IncrHi =
18081       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
18082   Value *Addr =
18083       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18084   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
18085   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18086   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18087   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18088   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18089   return Builder.CreateOr(
18090       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18091 }
18092 
18093 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
18094     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
18095     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
18096   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18097          "Only support quadword now");
18098   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18099   Type *ValTy = CmpVal->getType();
18100   assert(ValTy->getPrimitiveSizeInBits() == 128);
18101   Function *IntCmpXchg =
18102       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
18103   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18104   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
18105   Value *CmpHi =
18106       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
18107   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
18108   Value *NewHi =
18109       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
18110   Value *Addr =
18111       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18112   emitLeadingFence(Builder, CI, Ord);
18113   Value *LoHi =
18114       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
18115   emitTrailingFence(Builder, CI, Ord);
18116   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18117   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18118   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18119   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18120   return Builder.CreateOr(
18121       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18122 }
18123