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> EnablePPCPCRelTLS(
125     "enable-ppc-pcrel-tls",
126     cl::desc("enable the use of PC relative memops in TLS instructions on PPC"),
127     cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 // FIXME: Remove this once the bug has been fixed!
139 extern cl::opt<bool> ANDIGlueBug;
140 
141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
142                                      const PPCSubtarget &STI)
143     : TargetLowering(TM), Subtarget(STI) {
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   if (Subtarget.isISA3_0()) {
175     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
176     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
177     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
178     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
179   } else {
180     // No extending loads from f16 or HW conversions back and forth.
181     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
184     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
185     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
186     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
187     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
188     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
189   }
190 
191   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
192 
193   // PowerPC has pre-inc load and store's.
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
204   if (!Subtarget.hasSPE()) {
205     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
206     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
207     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
209   }
210 
211   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
212   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
213   for (MVT VT : ScalarIntVTs) {
214     setOperationAction(ISD::ADDC, VT, Legal);
215     setOperationAction(ISD::ADDE, VT, Legal);
216     setOperationAction(ISD::SUBC, VT, Legal);
217     setOperationAction(ISD::SUBE, VT, Legal);
218   }
219 
220   if (Subtarget.useCRBits()) {
221     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
222 
223     if (isPPC64 || Subtarget.hasFPCVT()) {
224       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
226                         isPPC64 ? MVT::i64 : MVT::i32);
227       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
228       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
229                         isPPC64 ? MVT::i64 : MVT::i32);
230 
231       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
232       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
233                          isPPC64 ? MVT::i64 : MVT::i32);
234       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
235       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
236                         isPPC64 ? MVT::i64 : MVT::i32);
237     } else {
238       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
239       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
240       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
241       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
242     }
243 
244     // PowerPC does not support direct load/store of condition registers.
245     setOperationAction(ISD::LOAD, MVT::i1, Custom);
246     setOperationAction(ISD::STORE, MVT::i1, Custom);
247 
248     // FIXME: Remove this once the ANDI glue bug is fixed:
249     if (ANDIGlueBug)
250       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
251 
252     for (MVT VT : MVT::integer_valuetypes()) {
253       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
254       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
255       setTruncStoreAction(VT, MVT::i1, Expand);
256     }
257 
258     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
259   }
260 
261   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
262   // PPC (the libcall is not available).
263   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
264   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
265 
266   // We do not currently implement these libm ops for PowerPC.
267   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
268   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
269   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
270   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
271   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
272   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
273 
274   // PowerPC has no SREM/UREM instructions unless we are on P9
275   // On P9 we may use a hardware instruction to compute the remainder.
276   // When the result of both the remainder and the division is required it is
277   // more efficient to compute the remainder from the result of the division
278   // rather than use the remainder instruction. The instructions are legalized
279   // directly because the DivRemPairsPass performs the transformation at the IR
280   // level.
281   if (Subtarget.isISA3_0()) {
282     setOperationAction(ISD::SREM, MVT::i32, Legal);
283     setOperationAction(ISD::UREM, MVT::i32, Legal);
284     setOperationAction(ISD::SREM, MVT::i64, Legal);
285     setOperationAction(ISD::UREM, MVT::i64, Legal);
286   } else {
287     setOperationAction(ISD::SREM, MVT::i32, Expand);
288     setOperationAction(ISD::UREM, MVT::i32, Expand);
289     setOperationAction(ISD::SREM, MVT::i64, Expand);
290     setOperationAction(ISD::UREM, MVT::i64, Expand);
291   }
292 
293   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
294   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
295   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
296   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
297   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
298   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
299   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
300   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
301   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
302 
303   // Handle constrained floating-point operations of scalar.
304   // TODO: Handle SPE specific operation.
305   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
306   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
307   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
308   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
309   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
310   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
311 
312   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
313   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
314   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
315   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
316   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
317   if (Subtarget.hasVSX())
318     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
319 
320   if (Subtarget.hasFSQRT()) {
321     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
322     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
323   }
324 
325   if (Subtarget.hasFPRND()) {
326     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
327     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
328     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
329     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
330 
331     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
332     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
333     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
334     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
335   }
336 
337   // We don't support sin/cos/sqrt/fmod/pow
338   setOperationAction(ISD::FSIN , MVT::f64, Expand);
339   setOperationAction(ISD::FCOS , MVT::f64, Expand);
340   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
341   setOperationAction(ISD::FREM , MVT::f64, Expand);
342   setOperationAction(ISD::FPOW , MVT::f64, Expand);
343   setOperationAction(ISD::FSIN , MVT::f32, Expand);
344   setOperationAction(ISD::FCOS , MVT::f32, Expand);
345   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
346   setOperationAction(ISD::FREM , MVT::f32, Expand);
347   setOperationAction(ISD::FPOW , MVT::f32, Expand);
348   if (Subtarget.hasSPE()) {
349     setOperationAction(ISD::FMA  , MVT::f64, Expand);
350     setOperationAction(ISD::FMA  , MVT::f32, Expand);
351   } else {
352     setOperationAction(ISD::FMA  , MVT::f64, Legal);
353     setOperationAction(ISD::FMA  , MVT::f32, Legal);
354   }
355 
356   if (Subtarget.hasSPE())
357     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
358 
359   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
360 
361   // If we're enabling GP optimizations, use hardware square root
362   if (!Subtarget.hasFSQRT() &&
363       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
364         Subtarget.hasFRE()))
365     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
366 
367   if (!Subtarget.hasFSQRT() &&
368       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
369         Subtarget.hasFRES()))
370     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
371 
372   if (Subtarget.hasFCPSGN()) {
373     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
374     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
375   } else {
376     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
377     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
378   }
379 
380   if (Subtarget.hasFPRND()) {
381     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
382     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
383     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
384     setOperationAction(ISD::FROUND, MVT::f64, Legal);
385 
386     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
387     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
388     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
389     setOperationAction(ISD::FROUND, MVT::f32, Legal);
390   }
391 
392   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
393   // to speed up scalar BSWAP64.
394   // CTPOP or CTTZ were introduced in P8/P9 respectively
395   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
396   if (Subtarget.hasP9Vector())
397     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
398   else
399     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
400   if (Subtarget.isISA3_0()) {
401     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
402     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
403   } else {
404     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
405     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
406   }
407 
408   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
409     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
410     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
411   } else {
412     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
413     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
414   }
415 
416   // PowerPC does not have ROTR
417   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
418   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
419 
420   if (!Subtarget.useCRBits()) {
421     // PowerPC does not have Select
422     setOperationAction(ISD::SELECT, MVT::i32, Expand);
423     setOperationAction(ISD::SELECT, MVT::i64, Expand);
424     setOperationAction(ISD::SELECT, MVT::f32, Expand);
425     setOperationAction(ISD::SELECT, MVT::f64, Expand);
426   }
427 
428   // PowerPC wants to turn select_cc of FP into fsel when possible.
429   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
430   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
431 
432   // PowerPC wants to optimize integer setcc a bit
433   if (!Subtarget.useCRBits())
434     setOperationAction(ISD::SETCC, MVT::i32, Custom);
435 
436   if (Subtarget.hasFPU()) {
437     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
438     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
439     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
440 
441     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
442     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
443     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
444   }
445 
446   // PowerPC does not have BRCOND which requires SetCC
447   if (!Subtarget.useCRBits())
448     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
449 
450   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
451 
452   if (Subtarget.hasSPE()) {
453     // SPE has built-in conversions
454     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
455     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
456     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
457     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
458     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
459     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
460   } else {
461     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
462     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
463     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
464 
465     // PowerPC does not have [U|S]INT_TO_FP
466     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
467     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
468     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
469     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
470   }
471 
472   if (Subtarget.hasDirectMove() && isPPC64) {
473     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
474     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
475     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
476     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
477     if (TM.Options.UnsafeFPMath) {
478       setOperationAction(ISD::LRINT, MVT::f64, Legal);
479       setOperationAction(ISD::LRINT, MVT::f32, Legal);
480       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
481       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
482       setOperationAction(ISD::LROUND, MVT::f64, Legal);
483       setOperationAction(ISD::LROUND, MVT::f32, Legal);
484       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
485       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
486     }
487   } else {
488     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
489     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
490     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
491     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
492   }
493 
494   // We cannot sextinreg(i1).  Expand to shifts.
495   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
496 
497   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
498   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
499   // support continuation, user-level threading, and etc.. As a result, no
500   // other SjLj exception interfaces are implemented and please don't build
501   // your own exception handling based on them.
502   // LLVM/Clang supports zero-cost DWARF exception handling.
503   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
504   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
505 
506   // We want to legalize GlobalAddress and ConstantPool nodes into the
507   // appropriate instructions to materialize the address.
508   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
509   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
510   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
511   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
512   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
513   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
514   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
515   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
516   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
517   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
518 
519   // TRAP is legal.
520   setOperationAction(ISD::TRAP, MVT::Other, Legal);
521 
522   // TRAMPOLINE is custom lowered.
523   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
524   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
525 
526   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
527   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
528 
529   if (Subtarget.is64BitELFABI()) {
530     // VAARG always uses double-word chunks, so promote anything smaller.
531     setOperationAction(ISD::VAARG, MVT::i1, Promote);
532     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
533     setOperationAction(ISD::VAARG, MVT::i8, Promote);
534     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
535     setOperationAction(ISD::VAARG, MVT::i16, Promote);
536     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
537     setOperationAction(ISD::VAARG, MVT::i32, Promote);
538     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
539     setOperationAction(ISD::VAARG, MVT::Other, Expand);
540   } else if (Subtarget.is32BitELFABI()) {
541     // VAARG is custom lowered with the 32-bit SVR4 ABI.
542     setOperationAction(ISD::VAARG, MVT::Other, Custom);
543     setOperationAction(ISD::VAARG, MVT::i64, Custom);
544   } else
545     setOperationAction(ISD::VAARG, MVT::Other, Expand);
546 
547   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
548   if (Subtarget.is32BitELFABI())
549     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
550   else
551     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
552 
553   // Use the default implementation.
554   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
555   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
556   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
557   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
558   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
559   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
560   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
561   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
562   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
563 
564   // We want to custom lower some of our intrinsics.
565   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
566 
567   // To handle counter-based loop conditions.
568   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
569 
570   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
571   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
572   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
573   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
574 
575   // Comparisons that require checking two conditions.
576   if (Subtarget.hasSPE()) {
577     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
578     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
579     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
580     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
581   }
582   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
583   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
584   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
585   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
586   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
587   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
588   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
589   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
590   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
591   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
592   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
593   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
594 
595   if (Subtarget.has64BitSupport()) {
596     // They also have instructions for converting between i64 and fp.
597     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
598     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
599     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
600     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
601     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
602     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
603     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
604     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
605     // This is just the low 32 bits of a (signed) fp->i64 conversion.
606     // We cannot do this with Promote because i64 is not a legal type.
607     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
608     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
609 
610     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
611       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
612       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
613     }
614   } else {
615     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
616     if (Subtarget.hasSPE()) {
617       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
618       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
619     } else {
620       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
621       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
622     }
623   }
624 
625   // With the instructions enabled under FPCVT, we can do everything.
626   if (Subtarget.hasFPCVT()) {
627     if (Subtarget.has64BitSupport()) {
628       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
629       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
630       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
631       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
632       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
633       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
634       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
635       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
636     }
637 
638     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
639     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
640     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
641     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
645     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
646   }
647 
648   if (Subtarget.use64BitRegs()) {
649     // 64-bit PowerPC implementations can support i64 types directly
650     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
651     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
652     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
653     // 64-bit PowerPC wants to expand i128 shifts itself.
654     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
655     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
656     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
657   } else {
658     // 32-bit PowerPC wants to expand i64 shifts itself.
659     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   }
663 
664   // PowerPC has better expansions for funnel shifts than the generic
665   // TargetLowering::expandFunnelShift.
666   if (Subtarget.has64BitSupport()) {
667     setOperationAction(ISD::FSHL, MVT::i64, Custom);
668     setOperationAction(ISD::FSHR, MVT::i64, Custom);
669   }
670   setOperationAction(ISD::FSHL, MVT::i32, Custom);
671   setOperationAction(ISD::FSHR, MVT::i32, Custom);
672 
673   if (Subtarget.hasVSX()) {
674     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
675     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
676     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
677     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
678   }
679 
680   if (Subtarget.hasAltivec()) {
681     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
682       setOperationAction(ISD::SADDSAT, VT, Legal);
683       setOperationAction(ISD::SSUBSAT, VT, Legal);
684       setOperationAction(ISD::UADDSAT, VT, Legal);
685       setOperationAction(ISD::USUBSAT, VT, Legal);
686     }
687     // First set operation action for all vector types to expand. Then we
688     // will selectively turn on ones that can be effectively codegen'd.
689     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
690       // add/sub are legal for all supported vector VT's.
691       setOperationAction(ISD::ADD, VT, Legal);
692       setOperationAction(ISD::SUB, VT, Legal);
693 
694       // For v2i64, these are only valid with P8Vector. This is corrected after
695       // the loop.
696       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
697         setOperationAction(ISD::SMAX, VT, Legal);
698         setOperationAction(ISD::SMIN, VT, Legal);
699         setOperationAction(ISD::UMAX, VT, Legal);
700         setOperationAction(ISD::UMIN, VT, Legal);
701       }
702       else {
703         setOperationAction(ISD::SMAX, VT, Expand);
704         setOperationAction(ISD::SMIN, VT, Expand);
705         setOperationAction(ISD::UMAX, VT, Expand);
706         setOperationAction(ISD::UMIN, VT, Expand);
707       }
708 
709       if (Subtarget.hasVSX()) {
710         setOperationAction(ISD::FMAXNUM, VT, Legal);
711         setOperationAction(ISD::FMINNUM, VT, Legal);
712       }
713 
714       // Vector instructions introduced in P8
715       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
716         setOperationAction(ISD::CTPOP, VT, Legal);
717         setOperationAction(ISD::CTLZ, VT, Legal);
718       }
719       else {
720         setOperationAction(ISD::CTPOP, VT, Expand);
721         setOperationAction(ISD::CTLZ, VT, Expand);
722       }
723 
724       // Vector instructions introduced in P9
725       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
726         setOperationAction(ISD::CTTZ, VT, Legal);
727       else
728         setOperationAction(ISD::CTTZ, VT, Expand);
729 
730       // We promote all shuffles to v16i8.
731       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
732       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
733 
734       // We promote all non-typed operations to v4i32.
735       setOperationAction(ISD::AND   , VT, Promote);
736       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
737       setOperationAction(ISD::OR    , VT, Promote);
738       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
739       setOperationAction(ISD::XOR   , VT, Promote);
740       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
741       setOperationAction(ISD::LOAD  , VT, Promote);
742       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
743       setOperationAction(ISD::SELECT, VT, Promote);
744       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
745       setOperationAction(ISD::VSELECT, VT, Legal);
746       setOperationAction(ISD::SELECT_CC, VT, Promote);
747       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
748       setOperationAction(ISD::STORE, VT, Promote);
749       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
750 
751       // No other operations are legal.
752       setOperationAction(ISD::MUL , VT, Expand);
753       setOperationAction(ISD::SDIV, VT, Expand);
754       setOperationAction(ISD::SREM, VT, Expand);
755       setOperationAction(ISD::UDIV, VT, Expand);
756       setOperationAction(ISD::UREM, VT, Expand);
757       setOperationAction(ISD::FDIV, VT, Expand);
758       setOperationAction(ISD::FREM, VT, Expand);
759       setOperationAction(ISD::FNEG, VT, Expand);
760       setOperationAction(ISD::FSQRT, VT, Expand);
761       setOperationAction(ISD::FLOG, VT, Expand);
762       setOperationAction(ISD::FLOG10, VT, Expand);
763       setOperationAction(ISD::FLOG2, VT, Expand);
764       setOperationAction(ISD::FEXP, VT, Expand);
765       setOperationAction(ISD::FEXP2, VT, Expand);
766       setOperationAction(ISD::FSIN, VT, Expand);
767       setOperationAction(ISD::FCOS, VT, Expand);
768       setOperationAction(ISD::FABS, VT, Expand);
769       setOperationAction(ISD::FFLOOR, VT, Expand);
770       setOperationAction(ISD::FCEIL,  VT, Expand);
771       setOperationAction(ISD::FTRUNC, VT, Expand);
772       setOperationAction(ISD::FRINT,  VT, Expand);
773       setOperationAction(ISD::FNEARBYINT, VT, Expand);
774       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
775       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
776       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
777       setOperationAction(ISD::MULHU, VT, Expand);
778       setOperationAction(ISD::MULHS, VT, Expand);
779       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
780       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
781       setOperationAction(ISD::UDIVREM, VT, Expand);
782       setOperationAction(ISD::SDIVREM, VT, Expand);
783       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
784       setOperationAction(ISD::FPOW, VT, Expand);
785       setOperationAction(ISD::BSWAP, VT, Expand);
786       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
787       setOperationAction(ISD::ROTL, VT, Expand);
788       setOperationAction(ISD::ROTR, VT, Expand);
789 
790       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
791         setTruncStoreAction(VT, InnerVT, Expand);
792         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
793         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
794         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
795       }
796     }
797     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
798     if (!Subtarget.hasP8Vector()) {
799       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
800       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
801       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
802       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
803     }
804 
805     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
806       setOperationAction(ISD::ABS, VT, Custom);
807 
808     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
809     // with merges, splats, etc.
810     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
811 
812     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
813     // are cheap, so handle them before they get expanded to scalar.
814     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
815     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
816     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
817     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
818     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
819 
820     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
821     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
822     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
823     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
824     setOperationAction(ISD::SELECT, MVT::v4i32,
825                        Subtarget.useCRBits() ? Legal : Expand);
826     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
827     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
828     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
829     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
830     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
831     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
832     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
833     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
834     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
835     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
836     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
837     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
838     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
839 
840     // Without hasP8Altivec set, v2i64 SMAX isn't available.
841     // But ABS custom lowering requires SMAX support.
842     if (!Subtarget.hasP8Altivec())
843       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
844 
845     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
846     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
847     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
848     if (Subtarget.hasAltivec())
849       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
850         setOperationAction(ISD::ROTL, VT, Legal);
851     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
852     if (Subtarget.hasP8Altivec())
853       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
854 
855     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
856     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
857     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
858     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
859 
860     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
861     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
862 
863     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
864       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
865       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
866     }
867 
868     if (Subtarget.hasP8Altivec())
869       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
870     else
871       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
872 
873     if (Subtarget.isISA3_1()) {
874       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
875       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
876       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
877       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
878       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
879       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
880       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
881       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
882       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
883       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
884       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
885       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
886       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
887     }
888 
889     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
890     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
891 
892     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
893     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
894 
895     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
896     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
897     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
898     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
899 
900     // Altivec does not contain unordered floating-point compare instructions
901     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
902     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
903     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
904     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
905 
906     if (Subtarget.hasVSX()) {
907       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
908       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
909       if (Subtarget.hasP8Vector()) {
910         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
911         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
912       }
913       if (Subtarget.hasDirectMove() && isPPC64) {
914         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
915         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
916         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
917         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
918         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
919         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
920         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
921         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
922       }
923       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
924 
925       // The nearbyint variants are not allowed to raise the inexact exception
926       // so we can only code-gen them with unsafe math.
927       if (TM.Options.UnsafeFPMath) {
928         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
929         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
930       }
931 
932       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
933       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
934       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
935       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
936       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
937       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
938       setOperationAction(ISD::FROUND, MVT::f64, Legal);
939       setOperationAction(ISD::FRINT, MVT::f64, Legal);
940 
941       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
942       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
943       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
944       setOperationAction(ISD::FROUND, MVT::f32, Legal);
945       setOperationAction(ISD::FRINT, MVT::f32, Legal);
946 
947       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
948       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
949 
950       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
951       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
952 
953       // Share the Altivec comparison restrictions.
954       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
955       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
956       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
957       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
958 
959       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
960       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
961 
962       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
963 
964       if (Subtarget.hasP8Vector())
965         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
966 
967       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
968 
969       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
970       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
971       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
972 
973       if (Subtarget.hasP8Altivec()) {
974         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
975         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
976         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
977 
978         // 128 bit shifts can be accomplished via 3 instructions for SHL and
979         // SRL, but not for SRA because of the instructions available:
980         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
981         // doing
982         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
983         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
984         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
985 
986         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
987       }
988       else {
989         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
990         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
991         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
992 
993         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
994 
995         // VSX v2i64 only supports non-arithmetic operations.
996         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
997         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
998       }
999 
1000       setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1001 
1002       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1003       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1004       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1005       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1006 
1007       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1008 
1009       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1010       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1011       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1012       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1013       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1014       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1015       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1016       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1017 
1018       // Custom handling for partial vectors of integers converted to
1019       // floating point. We already have optimal handling for v2i32 through
1020       // the DAG combine, so those aren't necessary.
1021       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1022       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1023       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1024       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1025       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1026       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1027       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1028       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1029       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1030       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1031       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1032       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1033       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1034       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1035       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1036       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1037 
1038       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1039       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1040       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1041       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1042       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1043       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1044 
1045       if (Subtarget.hasDirectMove())
1046         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1047       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1048 
1049       // Handle constrained floating-point operations of vector.
1050       // The predictor is `hasVSX` because altivec instruction has
1051       // no exception but VSX vector instruction has.
1052       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1053       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1054       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1055       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1056       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1057       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1058       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1059       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1060       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
1061       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1062       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1063       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1064       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1065 
1066       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1067       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1068       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1069       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1070       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1071       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1072       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1073       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1074       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
1075       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1076       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1077       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1078       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1079 
1080       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1081     }
1082 
1083     if (Subtarget.hasP8Altivec()) {
1084       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1085       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1086     }
1087 
1088     if (Subtarget.hasP9Vector()) {
1089       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1090       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1091 
1092       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1093       // SRL, but not for SRA because of the instructions available:
1094       // VS{RL} and VS{RL}O.
1095       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1096       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1097       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1098 
1099       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1100       setOperationAction(ISD::FADD, MVT::f128, Legal);
1101       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1102       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1103       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1104       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1105       // No extending loads to f128 on PPC.
1106       for (MVT FPT : MVT::fp_valuetypes())
1107         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1108       setOperationAction(ISD::FMA, MVT::f128, Legal);
1109       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1110       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1111       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1112       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1113       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1114       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1115 
1116       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1117       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1118       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1119       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1120       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1121       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1122 
1123       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1124       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1125       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1126       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1127       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1128       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1129       // No implementation for these ops for PowerPC.
1130       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1131       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1132       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1133       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1134       setOperationAction(ISD::FREM, MVT::f128, Expand);
1135 
1136       // Handle constrained floating-point operations of fp128
1137       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1138       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1139       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1140       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1141       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1142       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1143       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1144       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1145       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1146       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1147       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1148       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1149       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1150       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1151       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1152       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1153       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1154       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1155       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1156       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1157     }
1158 
1159     if (Subtarget.hasP9Altivec()) {
1160       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1161       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1162 
1163       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1164       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1165       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1166       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1167       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1168       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1169       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1170     }
1171   }
1172 
1173   if (Subtarget.has64BitSupport())
1174     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1175 
1176   if (Subtarget.isISA3_1())
1177     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1178 
1179   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1180 
1181   if (!isPPC64) {
1182     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1183     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1184   }
1185 
1186   setBooleanContents(ZeroOrOneBooleanContent);
1187 
1188   if (Subtarget.hasAltivec()) {
1189     // Altivec instructions set fields to all zeros or all ones.
1190     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1191   }
1192 
1193   if (!isPPC64) {
1194     // These libcalls are not available in 32-bit.
1195     setLibcallName(RTLIB::SHL_I128, nullptr);
1196     setLibcallName(RTLIB::SRL_I128, nullptr);
1197     setLibcallName(RTLIB::SRA_I128, nullptr);
1198   }
1199 
1200   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1201 
1202   // We have target-specific dag combine patterns for the following nodes:
1203   setTargetDAGCombine(ISD::ADD);
1204   setTargetDAGCombine(ISD::SHL);
1205   setTargetDAGCombine(ISD::SRA);
1206   setTargetDAGCombine(ISD::SRL);
1207   setTargetDAGCombine(ISD::MUL);
1208   setTargetDAGCombine(ISD::FMA);
1209   setTargetDAGCombine(ISD::SINT_TO_FP);
1210   setTargetDAGCombine(ISD::BUILD_VECTOR);
1211   if (Subtarget.hasFPCVT())
1212     setTargetDAGCombine(ISD::UINT_TO_FP);
1213   setTargetDAGCombine(ISD::LOAD);
1214   setTargetDAGCombine(ISD::STORE);
1215   setTargetDAGCombine(ISD::BR_CC);
1216   if (Subtarget.useCRBits())
1217     setTargetDAGCombine(ISD::BRCOND);
1218   setTargetDAGCombine(ISD::BSWAP);
1219   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1220   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1221   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1222 
1223   setTargetDAGCombine(ISD::SIGN_EXTEND);
1224   setTargetDAGCombine(ISD::ZERO_EXTEND);
1225   setTargetDAGCombine(ISD::ANY_EXTEND);
1226 
1227   setTargetDAGCombine(ISD::TRUNCATE);
1228   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1229 
1230 
1231   if (Subtarget.useCRBits()) {
1232     setTargetDAGCombine(ISD::TRUNCATE);
1233     setTargetDAGCombine(ISD::SETCC);
1234     setTargetDAGCombine(ISD::SELECT_CC);
1235   }
1236 
1237   // Use reciprocal estimates.
1238   if (TM.Options.UnsafeFPMath) {
1239     setTargetDAGCombine(ISD::FDIV);
1240     setTargetDAGCombine(ISD::FSQRT);
1241   }
1242 
1243   if (Subtarget.hasP9Altivec()) {
1244     setTargetDAGCombine(ISD::ABS);
1245     setTargetDAGCombine(ISD::VSELECT);
1246   }
1247 
1248   setLibcallName(RTLIB::LOG_F128, "logf128");
1249   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1250   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1251   setLibcallName(RTLIB::EXP_F128, "expf128");
1252   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1253   setLibcallName(RTLIB::SIN_F128, "sinf128");
1254   setLibcallName(RTLIB::COS_F128, "cosf128");
1255   setLibcallName(RTLIB::POW_F128, "powf128");
1256   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1257   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1258   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1259   setLibcallName(RTLIB::REM_F128, "fmodf128");
1260 
1261   // With 32 condition bits, we don't need to sink (and duplicate) compares
1262   // aggressively in CodeGenPrep.
1263   if (Subtarget.useCRBits()) {
1264     setHasMultipleConditionRegisters();
1265     setJumpIsExpensive();
1266   }
1267 
1268   setMinFunctionAlignment(Align(4));
1269 
1270   switch (Subtarget.getCPUDirective()) {
1271   default: break;
1272   case PPC::DIR_970:
1273   case PPC::DIR_A2:
1274   case PPC::DIR_E500:
1275   case PPC::DIR_E500mc:
1276   case PPC::DIR_E5500:
1277   case PPC::DIR_PWR4:
1278   case PPC::DIR_PWR5:
1279   case PPC::DIR_PWR5X:
1280   case PPC::DIR_PWR6:
1281   case PPC::DIR_PWR6X:
1282   case PPC::DIR_PWR7:
1283   case PPC::DIR_PWR8:
1284   case PPC::DIR_PWR9:
1285   case PPC::DIR_PWR10:
1286   case PPC::DIR_PWR_FUTURE:
1287     setPrefLoopAlignment(Align(16));
1288     setPrefFunctionAlignment(Align(16));
1289     break;
1290   }
1291 
1292   if (Subtarget.enableMachineScheduler())
1293     setSchedulingPreference(Sched::Source);
1294   else
1295     setSchedulingPreference(Sched::Hybrid);
1296 
1297   computeRegisterProperties(STI.getRegisterInfo());
1298 
1299   // The Freescale cores do better with aggressive inlining of memcpy and
1300   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1301   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1302       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1303     MaxStoresPerMemset = 32;
1304     MaxStoresPerMemsetOptSize = 16;
1305     MaxStoresPerMemcpy = 32;
1306     MaxStoresPerMemcpyOptSize = 8;
1307     MaxStoresPerMemmove = 32;
1308     MaxStoresPerMemmoveOptSize = 8;
1309   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1310     // The A2 also benefits from (very) aggressive inlining of memcpy and
1311     // friends. The overhead of a the function call, even when warm, can be
1312     // over one hundred cycles.
1313     MaxStoresPerMemset = 128;
1314     MaxStoresPerMemcpy = 128;
1315     MaxStoresPerMemmove = 128;
1316     MaxLoadsPerMemcmp = 128;
1317   } else {
1318     MaxLoadsPerMemcmp = 8;
1319     MaxLoadsPerMemcmpOptSize = 4;
1320   }
1321 
1322   // Let the subtarget (CPU) decide if a predictable select is more expensive
1323   // than the corresponding branch. This information is used in CGP to decide
1324   // when to convert selects into branches.
1325   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1326 }
1327 
1328 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1329 /// the desired ByVal argument alignment.
1330 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1331   if (MaxAlign == MaxMaxAlign)
1332     return;
1333   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1334     if (MaxMaxAlign >= 32 &&
1335         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1336       MaxAlign = Align(32);
1337     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1338              MaxAlign < 16)
1339       MaxAlign = Align(16);
1340   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1341     Align EltAlign;
1342     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1343     if (EltAlign > MaxAlign)
1344       MaxAlign = EltAlign;
1345   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1346     for (auto *EltTy : STy->elements()) {
1347       Align EltAlign;
1348       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1349       if (EltAlign > MaxAlign)
1350         MaxAlign = EltAlign;
1351       if (MaxAlign == MaxMaxAlign)
1352         break;
1353     }
1354   }
1355 }
1356 
1357 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1358 /// function arguments in the caller parameter area.
1359 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1360                                                   const DataLayout &DL) const {
1361   // 16byte and wider vectors are passed on 16byte boundary.
1362   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1363   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1364   if (Subtarget.hasAltivec())
1365     getMaxByValAlign(Ty, Alignment, Align(16));
1366   return Alignment.value();
1367 }
1368 
1369 bool PPCTargetLowering::useSoftFloat() const {
1370   return Subtarget.useSoftFloat();
1371 }
1372 
1373 bool PPCTargetLowering::hasSPE() const {
1374   return Subtarget.hasSPE();
1375 }
1376 
1377 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1378   return VT.isScalarInteger();
1379 }
1380 
1381 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1382 /// type is cheaper than a multiply followed by a shift.
1383 /// This is true for words and doublewords on 64-bit PowerPC.
1384 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1385   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1386                               isOperationLegal(ISD::MULHU, Type)))
1387     return true;
1388   return TargetLowering::isMulhCheaperThanMulShift(Type);
1389 }
1390 
1391 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1392   switch ((PPCISD::NodeType)Opcode) {
1393   case PPCISD::FIRST_NUMBER:    break;
1394   case PPCISD::FSEL:            return "PPCISD::FSEL";
1395   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1396   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1397   case PPCISD::FCFID:           return "PPCISD::FCFID";
1398   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1399   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1400   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1401   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1402   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1403   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1404   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1405   case PPCISD::FP_TO_UINT_IN_VSR:
1406                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1407   case PPCISD::FP_TO_SINT_IN_VSR:
1408                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1409   case PPCISD::FRE:             return "PPCISD::FRE";
1410   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1411   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1412   case PPCISD::VPERM:           return "PPCISD::VPERM";
1413   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1414   case PPCISD::XXSPLTI_SP_TO_DP:
1415     return "PPCISD::XXSPLTI_SP_TO_DP";
1416   case PPCISD::XXSPLTI32DX:
1417     return "PPCISD::XXSPLTI32DX";
1418   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1419   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1420   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1421   case PPCISD::CMPB:            return "PPCISD::CMPB";
1422   case PPCISD::Hi:              return "PPCISD::Hi";
1423   case PPCISD::Lo:              return "PPCISD::Lo";
1424   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1425   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1426   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1427   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1428   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1429   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1430   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1431   case PPCISD::SRL:             return "PPCISD::SRL";
1432   case PPCISD::SRA:             return "PPCISD::SRA";
1433   case PPCISD::SHL:             return "PPCISD::SHL";
1434   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1435   case PPCISD::CALL:            return "PPCISD::CALL";
1436   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1437   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1438   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1439   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1440   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1441   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1442   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1443   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1444   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1445   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1446   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1447   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1448   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1449   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1450   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1451   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1452     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1453   case PPCISD::ANDI_rec_1_EQ_BIT:
1454     return "PPCISD::ANDI_rec_1_EQ_BIT";
1455   case PPCISD::ANDI_rec_1_GT_BIT:
1456     return "PPCISD::ANDI_rec_1_GT_BIT";
1457   case PPCISD::VCMP:            return "PPCISD::VCMP";
1458   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1459   case PPCISD::LBRX:            return "PPCISD::LBRX";
1460   case PPCISD::STBRX:           return "PPCISD::STBRX";
1461   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1462   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1463   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1464   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1465   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1466   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1467   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1468   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1469   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1470   case PPCISD::ST_VSR_SCAL_INT:
1471                                 return "PPCISD::ST_VSR_SCAL_INT";
1472   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1473   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1474   case PPCISD::BDZ:             return "PPCISD::BDZ";
1475   case PPCISD::MFFS:            return "PPCISD::MFFS";
1476   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1477   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1478   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1479   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1480   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1481   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1482   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1483   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1484   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1485   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1486   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1487   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1488   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1489   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1490   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1491   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1492   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1493   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1494   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1495   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1496   case PPCISD::SC:              return "PPCISD::SC";
1497   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1498   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1499   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1500   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1501   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1502   case PPCISD::VABSD:           return "PPCISD::VABSD";
1503   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1504   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1505   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1506   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1507   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1508   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1509   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1510   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1511     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1512   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1513   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1514   case PPCISD::STRICT_FCTIDZ:
1515     return "PPCISD::STRICT_FCTIDZ";
1516   case PPCISD::STRICT_FCTIWZ:
1517     return "PPCISD::STRICT_FCTIWZ";
1518   case PPCISD::STRICT_FCTIDUZ:
1519     return "PPCISD::STRICT_FCTIDUZ";
1520   case PPCISD::STRICT_FCTIWUZ:
1521     return "PPCISD::STRICT_FCTIWUZ";
1522   case PPCISD::STRICT_FCFID:
1523     return "PPCISD::STRICT_FCFID";
1524   case PPCISD::STRICT_FCFIDU:
1525     return "PPCISD::STRICT_FCFIDU";
1526   case PPCISD::STRICT_FCFIDS:
1527     return "PPCISD::STRICT_FCFIDS";
1528   case PPCISD::STRICT_FCFIDUS:
1529     return "PPCISD::STRICT_FCFIDUS";
1530   }
1531   return nullptr;
1532 }
1533 
1534 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1535                                           EVT VT) const {
1536   if (!VT.isVector())
1537     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1538 
1539   return VT.changeVectorElementTypeToInteger();
1540 }
1541 
1542 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1543   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1544   return true;
1545 }
1546 
1547 //===----------------------------------------------------------------------===//
1548 // Node matching predicates, for use by the tblgen matching code.
1549 //===----------------------------------------------------------------------===//
1550 
1551 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1552 static bool isFloatingPointZero(SDValue Op) {
1553   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1554     return CFP->getValueAPF().isZero();
1555   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1556     // Maybe this has already been legalized into the constant pool?
1557     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1558       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1559         return CFP->getValueAPF().isZero();
1560   }
1561   return false;
1562 }
1563 
1564 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1565 /// true if Op is undef or if it matches the specified value.
1566 static bool isConstantOrUndef(int Op, int Val) {
1567   return Op < 0 || Op == Val;
1568 }
1569 
1570 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1571 /// VPKUHUM instruction.
1572 /// The ShuffleKind distinguishes between big-endian operations with
1573 /// two different inputs (0), either-endian operations with two identical
1574 /// inputs (1), and little-endian operations with two different inputs (2).
1575 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1576 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1577                                SelectionDAG &DAG) {
1578   bool IsLE = DAG.getDataLayout().isLittleEndian();
1579   if (ShuffleKind == 0) {
1580     if (IsLE)
1581       return false;
1582     for (unsigned i = 0; i != 16; ++i)
1583       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1584         return false;
1585   } else if (ShuffleKind == 2) {
1586     if (!IsLE)
1587       return false;
1588     for (unsigned i = 0; i != 16; ++i)
1589       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1590         return false;
1591   } else if (ShuffleKind == 1) {
1592     unsigned j = IsLE ? 0 : 1;
1593     for (unsigned i = 0; i != 8; ++i)
1594       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1595           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1596         return false;
1597   }
1598   return true;
1599 }
1600 
1601 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1602 /// VPKUWUM instruction.
1603 /// The ShuffleKind distinguishes between big-endian operations with
1604 /// two different inputs (0), either-endian operations with two identical
1605 /// inputs (1), and little-endian operations with two different inputs (2).
1606 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1607 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1608                                SelectionDAG &DAG) {
1609   bool IsLE = DAG.getDataLayout().isLittleEndian();
1610   if (ShuffleKind == 0) {
1611     if (IsLE)
1612       return false;
1613     for (unsigned i = 0; i != 16; i += 2)
1614       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1615           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1616         return false;
1617   } else if (ShuffleKind == 2) {
1618     if (!IsLE)
1619       return false;
1620     for (unsigned i = 0; i != 16; i += 2)
1621       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1622           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1623         return false;
1624   } else if (ShuffleKind == 1) {
1625     unsigned j = IsLE ? 0 : 2;
1626     for (unsigned i = 0; i != 8; i += 2)
1627       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1628           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1629           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1630           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1631         return false;
1632   }
1633   return true;
1634 }
1635 
1636 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1637 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1638 /// current subtarget.
1639 ///
1640 /// The ShuffleKind distinguishes between big-endian operations with
1641 /// two different inputs (0), either-endian operations with two identical
1642 /// inputs (1), and little-endian operations with two different inputs (2).
1643 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1644 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1645                                SelectionDAG &DAG) {
1646   const PPCSubtarget& Subtarget =
1647       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1648   if (!Subtarget.hasP8Vector())
1649     return false;
1650 
1651   bool IsLE = DAG.getDataLayout().isLittleEndian();
1652   if (ShuffleKind == 0) {
1653     if (IsLE)
1654       return false;
1655     for (unsigned i = 0; i != 16; i += 4)
1656       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1657           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1658           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1659           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1660         return false;
1661   } else if (ShuffleKind == 2) {
1662     if (!IsLE)
1663       return false;
1664     for (unsigned i = 0; i != 16; i += 4)
1665       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1666           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1667           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1668           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1669         return false;
1670   } else if (ShuffleKind == 1) {
1671     unsigned j = IsLE ? 0 : 4;
1672     for (unsigned i = 0; i != 8; i += 4)
1673       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1674           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1675           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1676           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1677           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1678           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1679           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1680           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1681         return false;
1682   }
1683   return true;
1684 }
1685 
1686 /// isVMerge - Common function, used to match vmrg* shuffles.
1687 ///
1688 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1689                      unsigned LHSStart, unsigned RHSStart) {
1690   if (N->getValueType(0) != MVT::v16i8)
1691     return false;
1692   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1693          "Unsupported merge size!");
1694 
1695   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1696     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1697       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1698                              LHSStart+j+i*UnitSize) ||
1699           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1700                              RHSStart+j+i*UnitSize))
1701         return false;
1702     }
1703   return true;
1704 }
1705 
1706 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1707 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1708 /// The ShuffleKind distinguishes between big-endian merges with two
1709 /// different inputs (0), either-endian merges with two identical inputs (1),
1710 /// and little-endian merges with two different inputs (2).  For the latter,
1711 /// the input operands are swapped (see PPCInstrAltivec.td).
1712 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1713                              unsigned ShuffleKind, SelectionDAG &DAG) {
1714   if (DAG.getDataLayout().isLittleEndian()) {
1715     if (ShuffleKind == 1) // unary
1716       return isVMerge(N, UnitSize, 0, 0);
1717     else if (ShuffleKind == 2) // swapped
1718       return isVMerge(N, UnitSize, 0, 16);
1719     else
1720       return false;
1721   } else {
1722     if (ShuffleKind == 1) // unary
1723       return isVMerge(N, UnitSize, 8, 8);
1724     else if (ShuffleKind == 0) // normal
1725       return isVMerge(N, UnitSize, 8, 24);
1726     else
1727       return false;
1728   }
1729 }
1730 
1731 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1732 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1733 /// The ShuffleKind distinguishes between big-endian merges with two
1734 /// different inputs (0), either-endian merges with two identical inputs (1),
1735 /// and little-endian merges with two different inputs (2).  For the latter,
1736 /// the input operands are swapped (see PPCInstrAltivec.td).
1737 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1738                              unsigned ShuffleKind, SelectionDAG &DAG) {
1739   if (DAG.getDataLayout().isLittleEndian()) {
1740     if (ShuffleKind == 1) // unary
1741       return isVMerge(N, UnitSize, 8, 8);
1742     else if (ShuffleKind == 2) // swapped
1743       return isVMerge(N, UnitSize, 8, 24);
1744     else
1745       return false;
1746   } else {
1747     if (ShuffleKind == 1) // unary
1748       return isVMerge(N, UnitSize, 0, 0);
1749     else if (ShuffleKind == 0) // normal
1750       return isVMerge(N, UnitSize, 0, 16);
1751     else
1752       return false;
1753   }
1754 }
1755 
1756 /**
1757  * Common function used to match vmrgew and vmrgow shuffles
1758  *
1759  * The indexOffset determines whether to look for even or odd words in
1760  * the shuffle mask. This is based on the of the endianness of the target
1761  * machine.
1762  *   - Little Endian:
1763  *     - Use offset of 0 to check for odd elements
1764  *     - Use offset of 4 to check for even elements
1765  *   - Big Endian:
1766  *     - Use offset of 0 to check for even elements
1767  *     - Use offset of 4 to check for odd elements
1768  * A detailed description of the vector element ordering for little endian and
1769  * big endian can be found at
1770  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1771  * Targeting your applications - what little endian and big endian IBM XL C/C++
1772  * compiler differences mean to you
1773  *
1774  * The mask to the shuffle vector instruction specifies the indices of the
1775  * elements from the two input vectors to place in the result. The elements are
1776  * numbered in array-access order, starting with the first vector. These vectors
1777  * are always of type v16i8, thus each vector will contain 16 elements of size
1778  * 8. More info on the shuffle vector can be found in the
1779  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1780  * Language Reference.
1781  *
1782  * The RHSStartValue indicates whether the same input vectors are used (unary)
1783  * or two different input vectors are used, based on the following:
1784  *   - If the instruction uses the same vector for both inputs, the range of the
1785  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1786  *     be 0.
1787  *   - If the instruction has two different vectors then the range of the
1788  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1789  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1790  *     to 31 specify elements in the second vector).
1791  *
1792  * \param[in] N The shuffle vector SD Node to analyze
1793  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1794  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1795  * vector to the shuffle_vector instruction
1796  * \return true iff this shuffle vector represents an even or odd word merge
1797  */
1798 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1799                      unsigned RHSStartValue) {
1800   if (N->getValueType(0) != MVT::v16i8)
1801     return false;
1802 
1803   for (unsigned i = 0; i < 2; ++i)
1804     for (unsigned j = 0; j < 4; ++j)
1805       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1806                              i*RHSStartValue+j+IndexOffset) ||
1807           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1808                              i*RHSStartValue+j+IndexOffset+8))
1809         return false;
1810   return true;
1811 }
1812 
1813 /**
1814  * Determine if the specified shuffle mask is suitable for the vmrgew or
1815  * vmrgow instructions.
1816  *
1817  * \param[in] N The shuffle vector SD Node to analyze
1818  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1819  * \param[in] ShuffleKind Identify the type of merge:
1820  *   - 0 = big-endian merge with two different inputs;
1821  *   - 1 = either-endian merge with two identical inputs;
1822  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1823  *     little-endian merges).
1824  * \param[in] DAG The current SelectionDAG
1825  * \return true iff this shuffle mask
1826  */
1827 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1828                               unsigned ShuffleKind, SelectionDAG &DAG) {
1829   if (DAG.getDataLayout().isLittleEndian()) {
1830     unsigned indexOffset = CheckEven ? 4 : 0;
1831     if (ShuffleKind == 1) // Unary
1832       return isVMerge(N, indexOffset, 0);
1833     else if (ShuffleKind == 2) // swapped
1834       return isVMerge(N, indexOffset, 16);
1835     else
1836       return false;
1837   }
1838   else {
1839     unsigned indexOffset = CheckEven ? 0 : 4;
1840     if (ShuffleKind == 1) // Unary
1841       return isVMerge(N, indexOffset, 0);
1842     else if (ShuffleKind == 0) // Normal
1843       return isVMerge(N, indexOffset, 16);
1844     else
1845       return false;
1846   }
1847   return false;
1848 }
1849 
1850 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1851 /// amount, otherwise return -1.
1852 /// The ShuffleKind distinguishes between big-endian operations with two
1853 /// different inputs (0), either-endian operations with two identical inputs
1854 /// (1), and little-endian operations with two different inputs (2).  For the
1855 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1856 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1857                              SelectionDAG &DAG) {
1858   if (N->getValueType(0) != MVT::v16i8)
1859     return -1;
1860 
1861   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1862 
1863   // Find the first non-undef value in the shuffle mask.
1864   unsigned i;
1865   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1866     /*search*/;
1867 
1868   if (i == 16) return -1;  // all undef.
1869 
1870   // Otherwise, check to see if the rest of the elements are consecutively
1871   // numbered from this value.
1872   unsigned ShiftAmt = SVOp->getMaskElt(i);
1873   if (ShiftAmt < i) return -1;
1874 
1875   ShiftAmt -= i;
1876   bool isLE = DAG.getDataLayout().isLittleEndian();
1877 
1878   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1879     // Check the rest of the elements to see if they are consecutive.
1880     for (++i; i != 16; ++i)
1881       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1882         return -1;
1883   } else if (ShuffleKind == 1) {
1884     // Check the rest of the elements to see if they are consecutive.
1885     for (++i; i != 16; ++i)
1886       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1887         return -1;
1888   } else
1889     return -1;
1890 
1891   if (isLE)
1892     ShiftAmt = 16 - ShiftAmt;
1893 
1894   return ShiftAmt;
1895 }
1896 
1897 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1898 /// specifies a splat of a single element that is suitable for input to
1899 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1900 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1901   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1902          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1903 
1904   // The consecutive indices need to specify an element, not part of two
1905   // different elements.  So abandon ship early if this isn't the case.
1906   if (N->getMaskElt(0) % EltSize != 0)
1907     return false;
1908 
1909   // This is a splat operation if each element of the permute is the same, and
1910   // if the value doesn't reference the second vector.
1911   unsigned ElementBase = N->getMaskElt(0);
1912 
1913   // FIXME: Handle UNDEF elements too!
1914   if (ElementBase >= 16)
1915     return false;
1916 
1917   // Check that the indices are consecutive, in the case of a multi-byte element
1918   // splatted with a v16i8 mask.
1919   for (unsigned i = 1; i != EltSize; ++i)
1920     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1921       return false;
1922 
1923   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1924     if (N->getMaskElt(i) < 0) continue;
1925     for (unsigned j = 0; j != EltSize; ++j)
1926       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1927         return false;
1928   }
1929   return true;
1930 }
1931 
1932 /// Check that the mask is shuffling N byte elements. Within each N byte
1933 /// element of the mask, the indices could be either in increasing or
1934 /// decreasing order as long as they are consecutive.
1935 /// \param[in] N the shuffle vector SD Node to analyze
1936 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1937 /// Word/DoubleWord/QuadWord).
1938 /// \param[in] StepLen the delta indices number among the N byte element, if
1939 /// the mask is in increasing/decreasing order then it is 1/-1.
1940 /// \return true iff the mask is shuffling N byte elements.
1941 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1942                                    int StepLen) {
1943   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1944          "Unexpected element width.");
1945   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1946 
1947   unsigned NumOfElem = 16 / Width;
1948   unsigned MaskVal[16]; //  Width is never greater than 16
1949   for (unsigned i = 0; i < NumOfElem; ++i) {
1950     MaskVal[0] = N->getMaskElt(i * Width);
1951     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1952       return false;
1953     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1954       return false;
1955     }
1956 
1957     for (unsigned int j = 1; j < Width; ++j) {
1958       MaskVal[j] = N->getMaskElt(i * Width + j);
1959       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1960         return false;
1961       }
1962     }
1963   }
1964 
1965   return true;
1966 }
1967 
1968 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1969                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1970   if (!isNByteElemShuffleMask(N, 4, 1))
1971     return false;
1972 
1973   // Now we look at mask elements 0,4,8,12
1974   unsigned M0 = N->getMaskElt(0) / 4;
1975   unsigned M1 = N->getMaskElt(4) / 4;
1976   unsigned M2 = N->getMaskElt(8) / 4;
1977   unsigned M3 = N->getMaskElt(12) / 4;
1978   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1979   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1980 
1981   // Below, let H and L be arbitrary elements of the shuffle mask
1982   // where H is in the range [4,7] and L is in the range [0,3].
1983   // H, 1, 2, 3 or L, 5, 6, 7
1984   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1985       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1986     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1987     InsertAtByte = IsLE ? 12 : 0;
1988     Swap = M0 < 4;
1989     return true;
1990   }
1991   // 0, H, 2, 3 or 4, L, 6, 7
1992   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1993       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1994     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1995     InsertAtByte = IsLE ? 8 : 4;
1996     Swap = M1 < 4;
1997     return true;
1998   }
1999   // 0, 1, H, 3 or 4, 5, L, 7
2000   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2001       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2002     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2003     InsertAtByte = IsLE ? 4 : 8;
2004     Swap = M2 < 4;
2005     return true;
2006   }
2007   // 0, 1, 2, H or 4, 5, 6, L
2008   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2009       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2010     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2011     InsertAtByte = IsLE ? 0 : 12;
2012     Swap = M3 < 4;
2013     return true;
2014   }
2015 
2016   // If both vector operands for the shuffle are the same vector, the mask will
2017   // contain only elements from the first one and the second one will be undef.
2018   if (N->getOperand(1).isUndef()) {
2019     ShiftElts = 0;
2020     Swap = true;
2021     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2022     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2023       InsertAtByte = IsLE ? 12 : 0;
2024       return true;
2025     }
2026     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2027       InsertAtByte = IsLE ? 8 : 4;
2028       return true;
2029     }
2030     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2031       InsertAtByte = IsLE ? 4 : 8;
2032       return true;
2033     }
2034     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2035       InsertAtByte = IsLE ? 0 : 12;
2036       return true;
2037     }
2038   }
2039 
2040   return false;
2041 }
2042 
2043 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2044                                bool &Swap, bool IsLE) {
2045   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2046   // Ensure each byte index of the word is consecutive.
2047   if (!isNByteElemShuffleMask(N, 4, 1))
2048     return false;
2049 
2050   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2051   unsigned M0 = N->getMaskElt(0) / 4;
2052   unsigned M1 = N->getMaskElt(4) / 4;
2053   unsigned M2 = N->getMaskElt(8) / 4;
2054   unsigned M3 = N->getMaskElt(12) / 4;
2055 
2056   // If both vector operands for the shuffle are the same vector, the mask will
2057   // contain only elements from the first one and the second one will be undef.
2058   if (N->getOperand(1).isUndef()) {
2059     assert(M0 < 4 && "Indexing into an undef vector?");
2060     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2061       return false;
2062 
2063     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2064     Swap = false;
2065     return true;
2066   }
2067 
2068   // Ensure each word index of the ShuffleVector Mask is consecutive.
2069   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2070     return false;
2071 
2072   if (IsLE) {
2073     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2074       // Input vectors don't need to be swapped if the leading element
2075       // of the result is one of the 3 left elements of the second vector
2076       // (or if there is no shift to be done at all).
2077       Swap = false;
2078       ShiftElts = (8 - M0) % 8;
2079     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2080       // Input vectors need to be swapped if the leading element
2081       // of the result is one of the 3 left elements of the first vector
2082       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2083       Swap = true;
2084       ShiftElts = (4 - M0) % 4;
2085     }
2086 
2087     return true;
2088   } else {                                          // BE
2089     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2090       // Input vectors don't need to be swapped if the leading element
2091       // of the result is one of the 4 elements of the first vector.
2092       Swap = false;
2093       ShiftElts = M0;
2094     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2095       // Input vectors need to be swapped if the leading element
2096       // of the result is one of the 4 elements of the right vector.
2097       Swap = true;
2098       ShiftElts = M0 - 4;
2099     }
2100 
2101     return true;
2102   }
2103 }
2104 
2105 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2106   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2107 
2108   if (!isNByteElemShuffleMask(N, Width, -1))
2109     return false;
2110 
2111   for (int i = 0; i < 16; i += Width)
2112     if (N->getMaskElt(i) != i + Width - 1)
2113       return false;
2114 
2115   return true;
2116 }
2117 
2118 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2119   return isXXBRShuffleMaskHelper(N, 2);
2120 }
2121 
2122 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2123   return isXXBRShuffleMaskHelper(N, 4);
2124 }
2125 
2126 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2127   return isXXBRShuffleMaskHelper(N, 8);
2128 }
2129 
2130 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2131   return isXXBRShuffleMaskHelper(N, 16);
2132 }
2133 
2134 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2135 /// if the inputs to the instruction should be swapped and set \p DM to the
2136 /// value for the immediate.
2137 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2138 /// AND element 0 of the result comes from the first input (LE) or second input
2139 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2140 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2141 /// mask.
2142 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2143                                bool &Swap, bool IsLE) {
2144   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2145 
2146   // Ensure each byte index of the double word is consecutive.
2147   if (!isNByteElemShuffleMask(N, 8, 1))
2148     return false;
2149 
2150   unsigned M0 = N->getMaskElt(0) / 8;
2151   unsigned M1 = N->getMaskElt(8) / 8;
2152   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2153 
2154   // If both vector operands for the shuffle are the same vector, the mask will
2155   // contain only elements from the first one and the second one will be undef.
2156   if (N->getOperand(1).isUndef()) {
2157     if ((M0 | M1) < 2) {
2158       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2159       Swap = false;
2160       return true;
2161     } else
2162       return false;
2163   }
2164 
2165   if (IsLE) {
2166     if (M0 > 1 && M1 < 2) {
2167       Swap = false;
2168     } else if (M0 < 2 && M1 > 1) {
2169       M0 = (M0 + 2) % 4;
2170       M1 = (M1 + 2) % 4;
2171       Swap = true;
2172     } else
2173       return false;
2174 
2175     // Note: if control flow comes here that means Swap is already set above
2176     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2177     return true;
2178   } else { // BE
2179     if (M0 < 2 && M1 > 1) {
2180       Swap = false;
2181     } else if (M0 > 1 && M1 < 2) {
2182       M0 = (M0 + 2) % 4;
2183       M1 = (M1 + 2) % 4;
2184       Swap = true;
2185     } else
2186       return false;
2187 
2188     // Note: if control flow comes here that means Swap is already set above
2189     DM = (M0 << 1) + (M1 & 1);
2190     return true;
2191   }
2192 }
2193 
2194 
2195 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2196 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2197 /// elements are counted from the left of the vector register).
2198 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2199                                          SelectionDAG &DAG) {
2200   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2201   assert(isSplatShuffleMask(SVOp, EltSize));
2202   if (DAG.getDataLayout().isLittleEndian())
2203     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2204   else
2205     return SVOp->getMaskElt(0) / EltSize;
2206 }
2207 
2208 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2209 /// by using a vspltis[bhw] instruction of the specified element size, return
2210 /// the constant being splatted.  The ByteSize field indicates the number of
2211 /// bytes of each element [124] -> [bhw].
2212 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2213   SDValue OpVal(nullptr, 0);
2214 
2215   // If ByteSize of the splat is bigger than the element size of the
2216   // build_vector, then we have a case where we are checking for a splat where
2217   // multiple elements of the buildvector are folded together into a single
2218   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2219   unsigned EltSize = 16/N->getNumOperands();
2220   if (EltSize < ByteSize) {
2221     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2222     SDValue UniquedVals[4];
2223     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2224 
2225     // See if all of the elements in the buildvector agree across.
2226     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2227       if (N->getOperand(i).isUndef()) continue;
2228       // If the element isn't a constant, bail fully out.
2229       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2230 
2231       if (!UniquedVals[i&(Multiple-1)].getNode())
2232         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2233       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2234         return SDValue();  // no match.
2235     }
2236 
2237     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2238     // either constant or undef values that are identical for each chunk.  See
2239     // if these chunks can form into a larger vspltis*.
2240 
2241     // Check to see if all of the leading entries are either 0 or -1.  If
2242     // neither, then this won't fit into the immediate field.
2243     bool LeadingZero = true;
2244     bool LeadingOnes = true;
2245     for (unsigned i = 0; i != Multiple-1; ++i) {
2246       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2247 
2248       LeadingZero &= isNullConstant(UniquedVals[i]);
2249       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2250     }
2251     // Finally, check the least significant entry.
2252     if (LeadingZero) {
2253       if (!UniquedVals[Multiple-1].getNode())
2254         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2255       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2256       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2257         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2258     }
2259     if (LeadingOnes) {
2260       if (!UniquedVals[Multiple-1].getNode())
2261         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2262       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2263       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2264         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2265     }
2266 
2267     return SDValue();
2268   }
2269 
2270   // Check to see if this buildvec has a single non-undef value in its elements.
2271   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2272     if (N->getOperand(i).isUndef()) continue;
2273     if (!OpVal.getNode())
2274       OpVal = N->getOperand(i);
2275     else if (OpVal != N->getOperand(i))
2276       return SDValue();
2277   }
2278 
2279   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2280 
2281   unsigned ValSizeInBytes = EltSize;
2282   uint64_t Value = 0;
2283   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2284     Value = CN->getZExtValue();
2285   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2286     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2287     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2288   }
2289 
2290   // If the splat value is larger than the element value, then we can never do
2291   // this splat.  The only case that we could fit the replicated bits into our
2292   // immediate field for would be zero, and we prefer to use vxor for it.
2293   if (ValSizeInBytes < ByteSize) return SDValue();
2294 
2295   // If the element value is larger than the splat value, check if it consists
2296   // of a repeated bit pattern of size ByteSize.
2297   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2298     return SDValue();
2299 
2300   // Properly sign extend the value.
2301   int MaskVal = SignExtend32(Value, ByteSize * 8);
2302 
2303   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2304   if (MaskVal == 0) return SDValue();
2305 
2306   // Finally, if this value fits in a 5 bit sext field, return it
2307   if (SignExtend32<5>(MaskVal) == MaskVal)
2308     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2309   return SDValue();
2310 }
2311 
2312 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2313 /// amount, otherwise return -1.
2314 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2315   EVT VT = N->getValueType(0);
2316   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2317     return -1;
2318 
2319   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2320 
2321   // Find the first non-undef value in the shuffle mask.
2322   unsigned i;
2323   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2324     /*search*/;
2325 
2326   if (i == 4) return -1;  // all undef.
2327 
2328   // Otherwise, check to see if the rest of the elements are consecutively
2329   // numbered from this value.
2330   unsigned ShiftAmt = SVOp->getMaskElt(i);
2331   if (ShiftAmt < i) return -1;
2332   ShiftAmt -= i;
2333 
2334   // Check the rest of the elements to see if they are consecutive.
2335   for (++i; i != 4; ++i)
2336     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2337       return -1;
2338 
2339   return ShiftAmt;
2340 }
2341 
2342 //===----------------------------------------------------------------------===//
2343 //  Addressing Mode Selection
2344 //===----------------------------------------------------------------------===//
2345 
2346 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2347 /// or 64-bit immediate, and if the value can be accurately represented as a
2348 /// sign extension from a 16-bit value.  If so, this returns true and the
2349 /// immediate.
2350 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2351   if (!isa<ConstantSDNode>(N))
2352     return false;
2353 
2354   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2355   if (N->getValueType(0) == MVT::i32)
2356     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2357   else
2358     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2359 }
2360 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2361   return isIntS16Immediate(Op.getNode(), Imm);
2362 }
2363 
2364 
2365 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2366 /// be represented as an indexed [r+r] operation.
2367 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2368                                                SDValue &Index,
2369                                                SelectionDAG &DAG) const {
2370   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2371       UI != E; ++UI) {
2372     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2373       if (Memop->getMemoryVT() == MVT::f64) {
2374           Base = N.getOperand(0);
2375           Index = N.getOperand(1);
2376           return true;
2377       }
2378     }
2379   }
2380   return false;
2381 }
2382 
2383 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2384 /// can be represented as an indexed [r+r] operation.  Returns false if it
2385 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2386 /// non-zero and N can be represented by a base register plus a signed 16-bit
2387 /// displacement, make a more precise judgement by checking (displacement % \p
2388 /// EncodingAlignment).
2389 bool PPCTargetLowering::SelectAddressRegReg(
2390     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2391     MaybeAlign EncodingAlignment) const {
2392   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2393   // a [pc+imm].
2394   if (SelectAddressPCRel(N, Base))
2395     return false;
2396 
2397   int16_t Imm = 0;
2398   if (N.getOpcode() == ISD::ADD) {
2399     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2400     // SPE load/store can only handle 8-bit offsets.
2401     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2402         return true;
2403     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2404         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2405       return false; // r+i
2406     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2407       return false;    // r+i
2408 
2409     Base = N.getOperand(0);
2410     Index = N.getOperand(1);
2411     return true;
2412   } else if (N.getOpcode() == ISD::OR) {
2413     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2414         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2415       return false; // r+i can fold it if we can.
2416 
2417     // If this is an or of disjoint bitfields, we can codegen this as an add
2418     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2419     // disjoint.
2420     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2421 
2422     if (LHSKnown.Zero.getBoolValue()) {
2423       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2424       // If all of the bits are known zero on the LHS or RHS, the add won't
2425       // carry.
2426       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2427         Base = N.getOperand(0);
2428         Index = N.getOperand(1);
2429         return true;
2430       }
2431     }
2432   }
2433 
2434   return false;
2435 }
2436 
2437 // If we happen to be doing an i64 load or store into a stack slot that has
2438 // less than a 4-byte alignment, then the frame-index elimination may need to
2439 // use an indexed load or store instruction (because the offset may not be a
2440 // multiple of 4). The extra register needed to hold the offset comes from the
2441 // register scavenger, and it is possible that the scavenger will need to use
2442 // an emergency spill slot. As a result, we need to make sure that a spill slot
2443 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2444 // stack slot.
2445 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2446   // FIXME: This does not handle the LWA case.
2447   if (VT != MVT::i64)
2448     return;
2449 
2450   // NOTE: We'll exclude negative FIs here, which come from argument
2451   // lowering, because there are no known test cases triggering this problem
2452   // using packed structures (or similar). We can remove this exclusion if
2453   // we find such a test case. The reason why this is so test-case driven is
2454   // because this entire 'fixup' is only to prevent crashes (from the
2455   // register scavenger) on not-really-valid inputs. For example, if we have:
2456   //   %a = alloca i1
2457   //   %b = bitcast i1* %a to i64*
2458   //   store i64* a, i64 b
2459   // then the store should really be marked as 'align 1', but is not. If it
2460   // were marked as 'align 1' then the indexed form would have been
2461   // instruction-selected initially, and the problem this 'fixup' is preventing
2462   // won't happen regardless.
2463   if (FrameIdx < 0)
2464     return;
2465 
2466   MachineFunction &MF = DAG.getMachineFunction();
2467   MachineFrameInfo &MFI = MF.getFrameInfo();
2468 
2469   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2470     return;
2471 
2472   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2473   FuncInfo->setHasNonRISpills();
2474 }
2475 
2476 /// Returns true if the address N can be represented by a base register plus
2477 /// a signed 16-bit displacement [r+imm], and if it is not better
2478 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2479 /// displacements that are multiples of that value.
2480 bool PPCTargetLowering::SelectAddressRegImm(
2481     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2482     MaybeAlign EncodingAlignment) const {
2483   // FIXME dl should come from parent load or store, not from address
2484   SDLoc dl(N);
2485 
2486   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2487   // a [pc+imm].
2488   if (SelectAddressPCRel(N, Base))
2489     return false;
2490 
2491   // If this can be more profitably realized as r+r, fail.
2492   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2493     return false;
2494 
2495   if (N.getOpcode() == ISD::ADD) {
2496     int16_t imm = 0;
2497     if (isIntS16Immediate(N.getOperand(1), imm) &&
2498         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2499       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2500       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2501         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2502         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2503       } else {
2504         Base = N.getOperand(0);
2505       }
2506       return true; // [r+i]
2507     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2508       // Match LOAD (ADD (X, Lo(G))).
2509       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2510              && "Cannot handle constant offsets yet!");
2511       Disp = N.getOperand(1).getOperand(0);  // The global address.
2512       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2513              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2514              Disp.getOpcode() == ISD::TargetConstantPool ||
2515              Disp.getOpcode() == ISD::TargetJumpTable);
2516       Base = N.getOperand(0);
2517       return true;  // [&g+r]
2518     }
2519   } else if (N.getOpcode() == ISD::OR) {
2520     int16_t imm = 0;
2521     if (isIntS16Immediate(N.getOperand(1), imm) &&
2522         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2523       // If this is an or of disjoint bitfields, we can codegen this as an add
2524       // (for better address arithmetic) if the LHS and RHS of the OR are
2525       // provably disjoint.
2526       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2527 
2528       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2529         // If all of the bits are known zero on the LHS or RHS, the add won't
2530         // carry.
2531         if (FrameIndexSDNode *FI =
2532               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2533           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2534           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2535         } else {
2536           Base = N.getOperand(0);
2537         }
2538         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2539         return true;
2540       }
2541     }
2542   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2543     // Loading from a constant address.
2544 
2545     // If this address fits entirely in a 16-bit sext immediate field, codegen
2546     // this as "d, 0"
2547     int16_t Imm;
2548     if (isIntS16Immediate(CN, Imm) &&
2549         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2550       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2551       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2552                              CN->getValueType(0));
2553       return true;
2554     }
2555 
2556     // Handle 32-bit sext immediates with LIS + addr mode.
2557     if ((CN->getValueType(0) == MVT::i32 ||
2558          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2559         (!EncodingAlignment ||
2560          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2561       int Addr = (int)CN->getZExtValue();
2562 
2563       // Otherwise, break this down into an LIS + disp.
2564       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2565 
2566       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2567                                    MVT::i32);
2568       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2569       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2570       return true;
2571     }
2572   }
2573 
2574   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2575   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2576     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2577     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2578   } else
2579     Base = N;
2580   return true;      // [r+0]
2581 }
2582 
2583 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2584 /// represented as an indexed [r+r] operation.
2585 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2586                                                 SDValue &Index,
2587                                                 SelectionDAG &DAG) const {
2588   // Check to see if we can easily represent this as an [r+r] address.  This
2589   // will fail if it thinks that the address is more profitably represented as
2590   // reg+imm, e.g. where imm = 0.
2591   if (SelectAddressRegReg(N, Base, Index, DAG))
2592     return true;
2593 
2594   // If the address is the result of an add, we will utilize the fact that the
2595   // address calculation includes an implicit add.  However, we can reduce
2596   // register pressure if we do not materialize a constant just for use as the
2597   // index register.  We only get rid of the add if it is not an add of a
2598   // value and a 16-bit signed constant and both have a single use.
2599   int16_t imm = 0;
2600   if (N.getOpcode() == ISD::ADD &&
2601       (!isIntS16Immediate(N.getOperand(1), imm) ||
2602        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2603     Base = N.getOperand(0);
2604     Index = N.getOperand(1);
2605     return true;
2606   }
2607 
2608   // Otherwise, do it the hard way, using R0 as the base register.
2609   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2610                          N.getValueType());
2611   Index = N;
2612   return true;
2613 }
2614 
2615 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2616   Ty *PCRelCand = dyn_cast<Ty>(N);
2617   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2618 }
2619 
2620 /// Returns true if this address is a PC Relative address.
2621 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2622 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2623 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2624   // This is a materialize PC Relative node. Always select this as PC Relative.
2625   Base = N;
2626   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2627     return true;
2628   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2629       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2630       isValidPCRelNode<JumpTableSDNode>(N) ||
2631       isValidPCRelNode<BlockAddressSDNode>(N))
2632     return true;
2633   return false;
2634 }
2635 
2636 /// Returns true if we should use a direct load into vector instruction
2637 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2638 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2639 
2640   // If there are any other uses other than scalar to vector, then we should
2641   // keep it as a scalar load -> direct move pattern to prevent multiple
2642   // loads.
2643   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2644   if (!LD)
2645     return false;
2646 
2647   EVT MemVT = LD->getMemoryVT();
2648   if (!MemVT.isSimple())
2649     return false;
2650   switch(MemVT.getSimpleVT().SimpleTy) {
2651   case MVT::i64:
2652     break;
2653   case MVT::i32:
2654     if (!ST.hasP8Vector())
2655       return false;
2656     break;
2657   case MVT::i16:
2658   case MVT::i8:
2659     if (!ST.hasP9Vector())
2660       return false;
2661     break;
2662   default:
2663     return false;
2664   }
2665 
2666   SDValue LoadedVal(N, 0);
2667   if (!LoadedVal.hasOneUse())
2668     return false;
2669 
2670   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2671        UI != UE; ++UI)
2672     if (UI.getUse().get().getResNo() == 0 &&
2673         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2674         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2675       return false;
2676 
2677   return true;
2678 }
2679 
2680 /// getPreIndexedAddressParts - returns true by value, base pointer and
2681 /// offset pointer and addressing mode by reference if the node's address
2682 /// can be legally represented as pre-indexed load / store address.
2683 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2684                                                   SDValue &Offset,
2685                                                   ISD::MemIndexedMode &AM,
2686                                                   SelectionDAG &DAG) const {
2687   if (DisablePPCPreinc) return false;
2688 
2689   bool isLoad = true;
2690   SDValue Ptr;
2691   EVT VT;
2692   unsigned Alignment;
2693   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2694     Ptr = LD->getBasePtr();
2695     VT = LD->getMemoryVT();
2696     Alignment = LD->getAlignment();
2697   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2698     Ptr = ST->getBasePtr();
2699     VT  = ST->getMemoryVT();
2700     Alignment = ST->getAlignment();
2701     isLoad = false;
2702   } else
2703     return false;
2704 
2705   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2706   // instructions because we can fold these into a more efficient instruction
2707   // instead, (such as LXSD).
2708   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2709     return false;
2710   }
2711 
2712   // PowerPC doesn't have preinc load/store instructions for vectors
2713   if (VT.isVector())
2714     return false;
2715 
2716   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2717     // Common code will reject creating a pre-inc form if the base pointer
2718     // is a frame index, or if N is a store and the base pointer is either
2719     // the same as or a predecessor of the value being stored.  Check for
2720     // those situations here, and try with swapped Base/Offset instead.
2721     bool Swap = false;
2722 
2723     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2724       Swap = true;
2725     else if (!isLoad) {
2726       SDValue Val = cast<StoreSDNode>(N)->getValue();
2727       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2728         Swap = true;
2729     }
2730 
2731     if (Swap)
2732       std::swap(Base, Offset);
2733 
2734     AM = ISD::PRE_INC;
2735     return true;
2736   }
2737 
2738   // LDU/STU can only handle immediates that are a multiple of 4.
2739   if (VT != MVT::i64) {
2740     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2741       return false;
2742   } else {
2743     // LDU/STU need an address with at least 4-byte alignment.
2744     if (Alignment < 4)
2745       return false;
2746 
2747     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2748       return false;
2749   }
2750 
2751   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2752     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2753     // sext i32 to i64 when addr mode is r+i.
2754     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2755         LD->getExtensionType() == ISD::SEXTLOAD &&
2756         isa<ConstantSDNode>(Offset))
2757       return false;
2758   }
2759 
2760   AM = ISD::PRE_INC;
2761   return true;
2762 }
2763 
2764 //===----------------------------------------------------------------------===//
2765 //  LowerOperation implementation
2766 //===----------------------------------------------------------------------===//
2767 
2768 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2769 /// and LoOpFlags to the target MO flags.
2770 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2771                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2772                                const GlobalValue *GV = nullptr) {
2773   HiOpFlags = PPCII::MO_HA;
2774   LoOpFlags = PPCII::MO_LO;
2775 
2776   // Don't use the pic base if not in PIC relocation model.
2777   if (IsPIC) {
2778     HiOpFlags |= PPCII::MO_PIC_FLAG;
2779     LoOpFlags |= PPCII::MO_PIC_FLAG;
2780   }
2781 }
2782 
2783 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2784                              SelectionDAG &DAG) {
2785   SDLoc DL(HiPart);
2786   EVT PtrVT = HiPart.getValueType();
2787   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2788 
2789   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2790   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2791 
2792   // With PIC, the first instruction is actually "GR+hi(&G)".
2793   if (isPIC)
2794     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2795                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2796 
2797   // Generate non-pic code that has direct accesses to the constant pool.
2798   // The address of the global is just (hi(&g)+lo(&g)).
2799   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2800 }
2801 
2802 static void setUsesTOCBasePtr(MachineFunction &MF) {
2803   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2804   FuncInfo->setUsesTOCBasePtr();
2805 }
2806 
2807 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2808   setUsesTOCBasePtr(DAG.getMachineFunction());
2809 }
2810 
2811 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2812                                        SDValue GA) const {
2813   const bool Is64Bit = Subtarget.isPPC64();
2814   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2815   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2816                         : Subtarget.isAIXABI()
2817                               ? DAG.getRegister(PPC::R2, VT)
2818                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2819   SDValue Ops[] = { GA, Reg };
2820   return DAG.getMemIntrinsicNode(
2821       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2822       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2823       MachineMemOperand::MOLoad);
2824 }
2825 
2826 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2827                                              SelectionDAG &DAG) const {
2828   EVT PtrVT = Op.getValueType();
2829   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2830   const Constant *C = CP->getConstVal();
2831 
2832   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2833   // The actual address of the GlobalValue is stored in the TOC.
2834   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2835     if (Subtarget.isUsingPCRelativeCalls()) {
2836       SDLoc DL(CP);
2837       EVT Ty = getPointerTy(DAG.getDataLayout());
2838       SDValue ConstPool = DAG.getTargetConstantPool(
2839           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2840       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2841     }
2842     setUsesTOCBasePtr(DAG);
2843     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2844     return getTOCEntry(DAG, SDLoc(CP), GA);
2845   }
2846 
2847   unsigned MOHiFlag, MOLoFlag;
2848   bool IsPIC = isPositionIndependent();
2849   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2850 
2851   if (IsPIC && Subtarget.isSVR4ABI()) {
2852     SDValue GA =
2853         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2854     return getTOCEntry(DAG, SDLoc(CP), GA);
2855   }
2856 
2857   SDValue CPIHi =
2858       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2859   SDValue CPILo =
2860       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2861   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2862 }
2863 
2864 // For 64-bit PowerPC, prefer the more compact relative encodings.
2865 // This trades 32 bits per jump table entry for one or two instructions
2866 // on the jump site.
2867 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2868   if (isJumpTableRelative())
2869     return MachineJumpTableInfo::EK_LabelDifference32;
2870 
2871   return TargetLowering::getJumpTableEncoding();
2872 }
2873 
2874 bool PPCTargetLowering::isJumpTableRelative() const {
2875   if (UseAbsoluteJumpTables)
2876     return false;
2877   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2878     return true;
2879   return TargetLowering::isJumpTableRelative();
2880 }
2881 
2882 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2883                                                     SelectionDAG &DAG) const {
2884   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2885     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2886 
2887   switch (getTargetMachine().getCodeModel()) {
2888   case CodeModel::Small:
2889   case CodeModel::Medium:
2890     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2891   default:
2892     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2893                        getPointerTy(DAG.getDataLayout()));
2894   }
2895 }
2896 
2897 const MCExpr *
2898 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2899                                                 unsigned JTI,
2900                                                 MCContext &Ctx) const {
2901   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2902     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2903 
2904   switch (getTargetMachine().getCodeModel()) {
2905   case CodeModel::Small:
2906   case CodeModel::Medium:
2907     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2908   default:
2909     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2910   }
2911 }
2912 
2913 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2914   EVT PtrVT = Op.getValueType();
2915   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2916 
2917   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2918   if (Subtarget.isUsingPCRelativeCalls()) {
2919     SDLoc DL(JT);
2920     EVT Ty = getPointerTy(DAG.getDataLayout());
2921     SDValue GA =
2922         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2923     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2924     return MatAddr;
2925   }
2926 
2927   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2928   // The actual address of the GlobalValue is stored in the TOC.
2929   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2930     setUsesTOCBasePtr(DAG);
2931     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2932     return getTOCEntry(DAG, SDLoc(JT), GA);
2933   }
2934 
2935   unsigned MOHiFlag, MOLoFlag;
2936   bool IsPIC = isPositionIndependent();
2937   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2938 
2939   if (IsPIC && Subtarget.isSVR4ABI()) {
2940     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2941                                         PPCII::MO_PIC_FLAG);
2942     return getTOCEntry(DAG, SDLoc(GA), GA);
2943   }
2944 
2945   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2946   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2947   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2948 }
2949 
2950 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2951                                              SelectionDAG &DAG) const {
2952   EVT PtrVT = Op.getValueType();
2953   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2954   const BlockAddress *BA = BASDN->getBlockAddress();
2955 
2956   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2957   if (Subtarget.isUsingPCRelativeCalls()) {
2958     SDLoc DL(BASDN);
2959     EVT Ty = getPointerTy(DAG.getDataLayout());
2960     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2961                                            PPCII::MO_PCREL_FLAG);
2962     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2963     return MatAddr;
2964   }
2965 
2966   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2967   // The actual BlockAddress is stored in the TOC.
2968   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2969     setUsesTOCBasePtr(DAG);
2970     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2971     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2972   }
2973 
2974   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2975   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2976     return getTOCEntry(
2977         DAG, SDLoc(BASDN),
2978         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2979 
2980   unsigned MOHiFlag, MOLoFlag;
2981   bool IsPIC = isPositionIndependent();
2982   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2983   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2984   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2985   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2986 }
2987 
2988 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2989                                               SelectionDAG &DAG) const {
2990   // FIXME: TLS addresses currently use medium model code sequences,
2991   // which is the most useful form.  Eventually support for small and
2992   // large models could be added if users need it, at the cost of
2993   // additional complexity.
2994   if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS)
2995     report_fatal_error("Thread local storage is not supported with pc-relative"
2996                        " addressing - please compile with -mno-pcrel");
2997   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2998   if (DAG.getTarget().useEmulatedTLS())
2999     return LowerToTLSEmulatedModel(GA, DAG);
3000 
3001   SDLoc dl(GA);
3002   const GlobalValue *GV = GA->getGlobal();
3003   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3004   bool is64bit = Subtarget.isPPC64();
3005   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3006   PICLevel::Level picLevel = M->getPICLevel();
3007 
3008   const TargetMachine &TM = getTargetMachine();
3009   TLSModel::Model Model = TM.getTLSModel(GV);
3010 
3011   if (Model == TLSModel::LocalExec) {
3012     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3013                                                PPCII::MO_TPREL_HA);
3014     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3015                                                PPCII::MO_TPREL_LO);
3016     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3017                              : DAG.getRegister(PPC::R2, MVT::i32);
3018 
3019     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3020     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3021   }
3022 
3023   if (Model == TLSModel::InitialExec) {
3024     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3025     SDValue TGA = DAG.getTargetGlobalAddress(
3026         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3027     SDValue TGATLS = DAG.getTargetGlobalAddress(
3028         GV, dl, PtrVT, 0,
3029         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3030     SDValue TPOffset;
3031     if (IsPCRel) {
3032       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3033       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3034                              MachinePointerInfo());
3035     } else {
3036       SDValue GOTPtr;
3037       if (is64bit) {
3038         setUsesTOCBasePtr(DAG);
3039         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3040         GOTPtr =
3041             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3042       } else {
3043         if (!TM.isPositionIndependent())
3044           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3045         else if (picLevel == PICLevel::SmallPIC)
3046           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3047         else
3048           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3049       }
3050       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3051     }
3052     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3053   }
3054 
3055   if (Model == TLSModel::GeneralDynamic) {
3056     if (Subtarget.isUsingPCRelativeCalls()) {
3057       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3058                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3059       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3060     }
3061 
3062     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3063     SDValue GOTPtr;
3064     if (is64bit) {
3065       setUsesTOCBasePtr(DAG);
3066       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3067       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3068                                    GOTReg, TGA);
3069     } else {
3070       if (picLevel == PICLevel::SmallPIC)
3071         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3072       else
3073         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3074     }
3075     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3076                        GOTPtr, TGA, TGA);
3077   }
3078 
3079   if (Model == TLSModel::LocalDynamic) {
3080     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3081     SDValue GOTPtr;
3082     if (is64bit) {
3083       setUsesTOCBasePtr(DAG);
3084       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3085       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3086                            GOTReg, TGA);
3087     } else {
3088       if (picLevel == PICLevel::SmallPIC)
3089         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3090       else
3091         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3092     }
3093     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3094                                   PtrVT, GOTPtr, TGA, TGA);
3095     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3096                                       PtrVT, TLSAddr, TGA);
3097     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3098   }
3099 
3100   llvm_unreachable("Unknown TLS model!");
3101 }
3102 
3103 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3104                                               SelectionDAG &DAG) const {
3105   EVT PtrVT = Op.getValueType();
3106   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3107   SDLoc DL(GSDN);
3108   const GlobalValue *GV = GSDN->getGlobal();
3109 
3110   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3111   // The actual address of the GlobalValue is stored in the TOC.
3112   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3113     if (Subtarget.isUsingPCRelativeCalls()) {
3114       EVT Ty = getPointerTy(DAG.getDataLayout());
3115       if (isAccessedAsGotIndirect(Op)) {
3116         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3117                                                 PPCII::MO_PCREL_FLAG |
3118                                                     PPCII::MO_GOT_FLAG);
3119         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3120         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3121                                    MachinePointerInfo());
3122         return Load;
3123       } else {
3124         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3125                                                 PPCII::MO_PCREL_FLAG);
3126         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3127       }
3128     }
3129     setUsesTOCBasePtr(DAG);
3130     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3131     return getTOCEntry(DAG, DL, GA);
3132   }
3133 
3134   unsigned MOHiFlag, MOLoFlag;
3135   bool IsPIC = isPositionIndependent();
3136   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3137 
3138   if (IsPIC && Subtarget.isSVR4ABI()) {
3139     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3140                                             GSDN->getOffset(),
3141                                             PPCII::MO_PIC_FLAG);
3142     return getTOCEntry(DAG, DL, GA);
3143   }
3144 
3145   SDValue GAHi =
3146     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3147   SDValue GALo =
3148     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3149 
3150   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3151 }
3152 
3153 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3154   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3155   SDLoc dl(Op);
3156 
3157   if (Op.getValueType() == MVT::v2i64) {
3158     // When the operands themselves are v2i64 values, we need to do something
3159     // special because VSX has no underlying comparison operations for these.
3160     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3161       // Equality can be handled by casting to the legal type for Altivec
3162       // comparisons, everything else needs to be expanded.
3163       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3164         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3165                  DAG.getSetCC(dl, MVT::v4i32,
3166                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3167                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3168                    CC));
3169       }
3170 
3171       return SDValue();
3172     }
3173 
3174     // We handle most of these in the usual way.
3175     return Op;
3176   }
3177 
3178   // If we're comparing for equality to zero, expose the fact that this is
3179   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3180   // fold the new nodes.
3181   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3182     return V;
3183 
3184   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3185     // Leave comparisons against 0 and -1 alone for now, since they're usually
3186     // optimized.  FIXME: revisit this when we can custom lower all setcc
3187     // optimizations.
3188     if (C->isAllOnesValue() || C->isNullValue())
3189       return SDValue();
3190   }
3191 
3192   // If we have an integer seteq/setne, turn it into a compare against zero
3193   // by xor'ing the rhs with the lhs, which is faster than setting a
3194   // condition register, reading it back out, and masking the correct bit.  The
3195   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3196   // the result to other bit-twiddling opportunities.
3197   EVT LHSVT = Op.getOperand(0).getValueType();
3198   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3199     EVT VT = Op.getValueType();
3200     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3201                                 Op.getOperand(1));
3202     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3203   }
3204   return SDValue();
3205 }
3206 
3207 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3208   SDNode *Node = Op.getNode();
3209   EVT VT = Node->getValueType(0);
3210   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3211   SDValue InChain = Node->getOperand(0);
3212   SDValue VAListPtr = Node->getOperand(1);
3213   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3214   SDLoc dl(Node);
3215 
3216   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3217 
3218   // gpr_index
3219   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3220                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3221   InChain = GprIndex.getValue(1);
3222 
3223   if (VT == MVT::i64) {
3224     // Check if GprIndex is even
3225     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3226                                  DAG.getConstant(1, dl, MVT::i32));
3227     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3228                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3229     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3230                                           DAG.getConstant(1, dl, MVT::i32));
3231     // Align GprIndex to be even if it isn't
3232     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3233                            GprIndex);
3234   }
3235 
3236   // fpr index is 1 byte after gpr
3237   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3238                                DAG.getConstant(1, dl, MVT::i32));
3239 
3240   // fpr
3241   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3242                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3243   InChain = FprIndex.getValue(1);
3244 
3245   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3246                                        DAG.getConstant(8, dl, MVT::i32));
3247 
3248   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3249                                         DAG.getConstant(4, dl, MVT::i32));
3250 
3251   // areas
3252   SDValue OverflowArea =
3253       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3254   InChain = OverflowArea.getValue(1);
3255 
3256   SDValue RegSaveArea =
3257       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3258   InChain = RegSaveArea.getValue(1);
3259 
3260   // select overflow_area if index > 8
3261   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3262                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3263 
3264   // adjustment constant gpr_index * 4/8
3265   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3266                                     VT.isInteger() ? GprIndex : FprIndex,
3267                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3268                                                     MVT::i32));
3269 
3270   // OurReg = RegSaveArea + RegConstant
3271   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3272                                RegConstant);
3273 
3274   // Floating types are 32 bytes into RegSaveArea
3275   if (VT.isFloatingPoint())
3276     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3277                          DAG.getConstant(32, dl, MVT::i32));
3278 
3279   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3280   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3281                                    VT.isInteger() ? GprIndex : FprIndex,
3282                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3283                                                    MVT::i32));
3284 
3285   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3286                               VT.isInteger() ? VAListPtr : FprPtr,
3287                               MachinePointerInfo(SV), MVT::i8);
3288 
3289   // determine if we should load from reg_save_area or overflow_area
3290   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3291 
3292   // increase overflow_area by 4/8 if gpr/fpr > 8
3293   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3294                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3295                                           dl, MVT::i32));
3296 
3297   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3298                              OverflowAreaPlusN);
3299 
3300   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3301                               MachinePointerInfo(), MVT::i32);
3302 
3303   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3304 }
3305 
3306 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3307   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3308 
3309   // We have to copy the entire va_list struct:
3310   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3311   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3312                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3313                        false, true, false, MachinePointerInfo(),
3314                        MachinePointerInfo());
3315 }
3316 
3317 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3318                                                   SelectionDAG &DAG) const {
3319   if (Subtarget.isAIXABI())
3320     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3321 
3322   return Op.getOperand(0);
3323 }
3324 
3325 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3326                                                 SelectionDAG &DAG) const {
3327   if (Subtarget.isAIXABI())
3328     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3329 
3330   SDValue Chain = Op.getOperand(0);
3331   SDValue Trmp = Op.getOperand(1); // trampoline
3332   SDValue FPtr = Op.getOperand(2); // nested function
3333   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3334   SDLoc dl(Op);
3335 
3336   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3337   bool isPPC64 = (PtrVT == MVT::i64);
3338   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3339 
3340   TargetLowering::ArgListTy Args;
3341   TargetLowering::ArgListEntry Entry;
3342 
3343   Entry.Ty = IntPtrTy;
3344   Entry.Node = Trmp; Args.push_back(Entry);
3345 
3346   // TrampSize == (isPPC64 ? 48 : 40);
3347   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3348                                isPPC64 ? MVT::i64 : MVT::i32);
3349   Args.push_back(Entry);
3350 
3351   Entry.Node = FPtr; Args.push_back(Entry);
3352   Entry.Node = Nest; Args.push_back(Entry);
3353 
3354   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3355   TargetLowering::CallLoweringInfo CLI(DAG);
3356   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3357       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3358       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3359 
3360   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3361   return CallResult.second;
3362 }
3363 
3364 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3365   MachineFunction &MF = DAG.getMachineFunction();
3366   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3367   EVT PtrVT = getPointerTy(MF.getDataLayout());
3368 
3369   SDLoc dl(Op);
3370 
3371   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3372     // vastart just stores the address of the VarArgsFrameIndex slot into the
3373     // memory location argument.
3374     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3375     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3376     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3377                         MachinePointerInfo(SV));
3378   }
3379 
3380   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3381   // We suppose the given va_list is already allocated.
3382   //
3383   // typedef struct {
3384   //  char gpr;     /* index into the array of 8 GPRs
3385   //                 * stored in the register save area
3386   //                 * gpr=0 corresponds to r3,
3387   //                 * gpr=1 to r4, etc.
3388   //                 */
3389   //  char fpr;     /* index into the array of 8 FPRs
3390   //                 * stored in the register save area
3391   //                 * fpr=0 corresponds to f1,
3392   //                 * fpr=1 to f2, etc.
3393   //                 */
3394   //  char *overflow_arg_area;
3395   //                /* location on stack that holds
3396   //                 * the next overflow argument
3397   //                 */
3398   //  char *reg_save_area;
3399   //               /* where r3:r10 and f1:f8 (if saved)
3400   //                * are stored
3401   //                */
3402   // } va_list[1];
3403 
3404   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3405   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3406   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3407                                             PtrVT);
3408   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3409                                  PtrVT);
3410 
3411   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3412   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3413 
3414   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3415   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3416 
3417   uint64_t FPROffset = 1;
3418   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3419 
3420   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3421 
3422   // Store first byte : number of int regs
3423   SDValue firstStore =
3424       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3425                         MachinePointerInfo(SV), MVT::i8);
3426   uint64_t nextOffset = FPROffset;
3427   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3428                                   ConstFPROffset);
3429 
3430   // Store second byte : number of float regs
3431   SDValue secondStore =
3432       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3433                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3434   nextOffset += StackOffset;
3435   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3436 
3437   // Store second word : arguments given on stack
3438   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3439                                     MachinePointerInfo(SV, nextOffset));
3440   nextOffset += FrameOffset;
3441   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3442 
3443   // Store third word : arguments given in registers
3444   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3445                       MachinePointerInfo(SV, nextOffset));
3446 }
3447 
3448 /// FPR - The set of FP registers that should be allocated for arguments
3449 /// on Darwin and AIX.
3450 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3451                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3452                                 PPC::F11, PPC::F12, PPC::F13};
3453 
3454 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3455 /// the stack.
3456 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3457                                        unsigned PtrByteSize) {
3458   unsigned ArgSize = ArgVT.getStoreSize();
3459   if (Flags.isByVal())
3460     ArgSize = Flags.getByValSize();
3461 
3462   // Round up to multiples of the pointer size, except for array members,
3463   // which are always packed.
3464   if (!Flags.isInConsecutiveRegs())
3465     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3466 
3467   return ArgSize;
3468 }
3469 
3470 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3471 /// on the stack.
3472 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3473                                          ISD::ArgFlagsTy Flags,
3474                                          unsigned PtrByteSize) {
3475   Align Alignment(PtrByteSize);
3476 
3477   // Altivec parameters are padded to a 16 byte boundary.
3478   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3479       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3480       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3481       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3482     Alignment = Align(16);
3483 
3484   // ByVal parameters are aligned as requested.
3485   if (Flags.isByVal()) {
3486     auto BVAlign = Flags.getNonZeroByValAlign();
3487     if (BVAlign > PtrByteSize) {
3488       if (BVAlign.value() % PtrByteSize != 0)
3489         llvm_unreachable(
3490             "ByVal alignment is not a multiple of the pointer size");
3491 
3492       Alignment = BVAlign;
3493     }
3494   }
3495 
3496   // Array members are always packed to their original alignment.
3497   if (Flags.isInConsecutiveRegs()) {
3498     // If the array member was split into multiple registers, the first
3499     // needs to be aligned to the size of the full type.  (Except for
3500     // ppcf128, which is only aligned as its f64 components.)
3501     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3502       Alignment = Align(OrigVT.getStoreSize());
3503     else
3504       Alignment = Align(ArgVT.getStoreSize());
3505   }
3506 
3507   return Alignment;
3508 }
3509 
3510 /// CalculateStackSlotUsed - Return whether this argument will use its
3511 /// stack slot (instead of being passed in registers).  ArgOffset,
3512 /// AvailableFPRs, and AvailableVRs must hold the current argument
3513 /// position, and will be updated to account for this argument.
3514 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3515                                    unsigned PtrByteSize, unsigned LinkageSize,
3516                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3517                                    unsigned &AvailableFPRs,
3518                                    unsigned &AvailableVRs) {
3519   bool UseMemory = false;
3520 
3521   // Respect alignment of argument on the stack.
3522   Align Alignment =
3523       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3524   ArgOffset = alignTo(ArgOffset, Alignment);
3525   // If there's no space left in the argument save area, we must
3526   // use memory (this check also catches zero-sized arguments).
3527   if (ArgOffset >= LinkageSize + ParamAreaSize)
3528     UseMemory = true;
3529 
3530   // Allocate argument on the stack.
3531   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3532   if (Flags.isInConsecutiveRegsLast())
3533     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3534   // If we overran the argument save area, we must use memory
3535   // (this check catches arguments passed partially in memory)
3536   if (ArgOffset > LinkageSize + ParamAreaSize)
3537     UseMemory = true;
3538 
3539   // However, if the argument is actually passed in an FPR or a VR,
3540   // we don't use memory after all.
3541   if (!Flags.isByVal()) {
3542     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3543       if (AvailableFPRs > 0) {
3544         --AvailableFPRs;
3545         return false;
3546       }
3547     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3548         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3549         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3550         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3551       if (AvailableVRs > 0) {
3552         --AvailableVRs;
3553         return false;
3554       }
3555   }
3556 
3557   return UseMemory;
3558 }
3559 
3560 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3561 /// ensure minimum alignment required for target.
3562 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3563                                      unsigned NumBytes) {
3564   return alignTo(NumBytes, Lowering->getStackAlign());
3565 }
3566 
3567 SDValue PPCTargetLowering::LowerFormalArguments(
3568     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3569     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3570     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3571   if (Subtarget.isAIXABI())
3572     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3573                                     InVals);
3574   if (Subtarget.is64BitELFABI())
3575     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3576                                        InVals);
3577   if (Subtarget.is32BitELFABI())
3578     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3579                                        InVals);
3580 
3581   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3582                                      InVals);
3583 }
3584 
3585 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3586     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3587     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3588     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3589 
3590   // 32-bit SVR4 ABI Stack Frame Layout:
3591   //              +-----------------------------------+
3592   //        +-->  |            Back chain             |
3593   //        |     +-----------------------------------+
3594   //        |     | Floating-point register save area |
3595   //        |     +-----------------------------------+
3596   //        |     |    General register save area     |
3597   //        |     +-----------------------------------+
3598   //        |     |          CR save word             |
3599   //        |     +-----------------------------------+
3600   //        |     |         VRSAVE save word          |
3601   //        |     +-----------------------------------+
3602   //        |     |         Alignment padding         |
3603   //        |     +-----------------------------------+
3604   //        |     |     Vector register save area     |
3605   //        |     +-----------------------------------+
3606   //        |     |       Local variable space        |
3607   //        |     +-----------------------------------+
3608   //        |     |        Parameter list area        |
3609   //        |     +-----------------------------------+
3610   //        |     |           LR save word            |
3611   //        |     +-----------------------------------+
3612   // SP-->  +---  |            Back chain             |
3613   //              +-----------------------------------+
3614   //
3615   // Specifications:
3616   //   System V Application Binary Interface PowerPC Processor Supplement
3617   //   AltiVec Technology Programming Interface Manual
3618 
3619   MachineFunction &MF = DAG.getMachineFunction();
3620   MachineFrameInfo &MFI = MF.getFrameInfo();
3621   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3622 
3623   EVT PtrVT = getPointerTy(MF.getDataLayout());
3624   // Potential tail calls could cause overwriting of argument stack slots.
3625   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3626                        (CallConv == CallingConv::Fast));
3627   const Align PtrAlign(4);
3628 
3629   // Assign locations to all of the incoming arguments.
3630   SmallVector<CCValAssign, 16> ArgLocs;
3631   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3632                  *DAG.getContext());
3633 
3634   // Reserve space for the linkage area on the stack.
3635   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3636   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3637   if (useSoftFloat())
3638     CCInfo.PreAnalyzeFormalArguments(Ins);
3639 
3640   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3641   CCInfo.clearWasPPCF128();
3642 
3643   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3644     CCValAssign &VA = ArgLocs[i];
3645 
3646     // Arguments stored in registers.
3647     if (VA.isRegLoc()) {
3648       const TargetRegisterClass *RC;
3649       EVT ValVT = VA.getValVT();
3650 
3651       switch (ValVT.getSimpleVT().SimpleTy) {
3652         default:
3653           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3654         case MVT::i1:
3655         case MVT::i32:
3656           RC = &PPC::GPRCRegClass;
3657           break;
3658         case MVT::f32:
3659           if (Subtarget.hasP8Vector())
3660             RC = &PPC::VSSRCRegClass;
3661           else if (Subtarget.hasSPE())
3662             RC = &PPC::GPRCRegClass;
3663           else
3664             RC = &PPC::F4RCRegClass;
3665           break;
3666         case MVT::f64:
3667           if (Subtarget.hasVSX())
3668             RC = &PPC::VSFRCRegClass;
3669           else if (Subtarget.hasSPE())
3670             // SPE passes doubles in GPR pairs.
3671             RC = &PPC::GPRCRegClass;
3672           else
3673             RC = &PPC::F8RCRegClass;
3674           break;
3675         case MVT::v16i8:
3676         case MVT::v8i16:
3677         case MVT::v4i32:
3678           RC = &PPC::VRRCRegClass;
3679           break;
3680         case MVT::v4f32:
3681           RC = &PPC::VRRCRegClass;
3682           break;
3683         case MVT::v2f64:
3684         case MVT::v2i64:
3685           RC = &PPC::VRRCRegClass;
3686           break;
3687       }
3688 
3689       SDValue ArgValue;
3690       // Transform the arguments stored in physical registers into
3691       // virtual ones.
3692       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3693         assert(i + 1 < e && "No second half of double precision argument");
3694         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3695         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3696         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3697         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3698         if (!Subtarget.isLittleEndian())
3699           std::swap (ArgValueLo, ArgValueHi);
3700         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3701                                ArgValueHi);
3702       } else {
3703         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3704         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3705                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3706         if (ValVT == MVT::i1)
3707           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3708       }
3709 
3710       InVals.push_back(ArgValue);
3711     } else {
3712       // Argument stored in memory.
3713       assert(VA.isMemLoc());
3714 
3715       // Get the extended size of the argument type in stack
3716       unsigned ArgSize = VA.getLocVT().getStoreSize();
3717       // Get the actual size of the argument type
3718       unsigned ObjSize = VA.getValVT().getStoreSize();
3719       unsigned ArgOffset = VA.getLocMemOffset();
3720       // Stack objects in PPC32 are right justified.
3721       ArgOffset += ArgSize - ObjSize;
3722       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3723 
3724       // Create load nodes to retrieve arguments from the stack.
3725       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3726       InVals.push_back(
3727           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3728     }
3729   }
3730 
3731   // Assign locations to all of the incoming aggregate by value arguments.
3732   // Aggregates passed by value are stored in the local variable space of the
3733   // caller's stack frame, right above the parameter list area.
3734   SmallVector<CCValAssign, 16> ByValArgLocs;
3735   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3736                       ByValArgLocs, *DAG.getContext());
3737 
3738   // Reserve stack space for the allocations in CCInfo.
3739   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3740 
3741   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3742 
3743   // Area that is at least reserved in the caller of this function.
3744   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3745   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3746 
3747   // Set the size that is at least reserved in caller of this function.  Tail
3748   // call optimized function's reserved stack space needs to be aligned so that
3749   // taking the difference between two stack areas will result in an aligned
3750   // stack.
3751   MinReservedArea =
3752       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3753   FuncInfo->setMinReservedArea(MinReservedArea);
3754 
3755   SmallVector<SDValue, 8> MemOps;
3756 
3757   // If the function takes variable number of arguments, make a frame index for
3758   // the start of the first vararg value... for expansion of llvm.va_start.
3759   if (isVarArg) {
3760     static const MCPhysReg GPArgRegs[] = {
3761       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3762       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3763     };
3764     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3765 
3766     static const MCPhysReg FPArgRegs[] = {
3767       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3768       PPC::F8
3769     };
3770     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3771 
3772     if (useSoftFloat() || hasSPE())
3773        NumFPArgRegs = 0;
3774 
3775     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3776     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3777 
3778     // Make room for NumGPArgRegs and NumFPArgRegs.
3779     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3780                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3781 
3782     FuncInfo->setVarArgsStackOffset(
3783       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3784                             CCInfo.getNextStackOffset(), true));
3785 
3786     FuncInfo->setVarArgsFrameIndex(
3787         MFI.CreateStackObject(Depth, Align(8), false));
3788     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3789 
3790     // The fixed integer arguments of a variadic function are stored to the
3791     // VarArgsFrameIndex on the stack so that they may be loaded by
3792     // dereferencing the result of va_next.
3793     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3794       // Get an existing live-in vreg, or add a new one.
3795       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3796       if (!VReg)
3797         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3798 
3799       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3800       SDValue Store =
3801           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3802       MemOps.push_back(Store);
3803       // Increment the address by four for the next argument to store
3804       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3805       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3806     }
3807 
3808     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3809     // is set.
3810     // The double arguments are stored to the VarArgsFrameIndex
3811     // on the stack.
3812     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3813       // Get an existing live-in vreg, or add a new one.
3814       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3815       if (!VReg)
3816         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3817 
3818       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3819       SDValue Store =
3820           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3821       MemOps.push_back(Store);
3822       // Increment the address by eight for the next argument to store
3823       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3824                                          PtrVT);
3825       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3826     }
3827   }
3828 
3829   if (!MemOps.empty())
3830     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3831 
3832   return Chain;
3833 }
3834 
3835 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3836 // value to MVT::i64 and then truncate to the correct register size.
3837 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3838                                              EVT ObjectVT, SelectionDAG &DAG,
3839                                              SDValue ArgVal,
3840                                              const SDLoc &dl) const {
3841   if (Flags.isSExt())
3842     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3843                          DAG.getValueType(ObjectVT));
3844   else if (Flags.isZExt())
3845     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3846                          DAG.getValueType(ObjectVT));
3847 
3848   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3849 }
3850 
3851 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3852     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3853     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3854     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3855   // TODO: add description of PPC stack frame format, or at least some docs.
3856   //
3857   bool isELFv2ABI = Subtarget.isELFv2ABI();
3858   bool isLittleEndian = Subtarget.isLittleEndian();
3859   MachineFunction &MF = DAG.getMachineFunction();
3860   MachineFrameInfo &MFI = MF.getFrameInfo();
3861   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3862 
3863   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3864          "fastcc not supported on varargs functions");
3865 
3866   EVT PtrVT = getPointerTy(MF.getDataLayout());
3867   // Potential tail calls could cause overwriting of argument stack slots.
3868   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3869                        (CallConv == CallingConv::Fast));
3870   unsigned PtrByteSize = 8;
3871   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3872 
3873   static const MCPhysReg GPR[] = {
3874     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3875     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3876   };
3877   static const MCPhysReg VR[] = {
3878     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3879     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3880   };
3881 
3882   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3883   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3884   const unsigned Num_VR_Regs  = array_lengthof(VR);
3885 
3886   // Do a first pass over the arguments to determine whether the ABI
3887   // guarantees that our caller has allocated the parameter save area
3888   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3889   // in the ELFv2 ABI, it is true if this is a vararg function or if
3890   // any parameter is located in a stack slot.
3891 
3892   bool HasParameterArea = !isELFv2ABI || isVarArg;
3893   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3894   unsigned NumBytes = LinkageSize;
3895   unsigned AvailableFPRs = Num_FPR_Regs;
3896   unsigned AvailableVRs = Num_VR_Regs;
3897   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3898     if (Ins[i].Flags.isNest())
3899       continue;
3900 
3901     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3902                                PtrByteSize, LinkageSize, ParamAreaSize,
3903                                NumBytes, AvailableFPRs, AvailableVRs))
3904       HasParameterArea = true;
3905   }
3906 
3907   // Add DAG nodes to load the arguments or copy them out of registers.  On
3908   // entry to a function on PPC, the arguments start after the linkage area,
3909   // although the first ones are often in registers.
3910 
3911   unsigned ArgOffset = LinkageSize;
3912   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3913   SmallVector<SDValue, 8> MemOps;
3914   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3915   unsigned CurArgIdx = 0;
3916   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3917     SDValue ArgVal;
3918     bool needsLoad = false;
3919     EVT ObjectVT = Ins[ArgNo].VT;
3920     EVT OrigVT = Ins[ArgNo].ArgVT;
3921     unsigned ObjSize = ObjectVT.getStoreSize();
3922     unsigned ArgSize = ObjSize;
3923     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3924     if (Ins[ArgNo].isOrigArg()) {
3925       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3926       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3927     }
3928     // We re-align the argument offset for each argument, except when using the
3929     // fast calling convention, when we need to make sure we do that only when
3930     // we'll actually use a stack slot.
3931     unsigned CurArgOffset;
3932     Align Alignment;
3933     auto ComputeArgOffset = [&]() {
3934       /* Respect alignment of argument on the stack.  */
3935       Alignment =
3936           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3937       ArgOffset = alignTo(ArgOffset, Alignment);
3938       CurArgOffset = ArgOffset;
3939     };
3940 
3941     if (CallConv != CallingConv::Fast) {
3942       ComputeArgOffset();
3943 
3944       /* Compute GPR index associated with argument offset.  */
3945       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3946       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3947     }
3948 
3949     // FIXME the codegen can be much improved in some cases.
3950     // We do not have to keep everything in memory.
3951     if (Flags.isByVal()) {
3952       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3953 
3954       if (CallConv == CallingConv::Fast)
3955         ComputeArgOffset();
3956 
3957       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3958       ObjSize = Flags.getByValSize();
3959       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3960       // Empty aggregate parameters do not take up registers.  Examples:
3961       //   struct { } a;
3962       //   union  { } b;
3963       //   int c[0];
3964       // etc.  However, we have to provide a place-holder in InVals, so
3965       // pretend we have an 8-byte item at the current address for that
3966       // purpose.
3967       if (!ObjSize) {
3968         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3969         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3970         InVals.push_back(FIN);
3971         continue;
3972       }
3973 
3974       // Create a stack object covering all stack doublewords occupied
3975       // by the argument.  If the argument is (fully or partially) on
3976       // the stack, or if the argument is fully in registers but the
3977       // caller has allocated the parameter save anyway, we can refer
3978       // directly to the caller's stack frame.  Otherwise, create a
3979       // local copy in our own frame.
3980       int FI;
3981       if (HasParameterArea ||
3982           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3983         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3984       else
3985         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3986       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3987 
3988       // Handle aggregates smaller than 8 bytes.
3989       if (ObjSize < PtrByteSize) {
3990         // The value of the object is its address, which differs from the
3991         // address of the enclosing doubleword on big-endian systems.
3992         SDValue Arg = FIN;
3993         if (!isLittleEndian) {
3994           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3995           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3996         }
3997         InVals.push_back(Arg);
3998 
3999         if (GPR_idx != Num_GPR_Regs) {
4000           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4001           FuncInfo->addLiveInAttr(VReg, Flags);
4002           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4003           SDValue Store;
4004 
4005           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4006             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4007                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4008             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4009                                       MachinePointerInfo(&*FuncArg), ObjType);
4010           } else {
4011             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4012             // store the whole register as-is to the parameter save area
4013             // slot.
4014             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4015                                  MachinePointerInfo(&*FuncArg));
4016           }
4017 
4018           MemOps.push_back(Store);
4019         }
4020         // Whether we copied from a register or not, advance the offset
4021         // into the parameter save area by a full doubleword.
4022         ArgOffset += PtrByteSize;
4023         continue;
4024       }
4025 
4026       // The value of the object is its address, which is the address of
4027       // its first stack doubleword.
4028       InVals.push_back(FIN);
4029 
4030       // Store whatever pieces of the object are in registers to memory.
4031       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4032         if (GPR_idx == Num_GPR_Regs)
4033           break;
4034 
4035         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4036         FuncInfo->addLiveInAttr(VReg, Flags);
4037         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4038         SDValue Addr = FIN;
4039         if (j) {
4040           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4041           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4042         }
4043         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4044                                      MachinePointerInfo(&*FuncArg, j));
4045         MemOps.push_back(Store);
4046         ++GPR_idx;
4047       }
4048       ArgOffset += ArgSize;
4049       continue;
4050     }
4051 
4052     switch (ObjectVT.getSimpleVT().SimpleTy) {
4053     default: llvm_unreachable("Unhandled argument type!");
4054     case MVT::i1:
4055     case MVT::i32:
4056     case MVT::i64:
4057       if (Flags.isNest()) {
4058         // The 'nest' parameter, if any, is passed in R11.
4059         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4060         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4061 
4062         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4063           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4064 
4065         break;
4066       }
4067 
4068       // These can be scalar arguments or elements of an integer array type
4069       // passed directly.  Clang may use those instead of "byval" aggregate
4070       // types to avoid forcing arguments to memory unnecessarily.
4071       if (GPR_idx != Num_GPR_Regs) {
4072         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4073         FuncInfo->addLiveInAttr(VReg, Flags);
4074         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4075 
4076         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4077           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4078           // value to MVT::i64 and then truncate to the correct register size.
4079           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4080       } else {
4081         if (CallConv == CallingConv::Fast)
4082           ComputeArgOffset();
4083 
4084         needsLoad = true;
4085         ArgSize = PtrByteSize;
4086       }
4087       if (CallConv != CallingConv::Fast || needsLoad)
4088         ArgOffset += 8;
4089       break;
4090 
4091     case MVT::f32:
4092     case MVT::f64:
4093       // These can be scalar arguments or elements of a float array type
4094       // passed directly.  The latter are used to implement ELFv2 homogenous
4095       // float aggregates.
4096       if (FPR_idx != Num_FPR_Regs) {
4097         unsigned VReg;
4098 
4099         if (ObjectVT == MVT::f32)
4100           VReg = MF.addLiveIn(FPR[FPR_idx],
4101                               Subtarget.hasP8Vector()
4102                                   ? &PPC::VSSRCRegClass
4103                                   : &PPC::F4RCRegClass);
4104         else
4105           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4106                                                 ? &PPC::VSFRCRegClass
4107                                                 : &PPC::F8RCRegClass);
4108 
4109         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4110         ++FPR_idx;
4111       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4112         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4113         // once we support fp <-> gpr moves.
4114 
4115         // This can only ever happen in the presence of f32 array types,
4116         // since otherwise we never run out of FPRs before running out
4117         // of GPRs.
4118         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4119         FuncInfo->addLiveInAttr(VReg, Flags);
4120         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4121 
4122         if (ObjectVT == MVT::f32) {
4123           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4124             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4125                                  DAG.getConstant(32, dl, MVT::i32));
4126           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4127         }
4128 
4129         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4130       } else {
4131         if (CallConv == CallingConv::Fast)
4132           ComputeArgOffset();
4133 
4134         needsLoad = true;
4135       }
4136 
4137       // When passing an array of floats, the array occupies consecutive
4138       // space in the argument area; only round up to the next doubleword
4139       // at the end of the array.  Otherwise, each float takes 8 bytes.
4140       if (CallConv != CallingConv::Fast || needsLoad) {
4141         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4142         ArgOffset += ArgSize;
4143         if (Flags.isInConsecutiveRegsLast())
4144           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4145       }
4146       break;
4147     case MVT::v4f32:
4148     case MVT::v4i32:
4149     case MVT::v8i16:
4150     case MVT::v16i8:
4151     case MVT::v2f64:
4152     case MVT::v2i64:
4153     case MVT::v1i128:
4154     case MVT::f128:
4155       // These can be scalar arguments or elements of a vector array type
4156       // passed directly.  The latter are used to implement ELFv2 homogenous
4157       // vector aggregates.
4158       if (VR_idx != Num_VR_Regs) {
4159         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4160         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4161         ++VR_idx;
4162       } else {
4163         if (CallConv == CallingConv::Fast)
4164           ComputeArgOffset();
4165         needsLoad = true;
4166       }
4167       if (CallConv != CallingConv::Fast || needsLoad)
4168         ArgOffset += 16;
4169       break;
4170     }
4171 
4172     // We need to load the argument to a virtual register if we determined
4173     // above that we ran out of physical registers of the appropriate type.
4174     if (needsLoad) {
4175       if (ObjSize < ArgSize && !isLittleEndian)
4176         CurArgOffset += ArgSize - ObjSize;
4177       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4178       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4179       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4180     }
4181 
4182     InVals.push_back(ArgVal);
4183   }
4184 
4185   // Area that is at least reserved in the caller of this function.
4186   unsigned MinReservedArea;
4187   if (HasParameterArea)
4188     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4189   else
4190     MinReservedArea = LinkageSize;
4191 
4192   // Set the size that is at least reserved in caller of this function.  Tail
4193   // call optimized functions' reserved stack space needs to be aligned so that
4194   // taking the difference between two stack areas will result in an aligned
4195   // stack.
4196   MinReservedArea =
4197       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4198   FuncInfo->setMinReservedArea(MinReservedArea);
4199 
4200   // If the function takes variable number of arguments, make a frame index for
4201   // the start of the first vararg value... for expansion of llvm.va_start.
4202   // On ELFv2ABI spec, it writes:
4203   // C programs that are intended to be *portable* across different compilers
4204   // and architectures must use the header file <stdarg.h> to deal with variable
4205   // argument lists.
4206   if (isVarArg && MFI.hasVAStart()) {
4207     int Depth = ArgOffset;
4208 
4209     FuncInfo->setVarArgsFrameIndex(
4210       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4211     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4212 
4213     // If this function is vararg, store any remaining integer argument regs
4214     // to their spots on the stack so that they may be loaded by dereferencing
4215     // the result of va_next.
4216     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4217          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4218       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4219       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4220       SDValue Store =
4221           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4222       MemOps.push_back(Store);
4223       // Increment the address by four for the next argument to store
4224       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4225       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4226     }
4227   }
4228 
4229   if (!MemOps.empty())
4230     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4231 
4232   return Chain;
4233 }
4234 
4235 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4236     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4237     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4238     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4239   // TODO: add description of PPC stack frame format, or at least some docs.
4240   //
4241   MachineFunction &MF = DAG.getMachineFunction();
4242   MachineFrameInfo &MFI = MF.getFrameInfo();
4243   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4244 
4245   EVT PtrVT = getPointerTy(MF.getDataLayout());
4246   bool isPPC64 = PtrVT == MVT::i64;
4247   // Potential tail calls could cause overwriting of argument stack slots.
4248   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4249                        (CallConv == CallingConv::Fast));
4250   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4251   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4252   unsigned ArgOffset = LinkageSize;
4253   // Area that is at least reserved in caller of this function.
4254   unsigned MinReservedArea = ArgOffset;
4255 
4256   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4257     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4258     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4259   };
4260   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4261     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4262     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4263   };
4264   static const MCPhysReg VR[] = {
4265     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4266     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4267   };
4268 
4269   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4270   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4271   const unsigned Num_VR_Regs  = array_lengthof( VR);
4272 
4273   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4274 
4275   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4276 
4277   // In 32-bit non-varargs functions, the stack space for vectors is after the
4278   // stack space for non-vectors.  We do not use this space unless we have
4279   // too many vectors to fit in registers, something that only occurs in
4280   // constructed examples:), but we have to walk the arglist to figure
4281   // that out...for the pathological case, compute VecArgOffset as the
4282   // start of the vector parameter area.  Computing VecArgOffset is the
4283   // entire point of the following loop.
4284   unsigned VecArgOffset = ArgOffset;
4285   if (!isVarArg && !isPPC64) {
4286     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4287          ++ArgNo) {
4288       EVT ObjectVT = Ins[ArgNo].VT;
4289       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4290 
4291       if (Flags.isByVal()) {
4292         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4293         unsigned ObjSize = Flags.getByValSize();
4294         unsigned ArgSize =
4295                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4296         VecArgOffset += ArgSize;
4297         continue;
4298       }
4299 
4300       switch(ObjectVT.getSimpleVT().SimpleTy) {
4301       default: llvm_unreachable("Unhandled argument type!");
4302       case MVT::i1:
4303       case MVT::i32:
4304       case MVT::f32:
4305         VecArgOffset += 4;
4306         break;
4307       case MVT::i64:  // PPC64
4308       case MVT::f64:
4309         // FIXME: We are guaranteed to be !isPPC64 at this point.
4310         // Does MVT::i64 apply?
4311         VecArgOffset += 8;
4312         break;
4313       case MVT::v4f32:
4314       case MVT::v4i32:
4315       case MVT::v8i16:
4316       case MVT::v16i8:
4317         // Nothing to do, we're only looking at Nonvector args here.
4318         break;
4319       }
4320     }
4321   }
4322   // We've found where the vector parameter area in memory is.  Skip the
4323   // first 12 parameters; these don't use that memory.
4324   VecArgOffset = ((VecArgOffset+15)/16)*16;
4325   VecArgOffset += 12*16;
4326 
4327   // Add DAG nodes to load the arguments or copy them out of registers.  On
4328   // entry to a function on PPC, the arguments start after the linkage area,
4329   // although the first ones are often in registers.
4330 
4331   SmallVector<SDValue, 8> MemOps;
4332   unsigned nAltivecParamsAtEnd = 0;
4333   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4334   unsigned CurArgIdx = 0;
4335   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4336     SDValue ArgVal;
4337     bool needsLoad = false;
4338     EVT ObjectVT = Ins[ArgNo].VT;
4339     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4340     unsigned ArgSize = ObjSize;
4341     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4342     if (Ins[ArgNo].isOrigArg()) {
4343       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4344       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4345     }
4346     unsigned CurArgOffset = ArgOffset;
4347 
4348     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4349     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4350         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4351       if (isVarArg || isPPC64) {
4352         MinReservedArea = ((MinReservedArea+15)/16)*16;
4353         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4354                                                   Flags,
4355                                                   PtrByteSize);
4356       } else  nAltivecParamsAtEnd++;
4357     } else
4358       // Calculate min reserved area.
4359       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4360                                                 Flags,
4361                                                 PtrByteSize);
4362 
4363     // FIXME the codegen can be much improved in some cases.
4364     // We do not have to keep everything in memory.
4365     if (Flags.isByVal()) {
4366       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4367 
4368       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4369       ObjSize = Flags.getByValSize();
4370       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4371       // Objects of size 1 and 2 are right justified, everything else is
4372       // left justified.  This means the memory address is adjusted forwards.
4373       if (ObjSize==1 || ObjSize==2) {
4374         CurArgOffset = CurArgOffset + (4 - ObjSize);
4375       }
4376       // The value of the object is its address.
4377       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4378       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4379       InVals.push_back(FIN);
4380       if (ObjSize==1 || ObjSize==2) {
4381         if (GPR_idx != Num_GPR_Regs) {
4382           unsigned VReg;
4383           if (isPPC64)
4384             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4385           else
4386             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4387           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4388           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4389           SDValue Store =
4390               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4391                                 MachinePointerInfo(&*FuncArg), ObjType);
4392           MemOps.push_back(Store);
4393           ++GPR_idx;
4394         }
4395 
4396         ArgOffset += PtrByteSize;
4397 
4398         continue;
4399       }
4400       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4401         // Store whatever pieces of the object are in registers
4402         // to memory.  ArgOffset will be the address of the beginning
4403         // of the object.
4404         if (GPR_idx != Num_GPR_Regs) {
4405           unsigned VReg;
4406           if (isPPC64)
4407             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4408           else
4409             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4410           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4411           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4412           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4413           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4414                                        MachinePointerInfo(&*FuncArg, j));
4415           MemOps.push_back(Store);
4416           ++GPR_idx;
4417           ArgOffset += PtrByteSize;
4418         } else {
4419           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4420           break;
4421         }
4422       }
4423       continue;
4424     }
4425 
4426     switch (ObjectVT.getSimpleVT().SimpleTy) {
4427     default: llvm_unreachable("Unhandled argument type!");
4428     case MVT::i1:
4429     case MVT::i32:
4430       if (!isPPC64) {
4431         if (GPR_idx != Num_GPR_Regs) {
4432           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4433           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4434 
4435           if (ObjectVT == MVT::i1)
4436             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4437 
4438           ++GPR_idx;
4439         } else {
4440           needsLoad = true;
4441           ArgSize = PtrByteSize;
4442         }
4443         // All int arguments reserve stack space in the Darwin ABI.
4444         ArgOffset += PtrByteSize;
4445         break;
4446       }
4447       LLVM_FALLTHROUGH;
4448     case MVT::i64:  // PPC64
4449       if (GPR_idx != Num_GPR_Regs) {
4450         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4451         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4452 
4453         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4454           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4455           // value to MVT::i64 and then truncate to the correct register size.
4456           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4457 
4458         ++GPR_idx;
4459       } else {
4460         needsLoad = true;
4461         ArgSize = PtrByteSize;
4462       }
4463       // All int arguments reserve stack space in the Darwin ABI.
4464       ArgOffset += 8;
4465       break;
4466 
4467     case MVT::f32:
4468     case MVT::f64:
4469       // Every 4 bytes of argument space consumes one of the GPRs available for
4470       // argument passing.
4471       if (GPR_idx != Num_GPR_Regs) {
4472         ++GPR_idx;
4473         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4474           ++GPR_idx;
4475       }
4476       if (FPR_idx != Num_FPR_Regs) {
4477         unsigned VReg;
4478 
4479         if (ObjectVT == MVT::f32)
4480           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4481         else
4482           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4483 
4484         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4485         ++FPR_idx;
4486       } else {
4487         needsLoad = true;
4488       }
4489 
4490       // All FP arguments reserve stack space in the Darwin ABI.
4491       ArgOffset += isPPC64 ? 8 : ObjSize;
4492       break;
4493     case MVT::v4f32:
4494     case MVT::v4i32:
4495     case MVT::v8i16:
4496     case MVT::v16i8:
4497       // Note that vector arguments in registers don't reserve stack space,
4498       // except in varargs functions.
4499       if (VR_idx != Num_VR_Regs) {
4500         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4501         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4502         if (isVarArg) {
4503           while ((ArgOffset % 16) != 0) {
4504             ArgOffset += PtrByteSize;
4505             if (GPR_idx != Num_GPR_Regs)
4506               GPR_idx++;
4507           }
4508           ArgOffset += 16;
4509           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4510         }
4511         ++VR_idx;
4512       } else {
4513         if (!isVarArg && !isPPC64) {
4514           // Vectors go after all the nonvectors.
4515           CurArgOffset = VecArgOffset;
4516           VecArgOffset += 16;
4517         } else {
4518           // Vectors are aligned.
4519           ArgOffset = ((ArgOffset+15)/16)*16;
4520           CurArgOffset = ArgOffset;
4521           ArgOffset += 16;
4522         }
4523         needsLoad = true;
4524       }
4525       break;
4526     }
4527 
4528     // We need to load the argument to a virtual register if we determined above
4529     // that we ran out of physical registers of the appropriate type.
4530     if (needsLoad) {
4531       int FI = MFI.CreateFixedObject(ObjSize,
4532                                      CurArgOffset + (ArgSize - ObjSize),
4533                                      isImmutable);
4534       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4535       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4536     }
4537 
4538     InVals.push_back(ArgVal);
4539   }
4540 
4541   // Allow for Altivec parameters at the end, if needed.
4542   if (nAltivecParamsAtEnd) {
4543     MinReservedArea = ((MinReservedArea+15)/16)*16;
4544     MinReservedArea += 16*nAltivecParamsAtEnd;
4545   }
4546 
4547   // Area that is at least reserved in the caller of this function.
4548   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4549 
4550   // Set the size that is at least reserved in caller of this function.  Tail
4551   // call optimized functions' reserved stack space needs to be aligned so that
4552   // taking the difference between two stack areas will result in an aligned
4553   // stack.
4554   MinReservedArea =
4555       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4556   FuncInfo->setMinReservedArea(MinReservedArea);
4557 
4558   // If the function takes variable number of arguments, make a frame index for
4559   // the start of the first vararg value... for expansion of llvm.va_start.
4560   if (isVarArg) {
4561     int Depth = ArgOffset;
4562 
4563     FuncInfo->setVarArgsFrameIndex(
4564       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4565                             Depth, true));
4566     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4567 
4568     // If this function is vararg, store any remaining integer argument regs
4569     // to their spots on the stack so that they may be loaded by dereferencing
4570     // the result of va_next.
4571     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4572       unsigned VReg;
4573 
4574       if (isPPC64)
4575         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4576       else
4577         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4578 
4579       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4580       SDValue Store =
4581           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4582       MemOps.push_back(Store);
4583       // Increment the address by four for the next argument to store
4584       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4585       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4586     }
4587   }
4588 
4589   if (!MemOps.empty())
4590     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4591 
4592   return Chain;
4593 }
4594 
4595 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4596 /// adjusted to accommodate the arguments for the tailcall.
4597 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4598                                    unsigned ParamSize) {
4599 
4600   if (!isTailCall) return 0;
4601 
4602   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4603   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4604   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4605   // Remember only if the new adjustment is bigger.
4606   if (SPDiff < FI->getTailCallSPDelta())
4607     FI->setTailCallSPDelta(SPDiff);
4608 
4609   return SPDiff;
4610 }
4611 
4612 static bool isFunctionGlobalAddress(SDValue Callee);
4613 
4614 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4615                               const TargetMachine &TM) {
4616   // It does not make sense to call callsShareTOCBase() with a caller that
4617   // is PC Relative since PC Relative callers do not have a TOC.
4618 #ifndef NDEBUG
4619   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4620   assert(!STICaller->isUsingPCRelativeCalls() &&
4621          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4622 #endif
4623 
4624   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4625   // don't have enough information to determine if the caller and callee share
4626   // the same  TOC base, so we have to pessimistically assume they don't for
4627   // correctness.
4628   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4629   if (!G)
4630     return false;
4631 
4632   const GlobalValue *GV = G->getGlobal();
4633 
4634   // If the callee is preemptable, then the static linker will use a plt-stub
4635   // which saves the toc to the stack, and needs a nop after the call
4636   // instruction to convert to a toc-restore.
4637   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4638     return false;
4639 
4640   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4641   // We may need a TOC restore in the situation where the caller requires a
4642   // valid TOC but the callee is PC Relative and does not.
4643   const Function *F = dyn_cast<Function>(GV);
4644   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4645 
4646   // If we have an Alias we can try to get the function from there.
4647   if (Alias) {
4648     const GlobalObject *GlobalObj = Alias->getBaseObject();
4649     F = dyn_cast<Function>(GlobalObj);
4650   }
4651 
4652   // If we still have no valid function pointer we do not have enough
4653   // information to determine if the callee uses PC Relative calls so we must
4654   // assume that it does.
4655   if (!F)
4656     return false;
4657 
4658   // If the callee uses PC Relative we cannot guarantee that the callee won't
4659   // clobber the TOC of the caller and so we must assume that the two
4660   // functions do not share a TOC base.
4661   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4662   if (STICallee->isUsingPCRelativeCalls())
4663     return false;
4664 
4665   // The medium and large code models are expected to provide a sufficiently
4666   // large TOC to provide all data addressing needs of a module with a
4667   // single TOC.
4668   if (CodeModel::Medium == TM.getCodeModel() ||
4669       CodeModel::Large == TM.getCodeModel())
4670     return true;
4671 
4672   // Otherwise we need to ensure callee and caller are in the same section,
4673   // since the linker may allocate multiple TOCs, and we don't know which
4674   // sections will belong to the same TOC base.
4675   if (!GV->isStrongDefinitionForLinker())
4676     return false;
4677 
4678   // Any explicitly-specified sections and section prefixes must also match.
4679   // Also, if we're using -ffunction-sections, then each function is always in
4680   // a different section (the same is true for COMDAT functions).
4681   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4682       GV->getSection() != Caller->getSection())
4683     return false;
4684   if (const auto *F = dyn_cast<Function>(GV)) {
4685     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4686       return false;
4687   }
4688 
4689   return true;
4690 }
4691 
4692 static bool
4693 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4694                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4695   assert(Subtarget.is64BitELFABI());
4696 
4697   const unsigned PtrByteSize = 8;
4698   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4699 
4700   static const MCPhysReg GPR[] = {
4701     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4702     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4703   };
4704   static const MCPhysReg VR[] = {
4705     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4706     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4707   };
4708 
4709   const unsigned NumGPRs = array_lengthof(GPR);
4710   const unsigned NumFPRs = 13;
4711   const unsigned NumVRs = array_lengthof(VR);
4712   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4713 
4714   unsigned NumBytes = LinkageSize;
4715   unsigned AvailableFPRs = NumFPRs;
4716   unsigned AvailableVRs = NumVRs;
4717 
4718   for (const ISD::OutputArg& Param : Outs) {
4719     if (Param.Flags.isNest()) continue;
4720 
4721     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4722                                LinkageSize, ParamAreaSize, NumBytes,
4723                                AvailableFPRs, AvailableVRs))
4724       return true;
4725   }
4726   return false;
4727 }
4728 
4729 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4730   if (CB.arg_size() != CallerFn->arg_size())
4731     return false;
4732 
4733   auto CalleeArgIter = CB.arg_begin();
4734   auto CalleeArgEnd = CB.arg_end();
4735   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4736 
4737   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4738     const Value* CalleeArg = *CalleeArgIter;
4739     const Value* CallerArg = &(*CallerArgIter);
4740     if (CalleeArg == CallerArg)
4741       continue;
4742 
4743     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4744     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4745     //      }
4746     // 1st argument of callee is undef and has the same type as caller.
4747     if (CalleeArg->getType() == CallerArg->getType() &&
4748         isa<UndefValue>(CalleeArg))
4749       continue;
4750 
4751     return false;
4752   }
4753 
4754   return true;
4755 }
4756 
4757 // Returns true if TCO is possible between the callers and callees
4758 // calling conventions.
4759 static bool
4760 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4761                                     CallingConv::ID CalleeCC) {
4762   // Tail calls are possible with fastcc and ccc.
4763   auto isTailCallableCC  = [] (CallingConv::ID CC){
4764       return  CC == CallingConv::C || CC == CallingConv::Fast;
4765   };
4766   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4767     return false;
4768 
4769   // We can safely tail call both fastcc and ccc callees from a c calling
4770   // convention caller. If the caller is fastcc, we may have less stack space
4771   // than a non-fastcc caller with the same signature so disable tail-calls in
4772   // that case.
4773   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4774 }
4775 
4776 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4777     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4778     const SmallVectorImpl<ISD::OutputArg> &Outs,
4779     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4780   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4781 
4782   if (DisableSCO && !TailCallOpt) return false;
4783 
4784   // Variadic argument functions are not supported.
4785   if (isVarArg) return false;
4786 
4787   auto &Caller = DAG.getMachineFunction().getFunction();
4788   // Check that the calling conventions are compatible for tco.
4789   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4790     return false;
4791 
4792   // Caller contains any byval parameter is not supported.
4793   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4794     return false;
4795 
4796   // Callee contains any byval parameter is not supported, too.
4797   // Note: This is a quick work around, because in some cases, e.g.
4798   // caller's stack size > callee's stack size, we are still able to apply
4799   // sibling call optimization. For example, gcc is able to do SCO for caller1
4800   // in the following example, but not for caller2.
4801   //   struct test {
4802   //     long int a;
4803   //     char ary[56];
4804   //   } gTest;
4805   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4806   //     b->a = v.a;
4807   //     return 0;
4808   //   }
4809   //   void caller1(struct test a, struct test c, struct test *b) {
4810   //     callee(gTest, b); }
4811   //   void caller2(struct test *b) { callee(gTest, b); }
4812   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4813     return false;
4814 
4815   // If callee and caller use different calling conventions, we cannot pass
4816   // parameters on stack since offsets for the parameter area may be different.
4817   if (Caller.getCallingConv() != CalleeCC &&
4818       needStackSlotPassParameters(Subtarget, Outs))
4819     return false;
4820 
4821   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4822   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4823   // callee potentially have different TOC bases then we cannot tail call since
4824   // we need to restore the TOC pointer after the call.
4825   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4826   // We cannot guarantee this for indirect calls or calls to external functions.
4827   // When PC-Relative addressing is used, the concept of the TOC is no longer
4828   // applicable so this check is not required.
4829   // Check first for indirect calls.
4830   if (!Subtarget.isUsingPCRelativeCalls() &&
4831       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4832     return false;
4833 
4834   // Check if we share the TOC base.
4835   if (!Subtarget.isUsingPCRelativeCalls() &&
4836       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4837     return false;
4838 
4839   // TCO allows altering callee ABI, so we don't have to check further.
4840   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4841     return true;
4842 
4843   if (DisableSCO) return false;
4844 
4845   // If callee use the same argument list that caller is using, then we can
4846   // apply SCO on this case. If it is not, then we need to check if callee needs
4847   // stack for passing arguments.
4848   // PC Relative tail calls may not have a CallBase.
4849   // If there is no CallBase we cannot verify if we have the same argument
4850   // list so assume that we don't have the same argument list.
4851   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4852       needStackSlotPassParameters(Subtarget, Outs))
4853     return false;
4854   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4855     return false;
4856 
4857   return true;
4858 }
4859 
4860 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4861 /// for tail call optimization. Targets which want to do tail call
4862 /// optimization should implement this function.
4863 bool
4864 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4865                                                      CallingConv::ID CalleeCC,
4866                                                      bool isVarArg,
4867                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4868                                                      SelectionDAG& DAG) const {
4869   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4870     return false;
4871 
4872   // Variable argument functions are not supported.
4873   if (isVarArg)
4874     return false;
4875 
4876   MachineFunction &MF = DAG.getMachineFunction();
4877   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4878   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4879     // Functions containing by val parameters are not supported.
4880     for (unsigned i = 0; i != Ins.size(); i++) {
4881        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4882        if (Flags.isByVal()) return false;
4883     }
4884 
4885     // Non-PIC/GOT tail calls are supported.
4886     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4887       return true;
4888 
4889     // At the moment we can only do local tail calls (in same module, hidden
4890     // or protected) if we are generating PIC.
4891     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4892       return G->getGlobal()->hasHiddenVisibility()
4893           || G->getGlobal()->hasProtectedVisibility();
4894   }
4895 
4896   return false;
4897 }
4898 
4899 /// isCallCompatibleAddress - Return the immediate to use if the specified
4900 /// 32-bit value is representable in the immediate field of a BxA instruction.
4901 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4902   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4903   if (!C) return nullptr;
4904 
4905   int Addr = C->getZExtValue();
4906   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4907       SignExtend32<26>(Addr) != Addr)
4908     return nullptr;  // Top 6 bits have to be sext of immediate.
4909 
4910   return DAG
4911       .getConstant(
4912           (int)C->getZExtValue() >> 2, SDLoc(Op),
4913           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4914       .getNode();
4915 }
4916 
4917 namespace {
4918 
4919 struct TailCallArgumentInfo {
4920   SDValue Arg;
4921   SDValue FrameIdxOp;
4922   int FrameIdx = 0;
4923 
4924   TailCallArgumentInfo() = default;
4925 };
4926 
4927 } // end anonymous namespace
4928 
4929 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4930 static void StoreTailCallArgumentsToStackSlot(
4931     SelectionDAG &DAG, SDValue Chain,
4932     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4933     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4934   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4935     SDValue Arg = TailCallArgs[i].Arg;
4936     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4937     int FI = TailCallArgs[i].FrameIdx;
4938     // Store relative to framepointer.
4939     MemOpChains.push_back(DAG.getStore(
4940         Chain, dl, Arg, FIN,
4941         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4942   }
4943 }
4944 
4945 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4946 /// the appropriate stack slot for the tail call optimized function call.
4947 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4948                                              SDValue OldRetAddr, SDValue OldFP,
4949                                              int SPDiff, const SDLoc &dl) {
4950   if (SPDiff) {
4951     // Calculate the new stack slot for the return address.
4952     MachineFunction &MF = DAG.getMachineFunction();
4953     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4954     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4955     bool isPPC64 = Subtarget.isPPC64();
4956     int SlotSize = isPPC64 ? 8 : 4;
4957     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4958     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4959                                                          NewRetAddrLoc, true);
4960     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4961     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4962     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4963                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4964   }
4965   return Chain;
4966 }
4967 
4968 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4969 /// the position of the argument.
4970 static void
4971 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4972                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4973                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4974   int Offset = ArgOffset + SPDiff;
4975   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4976   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4977   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4978   SDValue FIN = DAG.getFrameIndex(FI, VT);
4979   TailCallArgumentInfo Info;
4980   Info.Arg = Arg;
4981   Info.FrameIdxOp = FIN;
4982   Info.FrameIdx = FI;
4983   TailCallArguments.push_back(Info);
4984 }
4985 
4986 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4987 /// stack slot. Returns the chain as result and the loaded frame pointers in
4988 /// LROpOut/FPOpout. Used when tail calling.
4989 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4990     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4991     SDValue &FPOpOut, const SDLoc &dl) const {
4992   if (SPDiff) {
4993     // Load the LR and FP stack slot for later adjusting.
4994     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4995     LROpOut = getReturnAddrFrameIndex(DAG);
4996     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4997     Chain = SDValue(LROpOut.getNode(), 1);
4998   }
4999   return Chain;
5000 }
5001 
5002 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5003 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5004 /// specified by the specific parameter attribute. The copy will be passed as
5005 /// a byval function parameter.
5006 /// Sometimes what we are copying is the end of a larger object, the part that
5007 /// does not fit in registers.
5008 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5009                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5010                                          SelectionDAG &DAG, const SDLoc &dl) {
5011   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5012   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5013                        Flags.getNonZeroByValAlign(), false, false, false,
5014                        MachinePointerInfo(), MachinePointerInfo());
5015 }
5016 
5017 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5018 /// tail calls.
5019 static void LowerMemOpCallTo(
5020     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5021     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5022     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5023     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5024   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5025   if (!isTailCall) {
5026     if (isVector) {
5027       SDValue StackPtr;
5028       if (isPPC64)
5029         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5030       else
5031         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5032       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5033                            DAG.getConstant(ArgOffset, dl, PtrVT));
5034     }
5035     MemOpChains.push_back(
5036         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5037     // Calculate and remember argument location.
5038   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5039                                   TailCallArguments);
5040 }
5041 
5042 static void
5043 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5044                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5045                 SDValue FPOp,
5046                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5047   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5048   // might overwrite each other in case of tail call optimization.
5049   SmallVector<SDValue, 8> MemOpChains2;
5050   // Do not flag preceding copytoreg stuff together with the following stuff.
5051   InFlag = SDValue();
5052   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5053                                     MemOpChains2, dl);
5054   if (!MemOpChains2.empty())
5055     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5056 
5057   // Store the return address to the appropriate stack slot.
5058   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5059 
5060   // Emit callseq_end just before tailcall node.
5061   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5062                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5063   InFlag = Chain.getValue(1);
5064 }
5065 
5066 // Is this global address that of a function that can be called by name? (as
5067 // opposed to something that must hold a descriptor for an indirect call).
5068 static bool isFunctionGlobalAddress(SDValue Callee) {
5069   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5070     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5071         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5072       return false;
5073 
5074     return G->getGlobal()->getValueType()->isFunctionTy();
5075   }
5076 
5077   return false;
5078 }
5079 
5080 SDValue PPCTargetLowering::LowerCallResult(
5081     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5082     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5083     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5084   SmallVector<CCValAssign, 16> RVLocs;
5085   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5086                     *DAG.getContext());
5087 
5088   CCRetInfo.AnalyzeCallResult(
5089       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5090                ? RetCC_PPC_Cold
5091                : RetCC_PPC);
5092 
5093   // Copy all of the result registers out of their specified physreg.
5094   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5095     CCValAssign &VA = RVLocs[i];
5096     assert(VA.isRegLoc() && "Can only return in registers!");
5097 
5098     SDValue Val;
5099 
5100     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5101       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5102                                       InFlag);
5103       Chain = Lo.getValue(1);
5104       InFlag = Lo.getValue(2);
5105       VA = RVLocs[++i]; // skip ahead to next loc
5106       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5107                                       InFlag);
5108       Chain = Hi.getValue(1);
5109       InFlag = Hi.getValue(2);
5110       if (!Subtarget.isLittleEndian())
5111         std::swap (Lo, Hi);
5112       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5113     } else {
5114       Val = DAG.getCopyFromReg(Chain, dl,
5115                                VA.getLocReg(), VA.getLocVT(), InFlag);
5116       Chain = Val.getValue(1);
5117       InFlag = Val.getValue(2);
5118     }
5119 
5120     switch (VA.getLocInfo()) {
5121     default: llvm_unreachable("Unknown loc info!");
5122     case CCValAssign::Full: break;
5123     case CCValAssign::AExt:
5124       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5125       break;
5126     case CCValAssign::ZExt:
5127       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5128                         DAG.getValueType(VA.getValVT()));
5129       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5130       break;
5131     case CCValAssign::SExt:
5132       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5133                         DAG.getValueType(VA.getValVT()));
5134       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5135       break;
5136     }
5137 
5138     InVals.push_back(Val);
5139   }
5140 
5141   return Chain;
5142 }
5143 
5144 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5145                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5146   // PatchPoint calls are not indirect.
5147   if (isPatchPoint)
5148     return false;
5149 
5150   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5151     return false;
5152 
5153   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5154   // becuase the immediate function pointer points to a descriptor instead of
5155   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5156   // pointer immediate points to the global entry point, while the BLA would
5157   // need to jump to the local entry point (see rL211174).
5158   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5159       isBLACompatibleAddress(Callee, DAG))
5160     return false;
5161 
5162   return true;
5163 }
5164 
5165 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5166 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5167   return Subtarget.isAIXABI() ||
5168          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5169 }
5170 
5171 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5172                               const Function &Caller,
5173                               const SDValue &Callee,
5174                               const PPCSubtarget &Subtarget,
5175                               const TargetMachine &TM) {
5176   if (CFlags.IsTailCall)
5177     return PPCISD::TC_RETURN;
5178 
5179   // This is a call through a function pointer.
5180   if (CFlags.IsIndirect) {
5181     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5182     // indirect calls. The save of the caller's TOC pointer to the stack will be
5183     // inserted into the DAG as part of call lowering. The restore of the TOC
5184     // pointer is modeled by using a pseudo instruction for the call opcode that
5185     // represents the 2 instruction sequence of an indirect branch and link,
5186     // immediately followed by a load of the TOC pointer from the the stack save
5187     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5188     // as it is not saved or used.
5189     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5190                                                : PPCISD::BCTRL;
5191   }
5192 
5193   if (Subtarget.isUsingPCRelativeCalls()) {
5194     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5195     return PPCISD::CALL_NOTOC;
5196   }
5197 
5198   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5199   // immediately following the call instruction if the caller and callee may
5200   // have different TOC bases. At link time if the linker determines the calls
5201   // may not share a TOC base, the call is redirected to a trampoline inserted
5202   // by the linker. The trampoline will (among other things) save the callers
5203   // TOC pointer at an ABI designated offset in the linkage area and the linker
5204   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5205   // into gpr2.
5206   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5207     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5208                                                   : PPCISD::CALL_NOP;
5209 
5210   return PPCISD::CALL;
5211 }
5212 
5213 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5214                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5215   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5216     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5217       return SDValue(Dest, 0);
5218 
5219   // Returns true if the callee is local, and false otherwise.
5220   auto isLocalCallee = [&]() {
5221     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5222     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5223     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5224 
5225     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5226            !dyn_cast_or_null<GlobalIFunc>(GV);
5227   };
5228 
5229   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5230   // a static relocation model causes some versions of GNU LD (2.17.50, at
5231   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5232   // built with secure-PLT.
5233   bool UsePlt =
5234       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5235       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5236 
5237   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5238     const TargetMachine &TM = Subtarget.getTargetMachine();
5239     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5240     MCSymbolXCOFF *S =
5241         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5242 
5243     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5244     return DAG.getMCSymbol(S, PtrVT);
5245   };
5246 
5247   if (isFunctionGlobalAddress(Callee)) {
5248     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5249 
5250     if (Subtarget.isAIXABI()) {
5251       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5252       return getAIXFuncEntryPointSymbolSDNode(GV);
5253     }
5254     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5255                                       UsePlt ? PPCII::MO_PLT : 0);
5256   }
5257 
5258   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5259     const char *SymName = S->getSymbol();
5260     if (Subtarget.isAIXABI()) {
5261       // If there exists a user-declared function whose name is the same as the
5262       // ExternalSymbol's, then we pick up the user-declared version.
5263       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5264       if (const Function *F =
5265               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5266         return getAIXFuncEntryPointSymbolSDNode(F);
5267 
5268       // On AIX, direct function calls reference the symbol for the function's
5269       // entry point, which is named by prepending a "." before the function's
5270       // C-linkage name. A Qualname is returned here because an external
5271       // function entry point is a csect with XTY_ER property.
5272       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5273         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5274         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5275             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5276             SectionKind::getMetadata());
5277         return Sec->getQualNameSymbol();
5278       };
5279 
5280       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5281     }
5282     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5283                                        UsePlt ? PPCII::MO_PLT : 0);
5284   }
5285 
5286   // No transformation needed.
5287   assert(Callee.getNode() && "What no callee?");
5288   return Callee;
5289 }
5290 
5291 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5292   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5293          "Expected a CALLSEQ_STARTSDNode.");
5294 
5295   // The last operand is the chain, except when the node has glue. If the node
5296   // has glue, then the last operand is the glue, and the chain is the second
5297   // last operand.
5298   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5299   if (LastValue.getValueType() != MVT::Glue)
5300     return LastValue;
5301 
5302   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5303 }
5304 
5305 // Creates the node that moves a functions address into the count register
5306 // to prepare for an indirect call instruction.
5307 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5308                                 SDValue &Glue, SDValue &Chain,
5309                                 const SDLoc &dl) {
5310   SDValue MTCTROps[] = {Chain, Callee, Glue};
5311   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5312   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5313                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5314   // The glue is the second value produced.
5315   Glue = Chain.getValue(1);
5316 }
5317 
5318 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5319                                           SDValue &Glue, SDValue &Chain,
5320                                           SDValue CallSeqStart,
5321                                           const CallBase *CB, const SDLoc &dl,
5322                                           bool hasNest,
5323                                           const PPCSubtarget &Subtarget) {
5324   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5325   // entry point, but to the function descriptor (the function entry point
5326   // address is part of the function descriptor though).
5327   // The function descriptor is a three doubleword structure with the
5328   // following fields: function entry point, TOC base address and
5329   // environment pointer.
5330   // Thus for a call through a function pointer, the following actions need
5331   // to be performed:
5332   //   1. Save the TOC of the caller in the TOC save area of its stack
5333   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5334   //   2. Load the address of the function entry point from the function
5335   //      descriptor.
5336   //   3. Load the TOC of the callee from the function descriptor into r2.
5337   //   4. Load the environment pointer from the function descriptor into
5338   //      r11.
5339   //   5. Branch to the function entry point address.
5340   //   6. On return of the callee, the TOC of the caller needs to be
5341   //      restored (this is done in FinishCall()).
5342   //
5343   // The loads are scheduled at the beginning of the call sequence, and the
5344   // register copies are flagged together to ensure that no other
5345   // operations can be scheduled in between. E.g. without flagging the
5346   // copies together, a TOC access in the caller could be scheduled between
5347   // the assignment of the callee TOC and the branch to the callee, which leads
5348   // to incorrect code.
5349 
5350   // Start by loading the function address from the descriptor.
5351   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5352   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5353                       ? (MachineMemOperand::MODereferenceable |
5354                          MachineMemOperand::MOInvariant)
5355                       : MachineMemOperand::MONone;
5356 
5357   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5358 
5359   // Registers used in building the DAG.
5360   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5361   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5362 
5363   // Offsets of descriptor members.
5364   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5365   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5366 
5367   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5368   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5369 
5370   // One load for the functions entry point address.
5371   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5372                                     Alignment, MMOFlags);
5373 
5374   // One for loading the TOC anchor for the module that contains the called
5375   // function.
5376   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5377   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5378   SDValue TOCPtr =
5379       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5380                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5381 
5382   // One for loading the environment pointer.
5383   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5384   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5385   SDValue LoadEnvPtr =
5386       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5387                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5388 
5389 
5390   // Then copy the newly loaded TOC anchor to the TOC pointer.
5391   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5392   Chain = TOCVal.getValue(0);
5393   Glue = TOCVal.getValue(1);
5394 
5395   // If the function call has an explicit 'nest' parameter, it takes the
5396   // place of the environment pointer.
5397   assert((!hasNest || !Subtarget.isAIXABI()) &&
5398          "Nest parameter is not supported on AIX.");
5399   if (!hasNest) {
5400     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5401     Chain = EnvVal.getValue(0);
5402     Glue = EnvVal.getValue(1);
5403   }
5404 
5405   // The rest of the indirect call sequence is the same as the non-descriptor
5406   // DAG.
5407   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5408 }
5409 
5410 static void
5411 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5412                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5413                   SelectionDAG &DAG,
5414                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5415                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5416                   const PPCSubtarget &Subtarget) {
5417   const bool IsPPC64 = Subtarget.isPPC64();
5418   // MVT for a general purpose register.
5419   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5420 
5421   // First operand is always the chain.
5422   Ops.push_back(Chain);
5423 
5424   // If it's a direct call pass the callee as the second operand.
5425   if (!CFlags.IsIndirect)
5426     Ops.push_back(Callee);
5427   else {
5428     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5429 
5430     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5431     // on the stack (this would have been done in `LowerCall_64SVR4` or
5432     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5433     // represents both the indirect branch and a load that restores the TOC
5434     // pointer from the linkage area. The operand for the TOC restore is an add
5435     // of the TOC save offset to the stack pointer. This must be the second
5436     // operand: after the chain input but before any other variadic arguments.
5437     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5438     // saved or used.
5439     if (isTOCSaveRestoreRequired(Subtarget)) {
5440       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5441 
5442       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5443       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5444       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5445       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5446       Ops.push_back(AddTOC);
5447     }
5448 
5449     // Add the register used for the environment pointer.
5450     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5451       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5452                                     RegVT));
5453 
5454 
5455     // Add CTR register as callee so a bctr can be emitted later.
5456     if (CFlags.IsTailCall)
5457       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5458   }
5459 
5460   // If this is a tail call add stack pointer delta.
5461   if (CFlags.IsTailCall)
5462     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5463 
5464   // Add argument registers to the end of the list so that they are known live
5465   // into the call.
5466   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5467     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5468                                   RegsToPass[i].second.getValueType()));
5469 
5470   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5471   // no way to mark dependencies as implicit here.
5472   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5473   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5474        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5475     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5476 
5477   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5478   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5479     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5480 
5481   // Add a register mask operand representing the call-preserved registers.
5482   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5483   const uint32_t *Mask =
5484       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5485   assert(Mask && "Missing call preserved mask for calling convention");
5486   Ops.push_back(DAG.getRegisterMask(Mask));
5487 
5488   // If the glue is valid, it is the last operand.
5489   if (Glue.getNode())
5490     Ops.push_back(Glue);
5491 }
5492 
5493 SDValue PPCTargetLowering::FinishCall(
5494     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5495     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5496     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5497     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5498     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5499 
5500   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5501       Subtarget.isAIXABI())
5502     setUsesTOCBasePtr(DAG);
5503 
5504   unsigned CallOpc =
5505       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5506                     Subtarget, DAG.getTarget());
5507 
5508   if (!CFlags.IsIndirect)
5509     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5510   else if (Subtarget.usesFunctionDescriptors())
5511     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5512                                   dl, CFlags.HasNest, Subtarget);
5513   else
5514     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5515 
5516   // Build the operand list for the call instruction.
5517   SmallVector<SDValue, 8> Ops;
5518   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5519                     SPDiff, Subtarget);
5520 
5521   // Emit tail call.
5522   if (CFlags.IsTailCall) {
5523     // Indirect tail call when using PC Relative calls do not have the same
5524     // constraints.
5525     assert(((Callee.getOpcode() == ISD::Register &&
5526              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5527             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5528             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5529             isa<ConstantSDNode>(Callee) ||
5530             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5531            "Expecting a global address, external symbol, absolute value, "
5532            "register or an indirect tail call when PC Relative calls are "
5533            "used.");
5534     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5535     assert(CallOpc == PPCISD::TC_RETURN &&
5536            "Unexpected call opcode for a tail call.");
5537     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5538     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5539   }
5540 
5541   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5542   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5543   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5544   Glue = Chain.getValue(1);
5545 
5546   // When performing tail call optimization the callee pops its arguments off
5547   // the stack. Account for this here so these bytes can be pushed back on in
5548   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5549   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5550                          getTargetMachine().Options.GuaranteedTailCallOpt)
5551                             ? NumBytes
5552                             : 0;
5553 
5554   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5555                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5556                              Glue, dl);
5557   Glue = Chain.getValue(1);
5558 
5559   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5560                          DAG, InVals);
5561 }
5562 
5563 SDValue
5564 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5565                              SmallVectorImpl<SDValue> &InVals) const {
5566   SelectionDAG &DAG                     = CLI.DAG;
5567   SDLoc &dl                             = CLI.DL;
5568   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5569   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5570   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5571   SDValue Chain                         = CLI.Chain;
5572   SDValue Callee                        = CLI.Callee;
5573   bool &isTailCall                      = CLI.IsTailCall;
5574   CallingConv::ID CallConv              = CLI.CallConv;
5575   bool isVarArg                         = CLI.IsVarArg;
5576   bool isPatchPoint                     = CLI.IsPatchPoint;
5577   const CallBase *CB                    = CLI.CB;
5578 
5579   if (isTailCall) {
5580     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5581       isTailCall = false;
5582     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5583       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5584           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5585     else
5586       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5587                                                      Ins, DAG);
5588     if (isTailCall) {
5589       ++NumTailCalls;
5590       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5591         ++NumSiblingCalls;
5592 
5593       // PC Relative calls no longer guarantee that the callee is a Global
5594       // Address Node. The callee could be an indirect tail call in which
5595       // case the SDValue for the callee could be a load (to load the address
5596       // of a function pointer) or it may be a register copy (to move the
5597       // address of the callee from a function parameter into a virtual
5598       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5599       assert((Subtarget.isUsingPCRelativeCalls() ||
5600               isa<GlobalAddressSDNode>(Callee)) &&
5601              "Callee should be an llvm::Function object.");
5602 
5603       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5604                         << "\nTCO callee: ");
5605       LLVM_DEBUG(Callee.dump());
5606     }
5607   }
5608 
5609   if (!isTailCall && CB && CB->isMustTailCall())
5610     report_fatal_error("failed to perform tail call elimination on a call "
5611                        "site marked musttail");
5612 
5613   // When long calls (i.e. indirect calls) are always used, calls are always
5614   // made via function pointer. If we have a function name, first translate it
5615   // into a pointer.
5616   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5617       !isTailCall)
5618     Callee = LowerGlobalAddress(Callee, DAG);
5619 
5620   CallFlags CFlags(
5621       CallConv, isTailCall, isVarArg, isPatchPoint,
5622       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5623       // hasNest
5624       Subtarget.is64BitELFABI() &&
5625           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5626       CLI.NoMerge);
5627 
5628   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5629     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5630                             InVals, CB);
5631 
5632   if (Subtarget.isSVR4ABI())
5633     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5634                             InVals, CB);
5635 
5636   if (Subtarget.isAIXABI())
5637     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5638                          InVals, CB);
5639 
5640   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5641                           InVals, CB);
5642 }
5643 
5644 SDValue PPCTargetLowering::LowerCall_32SVR4(
5645     SDValue Chain, SDValue Callee, CallFlags CFlags,
5646     const SmallVectorImpl<ISD::OutputArg> &Outs,
5647     const SmallVectorImpl<SDValue> &OutVals,
5648     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5649     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5650     const CallBase *CB) const {
5651   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5652   // of the 32-bit SVR4 ABI stack frame layout.
5653 
5654   const CallingConv::ID CallConv = CFlags.CallConv;
5655   const bool IsVarArg = CFlags.IsVarArg;
5656   const bool IsTailCall = CFlags.IsTailCall;
5657 
5658   assert((CallConv == CallingConv::C ||
5659           CallConv == CallingConv::Cold ||
5660           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5661 
5662   const Align PtrAlign(4);
5663 
5664   MachineFunction &MF = DAG.getMachineFunction();
5665 
5666   // Mark this function as potentially containing a function that contains a
5667   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5668   // and restoring the callers stack pointer in this functions epilog. This is
5669   // done because by tail calling the called function might overwrite the value
5670   // in this function's (MF) stack pointer stack slot 0(SP).
5671   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5672       CallConv == CallingConv::Fast)
5673     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5674 
5675   // Count how many bytes are to be pushed on the stack, including the linkage
5676   // area, parameter list area and the part of the local variable space which
5677   // contains copies of aggregates which are passed by value.
5678 
5679   // Assign locations to all of the outgoing arguments.
5680   SmallVector<CCValAssign, 16> ArgLocs;
5681   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5682 
5683   // Reserve space for the linkage area on the stack.
5684   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5685                        PtrAlign);
5686   if (useSoftFloat())
5687     CCInfo.PreAnalyzeCallOperands(Outs);
5688 
5689   if (IsVarArg) {
5690     // Handle fixed and variable vector arguments differently.
5691     // Fixed vector arguments go into registers as long as registers are
5692     // available. Variable vector arguments always go into memory.
5693     unsigned NumArgs = Outs.size();
5694 
5695     for (unsigned i = 0; i != NumArgs; ++i) {
5696       MVT ArgVT = Outs[i].VT;
5697       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5698       bool Result;
5699 
5700       if (Outs[i].IsFixed) {
5701         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5702                                CCInfo);
5703       } else {
5704         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5705                                       ArgFlags, CCInfo);
5706       }
5707 
5708       if (Result) {
5709 #ifndef NDEBUG
5710         errs() << "Call operand #" << i << " has unhandled type "
5711              << EVT(ArgVT).getEVTString() << "\n";
5712 #endif
5713         llvm_unreachable(nullptr);
5714       }
5715     }
5716   } else {
5717     // All arguments are treated the same.
5718     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5719   }
5720   CCInfo.clearWasPPCF128();
5721 
5722   // Assign locations to all of the outgoing aggregate by value arguments.
5723   SmallVector<CCValAssign, 16> ByValArgLocs;
5724   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5725 
5726   // Reserve stack space for the allocations in CCInfo.
5727   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5728 
5729   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5730 
5731   // Size of the linkage area, parameter list area and the part of the local
5732   // space variable where copies of aggregates which are passed by value are
5733   // stored.
5734   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5735 
5736   // Calculate by how many bytes the stack has to be adjusted in case of tail
5737   // call optimization.
5738   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5739 
5740   // Adjust the stack pointer for the new arguments...
5741   // These operations are automatically eliminated by the prolog/epilog pass
5742   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5743   SDValue CallSeqStart = Chain;
5744 
5745   // Load the return address and frame pointer so it can be moved somewhere else
5746   // later.
5747   SDValue LROp, FPOp;
5748   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5749 
5750   // Set up a copy of the stack pointer for use loading and storing any
5751   // arguments that may not fit in the registers available for argument
5752   // passing.
5753   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5754 
5755   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5756   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5757   SmallVector<SDValue, 8> MemOpChains;
5758 
5759   bool seenFloatArg = false;
5760   // Walk the register/memloc assignments, inserting copies/loads.
5761   // i - Tracks the index into the list of registers allocated for the call
5762   // RealArgIdx - Tracks the index into the list of actual function arguments
5763   // j - Tracks the index into the list of byval arguments
5764   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5765        i != e;
5766        ++i, ++RealArgIdx) {
5767     CCValAssign &VA = ArgLocs[i];
5768     SDValue Arg = OutVals[RealArgIdx];
5769     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5770 
5771     if (Flags.isByVal()) {
5772       // Argument is an aggregate which is passed by value, thus we need to
5773       // create a copy of it in the local variable space of the current stack
5774       // frame (which is the stack frame of the caller) and pass the address of
5775       // this copy to the callee.
5776       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5777       CCValAssign &ByValVA = ByValArgLocs[j++];
5778       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5779 
5780       // Memory reserved in the local variable space of the callers stack frame.
5781       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5782 
5783       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5784       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5785                            StackPtr, PtrOff);
5786 
5787       // Create a copy of the argument in the local area of the current
5788       // stack frame.
5789       SDValue MemcpyCall =
5790         CreateCopyOfByValArgument(Arg, PtrOff,
5791                                   CallSeqStart.getNode()->getOperand(0),
5792                                   Flags, DAG, dl);
5793 
5794       // This must go outside the CALLSEQ_START..END.
5795       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5796                                                      SDLoc(MemcpyCall));
5797       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5798                              NewCallSeqStart.getNode());
5799       Chain = CallSeqStart = NewCallSeqStart;
5800 
5801       // Pass the address of the aggregate copy on the stack either in a
5802       // physical register or in the parameter list area of the current stack
5803       // frame to the callee.
5804       Arg = PtrOff;
5805     }
5806 
5807     // When useCRBits() is true, there can be i1 arguments.
5808     // It is because getRegisterType(MVT::i1) => MVT::i1,
5809     // and for other integer types getRegisterType() => MVT::i32.
5810     // Extend i1 and ensure callee will get i32.
5811     if (Arg.getValueType() == MVT::i1)
5812       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5813                         dl, MVT::i32, Arg);
5814 
5815     if (VA.isRegLoc()) {
5816       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5817       // Put argument in a physical register.
5818       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5819         bool IsLE = Subtarget.isLittleEndian();
5820         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5821                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5822         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5823         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5824                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5825         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5826                              SVal.getValue(0)));
5827       } else
5828         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5829     } else {
5830       // Put argument in the parameter list area of the current stack frame.
5831       assert(VA.isMemLoc());
5832       unsigned LocMemOffset = VA.getLocMemOffset();
5833 
5834       if (!IsTailCall) {
5835         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5836         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5837                              StackPtr, PtrOff);
5838 
5839         MemOpChains.push_back(
5840             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5841       } else {
5842         // Calculate and remember argument location.
5843         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5844                                  TailCallArguments);
5845       }
5846     }
5847   }
5848 
5849   if (!MemOpChains.empty())
5850     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5851 
5852   // Build a sequence of copy-to-reg nodes chained together with token chain
5853   // and flag operands which copy the outgoing args into the appropriate regs.
5854   SDValue InFlag;
5855   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5856     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5857                              RegsToPass[i].second, InFlag);
5858     InFlag = Chain.getValue(1);
5859   }
5860 
5861   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5862   // registers.
5863   if (IsVarArg) {
5864     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5865     SDValue Ops[] = { Chain, InFlag };
5866 
5867     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5868                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5869 
5870     InFlag = Chain.getValue(1);
5871   }
5872 
5873   if (IsTailCall)
5874     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5875                     TailCallArguments);
5876 
5877   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5878                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5879 }
5880 
5881 // Copy an argument into memory, being careful to do this outside the
5882 // call sequence for the call to which the argument belongs.
5883 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5884     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5885     SelectionDAG &DAG, const SDLoc &dl) const {
5886   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5887                         CallSeqStart.getNode()->getOperand(0),
5888                         Flags, DAG, dl);
5889   // The MEMCPY must go outside the CALLSEQ_START..END.
5890   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5891   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5892                                                  SDLoc(MemcpyCall));
5893   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5894                          NewCallSeqStart.getNode());
5895   return NewCallSeqStart;
5896 }
5897 
5898 SDValue PPCTargetLowering::LowerCall_64SVR4(
5899     SDValue Chain, SDValue Callee, CallFlags CFlags,
5900     const SmallVectorImpl<ISD::OutputArg> &Outs,
5901     const SmallVectorImpl<SDValue> &OutVals,
5902     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5903     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5904     const CallBase *CB) const {
5905   bool isELFv2ABI = Subtarget.isELFv2ABI();
5906   bool isLittleEndian = Subtarget.isLittleEndian();
5907   unsigned NumOps = Outs.size();
5908   bool IsSibCall = false;
5909   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5910 
5911   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5912   unsigned PtrByteSize = 8;
5913 
5914   MachineFunction &MF = DAG.getMachineFunction();
5915 
5916   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5917     IsSibCall = true;
5918 
5919   // Mark this function as potentially containing a function that contains a
5920   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5921   // and restoring the callers stack pointer in this functions epilog. This is
5922   // done because by tail calling the called function might overwrite the value
5923   // in this function's (MF) stack pointer stack slot 0(SP).
5924   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5925     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5926 
5927   assert(!(IsFastCall && CFlags.IsVarArg) &&
5928          "fastcc not supported on varargs functions");
5929 
5930   // Count how many bytes are to be pushed on the stack, including the linkage
5931   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5932   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5933   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5934   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5935   unsigned NumBytes = LinkageSize;
5936   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5937 
5938   static const MCPhysReg GPR[] = {
5939     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5940     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5941   };
5942   static const MCPhysReg VR[] = {
5943     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5944     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5945   };
5946 
5947   const unsigned NumGPRs = array_lengthof(GPR);
5948   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5949   const unsigned NumVRs  = array_lengthof(VR);
5950 
5951   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5952   // can be passed to the callee in registers.
5953   // For the fast calling convention, there is another check below.
5954   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5955   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5956   if (!HasParameterArea) {
5957     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5958     unsigned AvailableFPRs = NumFPRs;
5959     unsigned AvailableVRs = NumVRs;
5960     unsigned NumBytesTmp = NumBytes;
5961     for (unsigned i = 0; i != NumOps; ++i) {
5962       if (Outs[i].Flags.isNest()) continue;
5963       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5964                                  PtrByteSize, LinkageSize, ParamAreaSize,
5965                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5966         HasParameterArea = true;
5967     }
5968   }
5969 
5970   // When using the fast calling convention, we don't provide backing for
5971   // arguments that will be in registers.
5972   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5973 
5974   // Avoid allocating parameter area for fastcc functions if all the arguments
5975   // can be passed in the registers.
5976   if (IsFastCall)
5977     HasParameterArea = false;
5978 
5979   // Add up all the space actually used.
5980   for (unsigned i = 0; i != NumOps; ++i) {
5981     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5982     EVT ArgVT = Outs[i].VT;
5983     EVT OrigVT = Outs[i].ArgVT;
5984 
5985     if (Flags.isNest())
5986       continue;
5987 
5988     if (IsFastCall) {
5989       if (Flags.isByVal()) {
5990         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5991         if (NumGPRsUsed > NumGPRs)
5992           HasParameterArea = true;
5993       } else {
5994         switch (ArgVT.getSimpleVT().SimpleTy) {
5995         default: llvm_unreachable("Unexpected ValueType for argument!");
5996         case MVT::i1:
5997         case MVT::i32:
5998         case MVT::i64:
5999           if (++NumGPRsUsed <= NumGPRs)
6000             continue;
6001           break;
6002         case MVT::v4i32:
6003         case MVT::v8i16:
6004         case MVT::v16i8:
6005         case MVT::v2f64:
6006         case MVT::v2i64:
6007         case MVT::v1i128:
6008         case MVT::f128:
6009           if (++NumVRsUsed <= NumVRs)
6010             continue;
6011           break;
6012         case MVT::v4f32:
6013           if (++NumVRsUsed <= NumVRs)
6014             continue;
6015           break;
6016         case MVT::f32:
6017         case MVT::f64:
6018           if (++NumFPRsUsed <= NumFPRs)
6019             continue;
6020           break;
6021         }
6022         HasParameterArea = true;
6023       }
6024     }
6025 
6026     /* Respect alignment of argument on the stack.  */
6027     auto Alignement =
6028         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6029     NumBytes = alignTo(NumBytes, Alignement);
6030 
6031     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6032     if (Flags.isInConsecutiveRegsLast())
6033       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6034   }
6035 
6036   unsigned NumBytesActuallyUsed = NumBytes;
6037 
6038   // In the old ELFv1 ABI,
6039   // the prolog code of the callee may store up to 8 GPR argument registers to
6040   // the stack, allowing va_start to index over them in memory if its varargs.
6041   // Because we cannot tell if this is needed on the caller side, we have to
6042   // conservatively assume that it is needed.  As such, make sure we have at
6043   // least enough stack space for the caller to store the 8 GPRs.
6044   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6045   // really requires memory operands, e.g. a vararg function.
6046   if (HasParameterArea)
6047     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6048   else
6049     NumBytes = LinkageSize;
6050 
6051   // Tail call needs the stack to be aligned.
6052   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6053     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6054 
6055   int SPDiff = 0;
6056 
6057   // Calculate by how many bytes the stack has to be adjusted in case of tail
6058   // call optimization.
6059   if (!IsSibCall)
6060     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6061 
6062   // To protect arguments on the stack from being clobbered in a tail call,
6063   // force all the loads to happen before doing any other lowering.
6064   if (CFlags.IsTailCall)
6065     Chain = DAG.getStackArgumentTokenFactor(Chain);
6066 
6067   // Adjust the stack pointer for the new arguments...
6068   // These operations are automatically eliminated by the prolog/epilog pass
6069   if (!IsSibCall)
6070     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6071   SDValue CallSeqStart = Chain;
6072 
6073   // Load the return address and frame pointer so it can be move somewhere else
6074   // later.
6075   SDValue LROp, FPOp;
6076   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6077 
6078   // Set up a copy of the stack pointer for use loading and storing any
6079   // arguments that may not fit in the registers available for argument
6080   // passing.
6081   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6082 
6083   // Figure out which arguments are going to go in registers, and which in
6084   // memory.  Also, if this is a vararg function, floating point operations
6085   // must be stored to our stack, and loaded into integer regs as well, if
6086   // any integer regs are available for argument passing.
6087   unsigned ArgOffset = LinkageSize;
6088 
6089   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6090   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6091 
6092   SmallVector<SDValue, 8> MemOpChains;
6093   for (unsigned i = 0; i != NumOps; ++i) {
6094     SDValue Arg = OutVals[i];
6095     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6096     EVT ArgVT = Outs[i].VT;
6097     EVT OrigVT = Outs[i].ArgVT;
6098 
6099     // PtrOff will be used to store the current argument to the stack if a
6100     // register cannot be found for it.
6101     SDValue PtrOff;
6102 
6103     // We re-align the argument offset for each argument, except when using the
6104     // fast calling convention, when we need to make sure we do that only when
6105     // we'll actually use a stack slot.
6106     auto ComputePtrOff = [&]() {
6107       /* Respect alignment of argument on the stack.  */
6108       auto Alignment =
6109           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6110       ArgOffset = alignTo(ArgOffset, Alignment);
6111 
6112       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6113 
6114       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6115     };
6116 
6117     if (!IsFastCall) {
6118       ComputePtrOff();
6119 
6120       /* Compute GPR index associated with argument offset.  */
6121       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6122       GPR_idx = std::min(GPR_idx, NumGPRs);
6123     }
6124 
6125     // Promote integers to 64-bit values.
6126     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6127       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6128       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6129       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6130     }
6131 
6132     // FIXME memcpy is used way more than necessary.  Correctness first.
6133     // Note: "by value" is code for passing a structure by value, not
6134     // basic types.
6135     if (Flags.isByVal()) {
6136       // Note: Size includes alignment padding, so
6137       //   struct x { short a; char b; }
6138       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6139       // These are the proper values we need for right-justifying the
6140       // aggregate in a parameter register.
6141       unsigned Size = Flags.getByValSize();
6142 
6143       // An empty aggregate parameter takes up no storage and no
6144       // registers.
6145       if (Size == 0)
6146         continue;
6147 
6148       if (IsFastCall)
6149         ComputePtrOff();
6150 
6151       // All aggregates smaller than 8 bytes must be passed right-justified.
6152       if (Size==1 || Size==2 || Size==4) {
6153         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6154         if (GPR_idx != NumGPRs) {
6155           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6156                                         MachinePointerInfo(), VT);
6157           MemOpChains.push_back(Load.getValue(1));
6158           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6159 
6160           ArgOffset += PtrByteSize;
6161           continue;
6162         }
6163       }
6164 
6165       if (GPR_idx == NumGPRs && Size < 8) {
6166         SDValue AddPtr = PtrOff;
6167         if (!isLittleEndian) {
6168           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6169                                           PtrOff.getValueType());
6170           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6171         }
6172         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6173                                                           CallSeqStart,
6174                                                           Flags, DAG, dl);
6175         ArgOffset += PtrByteSize;
6176         continue;
6177       }
6178       // Copy entire object into memory.  There are cases where gcc-generated
6179       // code assumes it is there, even if it could be put entirely into
6180       // registers.  (This is not what the doc says.)
6181 
6182       // FIXME: The above statement is likely due to a misunderstanding of the
6183       // documents.  All arguments must be copied into the parameter area BY
6184       // THE CALLEE in the event that the callee takes the address of any
6185       // formal argument.  That has not yet been implemented.  However, it is
6186       // reasonable to use the stack area as a staging area for the register
6187       // load.
6188 
6189       // Skip this for small aggregates, as we will use the same slot for a
6190       // right-justified copy, below.
6191       if (Size >= 8)
6192         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6193                                                           CallSeqStart,
6194                                                           Flags, DAG, dl);
6195 
6196       // When a register is available, pass a small aggregate right-justified.
6197       if (Size < 8 && GPR_idx != NumGPRs) {
6198         // The easiest way to get this right-justified in a register
6199         // is to copy the structure into the rightmost portion of a
6200         // local variable slot, then load the whole slot into the
6201         // register.
6202         // FIXME: The memcpy seems to produce pretty awful code for
6203         // small aggregates, particularly for packed ones.
6204         // FIXME: It would be preferable to use the slot in the
6205         // parameter save area instead of a new local variable.
6206         SDValue AddPtr = PtrOff;
6207         if (!isLittleEndian) {
6208           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6209           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6210         }
6211         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6212                                                           CallSeqStart,
6213                                                           Flags, DAG, dl);
6214 
6215         // Load the slot into the register.
6216         SDValue Load =
6217             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6218         MemOpChains.push_back(Load.getValue(1));
6219         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6220 
6221         // Done with this argument.
6222         ArgOffset += PtrByteSize;
6223         continue;
6224       }
6225 
6226       // For aggregates larger than PtrByteSize, copy the pieces of the
6227       // object that fit into registers from the parameter save area.
6228       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6229         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6230         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6231         if (GPR_idx != NumGPRs) {
6232           SDValue Load =
6233               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6234           MemOpChains.push_back(Load.getValue(1));
6235           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6236           ArgOffset += PtrByteSize;
6237         } else {
6238           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6239           break;
6240         }
6241       }
6242       continue;
6243     }
6244 
6245     switch (Arg.getSimpleValueType().SimpleTy) {
6246     default: llvm_unreachable("Unexpected ValueType for argument!");
6247     case MVT::i1:
6248     case MVT::i32:
6249     case MVT::i64:
6250       if (Flags.isNest()) {
6251         // The 'nest' parameter, if any, is passed in R11.
6252         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6253         break;
6254       }
6255 
6256       // These can be scalar arguments or elements of an integer array type
6257       // passed directly.  Clang may use those instead of "byval" aggregate
6258       // types to avoid forcing arguments to memory unnecessarily.
6259       if (GPR_idx != NumGPRs) {
6260         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6261       } else {
6262         if (IsFastCall)
6263           ComputePtrOff();
6264 
6265         assert(HasParameterArea &&
6266                "Parameter area must exist to pass an argument in memory.");
6267         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6268                          true, CFlags.IsTailCall, false, MemOpChains,
6269                          TailCallArguments, dl);
6270         if (IsFastCall)
6271           ArgOffset += PtrByteSize;
6272       }
6273       if (!IsFastCall)
6274         ArgOffset += PtrByteSize;
6275       break;
6276     case MVT::f32:
6277     case MVT::f64: {
6278       // These can be scalar arguments or elements of a float array type
6279       // passed directly.  The latter are used to implement ELFv2 homogenous
6280       // float aggregates.
6281 
6282       // Named arguments go into FPRs first, and once they overflow, the
6283       // remaining arguments go into GPRs and then the parameter save area.
6284       // Unnamed arguments for vararg functions always go to GPRs and
6285       // then the parameter save area.  For now, put all arguments to vararg
6286       // routines always in both locations (FPR *and* GPR or stack slot).
6287       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6288       bool NeededLoad = false;
6289 
6290       // First load the argument into the next available FPR.
6291       if (FPR_idx != NumFPRs)
6292         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6293 
6294       // Next, load the argument into GPR or stack slot if needed.
6295       if (!NeedGPROrStack)
6296         ;
6297       else if (GPR_idx != NumGPRs && !IsFastCall) {
6298         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6299         // once we support fp <-> gpr moves.
6300 
6301         // In the non-vararg case, this can only ever happen in the
6302         // presence of f32 array types, since otherwise we never run
6303         // out of FPRs before running out of GPRs.
6304         SDValue ArgVal;
6305 
6306         // Double values are always passed in a single GPR.
6307         if (Arg.getValueType() != MVT::f32) {
6308           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6309 
6310         // Non-array float values are extended and passed in a GPR.
6311         } else if (!Flags.isInConsecutiveRegs()) {
6312           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6313           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6314 
6315         // If we have an array of floats, we collect every odd element
6316         // together with its predecessor into one GPR.
6317         } else if (ArgOffset % PtrByteSize != 0) {
6318           SDValue Lo, Hi;
6319           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6320           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6321           if (!isLittleEndian)
6322             std::swap(Lo, Hi);
6323           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6324 
6325         // The final element, if even, goes into the first half of a GPR.
6326         } else if (Flags.isInConsecutiveRegsLast()) {
6327           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6328           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6329           if (!isLittleEndian)
6330             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6331                                  DAG.getConstant(32, dl, MVT::i32));
6332 
6333         // Non-final even elements are skipped; they will be handled
6334         // together the with subsequent argument on the next go-around.
6335         } else
6336           ArgVal = SDValue();
6337 
6338         if (ArgVal.getNode())
6339           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6340       } else {
6341         if (IsFastCall)
6342           ComputePtrOff();
6343 
6344         // Single-precision floating-point values are mapped to the
6345         // second (rightmost) word of the stack doubleword.
6346         if (Arg.getValueType() == MVT::f32 &&
6347             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6348           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6349           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6350         }
6351 
6352         assert(HasParameterArea &&
6353                "Parameter area must exist to pass an argument in memory.");
6354         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6355                          true, CFlags.IsTailCall, false, MemOpChains,
6356                          TailCallArguments, dl);
6357 
6358         NeededLoad = true;
6359       }
6360       // When passing an array of floats, the array occupies consecutive
6361       // space in the argument area; only round up to the next doubleword
6362       // at the end of the array.  Otherwise, each float takes 8 bytes.
6363       if (!IsFastCall || NeededLoad) {
6364         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6365                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6366         if (Flags.isInConsecutiveRegsLast())
6367           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6368       }
6369       break;
6370     }
6371     case MVT::v4f32:
6372     case MVT::v4i32:
6373     case MVT::v8i16:
6374     case MVT::v16i8:
6375     case MVT::v2f64:
6376     case MVT::v2i64:
6377     case MVT::v1i128:
6378     case MVT::f128:
6379       // These can be scalar arguments or elements of a vector array type
6380       // passed directly.  The latter are used to implement ELFv2 homogenous
6381       // vector aggregates.
6382 
6383       // For a varargs call, named arguments go into VRs or on the stack as
6384       // usual; unnamed arguments always go to the stack or the corresponding
6385       // GPRs when within range.  For now, we always put the value in both
6386       // locations (or even all three).
6387       if (CFlags.IsVarArg) {
6388         assert(HasParameterArea &&
6389                "Parameter area must exist if we have a varargs call.");
6390         // We could elide this store in the case where the object fits
6391         // entirely in R registers.  Maybe later.
6392         SDValue Store =
6393             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6394         MemOpChains.push_back(Store);
6395         if (VR_idx != NumVRs) {
6396           SDValue Load =
6397               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6398           MemOpChains.push_back(Load.getValue(1));
6399           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6400         }
6401         ArgOffset += 16;
6402         for (unsigned i=0; i<16; i+=PtrByteSize) {
6403           if (GPR_idx == NumGPRs)
6404             break;
6405           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6406                                    DAG.getConstant(i, dl, PtrVT));
6407           SDValue Load =
6408               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6409           MemOpChains.push_back(Load.getValue(1));
6410           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6411         }
6412         break;
6413       }
6414 
6415       // Non-varargs Altivec params go into VRs or on the stack.
6416       if (VR_idx != NumVRs) {
6417         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6418       } else {
6419         if (IsFastCall)
6420           ComputePtrOff();
6421 
6422         assert(HasParameterArea &&
6423                "Parameter area must exist to pass an argument in memory.");
6424         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6425                          true, CFlags.IsTailCall, true, MemOpChains,
6426                          TailCallArguments, dl);
6427         if (IsFastCall)
6428           ArgOffset += 16;
6429       }
6430 
6431       if (!IsFastCall)
6432         ArgOffset += 16;
6433       break;
6434     }
6435   }
6436 
6437   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6438          "mismatch in size of parameter area");
6439   (void)NumBytesActuallyUsed;
6440 
6441   if (!MemOpChains.empty())
6442     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6443 
6444   // Check if this is an indirect call (MTCTR/BCTRL).
6445   // See prepareDescriptorIndirectCall and buildCallOperands for more
6446   // information about calls through function pointers in the 64-bit SVR4 ABI.
6447   if (CFlags.IsIndirect) {
6448     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6449     // caller in the TOC save area.
6450     if (isTOCSaveRestoreRequired(Subtarget)) {
6451       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6452       // Load r2 into a virtual register and store it to the TOC save area.
6453       setUsesTOCBasePtr(DAG);
6454       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6455       // TOC save area offset.
6456       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6457       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6458       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6459       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6460                            MachinePointerInfo::getStack(
6461                                DAG.getMachineFunction(), TOCSaveOffset));
6462     }
6463     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6464     // This does not mean the MTCTR instruction must use R12; it's easier
6465     // to model this as an extra parameter, so do that.
6466     if (isELFv2ABI && !CFlags.IsPatchPoint)
6467       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6468   }
6469 
6470   // Build a sequence of copy-to-reg nodes chained together with token chain
6471   // and flag operands which copy the outgoing args into the appropriate regs.
6472   SDValue InFlag;
6473   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6474     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6475                              RegsToPass[i].second, InFlag);
6476     InFlag = Chain.getValue(1);
6477   }
6478 
6479   if (CFlags.IsTailCall && !IsSibCall)
6480     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6481                     TailCallArguments);
6482 
6483   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6484                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6485 }
6486 
6487 SDValue PPCTargetLowering::LowerCall_Darwin(
6488     SDValue Chain, SDValue Callee, CallFlags CFlags,
6489     const SmallVectorImpl<ISD::OutputArg> &Outs,
6490     const SmallVectorImpl<SDValue> &OutVals,
6491     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6492     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6493     const CallBase *CB) const {
6494   unsigned NumOps = Outs.size();
6495 
6496   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6497   bool isPPC64 = PtrVT == MVT::i64;
6498   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6499 
6500   MachineFunction &MF = DAG.getMachineFunction();
6501 
6502   // Mark this function as potentially containing a function that contains a
6503   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6504   // and restoring the callers stack pointer in this functions epilog. This is
6505   // done because by tail calling the called function might overwrite the value
6506   // in this function's (MF) stack pointer stack slot 0(SP).
6507   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6508       CFlags.CallConv == CallingConv::Fast)
6509     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6510 
6511   // Count how many bytes are to be pushed on the stack, including the linkage
6512   // area, and parameter passing area.  We start with 24/48 bytes, which is
6513   // prereserved space for [SP][CR][LR][3 x unused].
6514   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6515   unsigned NumBytes = LinkageSize;
6516 
6517   // Add up all the space actually used.
6518   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6519   // they all go in registers, but we must reserve stack space for them for
6520   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6521   // assigned stack space in order, with padding so Altivec parameters are
6522   // 16-byte aligned.
6523   unsigned nAltivecParamsAtEnd = 0;
6524   for (unsigned i = 0; i != NumOps; ++i) {
6525     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6526     EVT ArgVT = Outs[i].VT;
6527     // Varargs Altivec parameters are padded to a 16 byte boundary.
6528     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6529         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6530         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6531       if (!CFlags.IsVarArg && !isPPC64) {
6532         // Non-varargs Altivec parameters go after all the non-Altivec
6533         // parameters; handle those later so we know how much padding we need.
6534         nAltivecParamsAtEnd++;
6535         continue;
6536       }
6537       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6538       NumBytes = ((NumBytes+15)/16)*16;
6539     }
6540     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6541   }
6542 
6543   // Allow for Altivec parameters at the end, if needed.
6544   if (nAltivecParamsAtEnd) {
6545     NumBytes = ((NumBytes+15)/16)*16;
6546     NumBytes += 16*nAltivecParamsAtEnd;
6547   }
6548 
6549   // The prolog code of the callee may store up to 8 GPR argument registers to
6550   // the stack, allowing va_start to index over them in memory if its varargs.
6551   // Because we cannot tell if this is needed on the caller side, we have to
6552   // conservatively assume that it is needed.  As such, make sure we have at
6553   // least enough stack space for the caller to store the 8 GPRs.
6554   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6555 
6556   // Tail call needs the stack to be aligned.
6557   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6558       CFlags.CallConv == CallingConv::Fast)
6559     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6560 
6561   // Calculate by how many bytes the stack has to be adjusted in case of tail
6562   // call optimization.
6563   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6564 
6565   // To protect arguments on the stack from being clobbered in a tail call,
6566   // force all the loads to happen before doing any other lowering.
6567   if (CFlags.IsTailCall)
6568     Chain = DAG.getStackArgumentTokenFactor(Chain);
6569 
6570   // Adjust the stack pointer for the new arguments...
6571   // These operations are automatically eliminated by the prolog/epilog pass
6572   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6573   SDValue CallSeqStart = Chain;
6574 
6575   // Load the return address and frame pointer so it can be move somewhere else
6576   // later.
6577   SDValue LROp, FPOp;
6578   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6579 
6580   // Set up a copy of the stack pointer for use loading and storing any
6581   // arguments that may not fit in the registers available for argument
6582   // passing.
6583   SDValue StackPtr;
6584   if (isPPC64)
6585     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6586   else
6587     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6588 
6589   // Figure out which arguments are going to go in registers, and which in
6590   // memory.  Also, if this is a vararg function, floating point operations
6591   // must be stored to our stack, and loaded into integer regs as well, if
6592   // any integer regs are available for argument passing.
6593   unsigned ArgOffset = LinkageSize;
6594   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6595 
6596   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6597     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6598     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6599   };
6600   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6601     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6602     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6603   };
6604   static const MCPhysReg VR[] = {
6605     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6606     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6607   };
6608   const unsigned NumGPRs = array_lengthof(GPR_32);
6609   const unsigned NumFPRs = 13;
6610   const unsigned NumVRs  = array_lengthof(VR);
6611 
6612   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6613 
6614   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6615   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6616 
6617   SmallVector<SDValue, 8> MemOpChains;
6618   for (unsigned i = 0; i != NumOps; ++i) {
6619     SDValue Arg = OutVals[i];
6620     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6621 
6622     // PtrOff will be used to store the current argument to the stack if a
6623     // register cannot be found for it.
6624     SDValue PtrOff;
6625 
6626     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6627 
6628     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6629 
6630     // On PPC64, promote integers to 64-bit values.
6631     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6632       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6633       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6634       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6635     }
6636 
6637     // FIXME memcpy is used way more than necessary.  Correctness first.
6638     // Note: "by value" is code for passing a structure by value, not
6639     // basic types.
6640     if (Flags.isByVal()) {
6641       unsigned Size = Flags.getByValSize();
6642       // Very small objects are passed right-justified.  Everything else is
6643       // passed left-justified.
6644       if (Size==1 || Size==2) {
6645         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6646         if (GPR_idx != NumGPRs) {
6647           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6648                                         MachinePointerInfo(), VT);
6649           MemOpChains.push_back(Load.getValue(1));
6650           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6651 
6652           ArgOffset += PtrByteSize;
6653         } else {
6654           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6655                                           PtrOff.getValueType());
6656           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6657           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6658                                                             CallSeqStart,
6659                                                             Flags, DAG, dl);
6660           ArgOffset += PtrByteSize;
6661         }
6662         continue;
6663       }
6664       // Copy entire object into memory.  There are cases where gcc-generated
6665       // code assumes it is there, even if it could be put entirely into
6666       // registers.  (This is not what the doc says.)
6667       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6668                                                         CallSeqStart,
6669                                                         Flags, DAG, dl);
6670 
6671       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6672       // copy the pieces of the object that fit into registers from the
6673       // parameter save area.
6674       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6675         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6676         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6677         if (GPR_idx != NumGPRs) {
6678           SDValue Load =
6679               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6680           MemOpChains.push_back(Load.getValue(1));
6681           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6682           ArgOffset += PtrByteSize;
6683         } else {
6684           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6685           break;
6686         }
6687       }
6688       continue;
6689     }
6690 
6691     switch (Arg.getSimpleValueType().SimpleTy) {
6692     default: llvm_unreachable("Unexpected ValueType for argument!");
6693     case MVT::i1:
6694     case MVT::i32:
6695     case MVT::i64:
6696       if (GPR_idx != NumGPRs) {
6697         if (Arg.getValueType() == MVT::i1)
6698           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6699 
6700         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6701       } else {
6702         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6703                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6704                          TailCallArguments, dl);
6705       }
6706       ArgOffset += PtrByteSize;
6707       break;
6708     case MVT::f32:
6709     case MVT::f64:
6710       if (FPR_idx != NumFPRs) {
6711         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6712 
6713         if (CFlags.IsVarArg) {
6714           SDValue Store =
6715               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6716           MemOpChains.push_back(Store);
6717 
6718           // Float varargs are always shadowed in available integer registers
6719           if (GPR_idx != NumGPRs) {
6720             SDValue Load =
6721                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6722             MemOpChains.push_back(Load.getValue(1));
6723             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6724           }
6725           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6726             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6727             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6728             SDValue Load =
6729                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6730             MemOpChains.push_back(Load.getValue(1));
6731             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6732           }
6733         } else {
6734           // If we have any FPRs remaining, we may also have GPRs remaining.
6735           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6736           // GPRs.
6737           if (GPR_idx != NumGPRs)
6738             ++GPR_idx;
6739           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6740               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6741             ++GPR_idx;
6742         }
6743       } else
6744         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6745                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6746                          TailCallArguments, dl);
6747       if (isPPC64)
6748         ArgOffset += 8;
6749       else
6750         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6751       break;
6752     case MVT::v4f32:
6753     case MVT::v4i32:
6754     case MVT::v8i16:
6755     case MVT::v16i8:
6756       if (CFlags.IsVarArg) {
6757         // These go aligned on the stack, or in the corresponding R registers
6758         // when within range.  The Darwin PPC ABI doc claims they also go in
6759         // V registers; in fact gcc does this only for arguments that are
6760         // prototyped, not for those that match the ...  We do it for all
6761         // arguments, seems to work.
6762         while (ArgOffset % 16 !=0) {
6763           ArgOffset += PtrByteSize;
6764           if (GPR_idx != NumGPRs)
6765             GPR_idx++;
6766         }
6767         // We could elide this store in the case where the object fits
6768         // entirely in R registers.  Maybe later.
6769         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6770                              DAG.getConstant(ArgOffset, dl, PtrVT));
6771         SDValue Store =
6772             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6773         MemOpChains.push_back(Store);
6774         if (VR_idx != NumVRs) {
6775           SDValue Load =
6776               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6777           MemOpChains.push_back(Load.getValue(1));
6778           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6779         }
6780         ArgOffset += 16;
6781         for (unsigned i=0; i<16; i+=PtrByteSize) {
6782           if (GPR_idx == NumGPRs)
6783             break;
6784           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6785                                    DAG.getConstant(i, dl, PtrVT));
6786           SDValue Load =
6787               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6788           MemOpChains.push_back(Load.getValue(1));
6789           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6790         }
6791         break;
6792       }
6793 
6794       // Non-varargs Altivec params generally go in registers, but have
6795       // stack space allocated at the end.
6796       if (VR_idx != NumVRs) {
6797         // Doesn't have GPR space allocated.
6798         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6799       } else if (nAltivecParamsAtEnd==0) {
6800         // We are emitting Altivec params in order.
6801         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6802                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6803                          TailCallArguments, dl);
6804         ArgOffset += 16;
6805       }
6806       break;
6807     }
6808   }
6809   // If all Altivec parameters fit in registers, as they usually do,
6810   // they get stack space following the non-Altivec parameters.  We
6811   // don't track this here because nobody below needs it.
6812   // If there are more Altivec parameters than fit in registers emit
6813   // the stores here.
6814   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6815     unsigned j = 0;
6816     // Offset is aligned; skip 1st 12 params which go in V registers.
6817     ArgOffset = ((ArgOffset+15)/16)*16;
6818     ArgOffset += 12*16;
6819     for (unsigned i = 0; i != NumOps; ++i) {
6820       SDValue Arg = OutVals[i];
6821       EVT ArgType = Outs[i].VT;
6822       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6823           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6824         if (++j > NumVRs) {
6825           SDValue PtrOff;
6826           // We are emitting Altivec params in order.
6827           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6828                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6829                            TailCallArguments, dl);
6830           ArgOffset += 16;
6831         }
6832       }
6833     }
6834   }
6835 
6836   if (!MemOpChains.empty())
6837     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6838 
6839   // On Darwin, R12 must contain the address of an indirect callee.  This does
6840   // not mean the MTCTR instruction must use R12; it's easier to model this as
6841   // an extra parameter, so do that.
6842   if (CFlags.IsIndirect) {
6843     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6844     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6845                                                    PPC::R12), Callee));
6846   }
6847 
6848   // Build a sequence of copy-to-reg nodes chained together with token chain
6849   // and flag operands which copy the outgoing args into the appropriate regs.
6850   SDValue InFlag;
6851   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6852     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6853                              RegsToPass[i].second, InFlag);
6854     InFlag = Chain.getValue(1);
6855   }
6856 
6857   if (CFlags.IsTailCall)
6858     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6859                     TailCallArguments);
6860 
6861   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6862                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6863 }
6864 
6865 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6866                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6867                    CCState &State) {
6868 
6869   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6870       State.getMachineFunction().getSubtarget());
6871   const bool IsPPC64 = Subtarget.isPPC64();
6872   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6873   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6874 
6875   assert((!ValVT.isInteger() ||
6876           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6877          "Integer argument exceeds register size: should have been legalized");
6878 
6879   if (ValVT == MVT::f128)
6880     report_fatal_error("f128 is unimplemented on AIX.");
6881 
6882   if (ArgFlags.isNest())
6883     report_fatal_error("Nest arguments are unimplemented.");
6884 
6885   if (ValVT.isVector() || LocVT.isVector())
6886     report_fatal_error("Vector arguments are unimplemented on AIX.");
6887 
6888   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6889                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6890                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6891   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6892                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6893                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6894 
6895   if (ArgFlags.isByVal()) {
6896     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6897       report_fatal_error("Pass-by-value arguments with alignment greater than "
6898                          "register width are not supported.");
6899 
6900     const unsigned ByValSize = ArgFlags.getByValSize();
6901 
6902     // An empty aggregate parameter takes up no storage and no registers,
6903     // but needs a MemLoc for a stack slot for the formal arguments side.
6904     if (ByValSize == 0) {
6905       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6906                                        State.getNextStackOffset(), RegVT,
6907                                        LocInfo));
6908       return false;
6909     }
6910 
6911     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6912     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6913     for (const unsigned E = Offset + StackSize; Offset < E;
6914          Offset += PtrAlign.value()) {
6915       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6916         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6917       else {
6918         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6919                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6920                                          LocInfo));
6921         break;
6922       }
6923     }
6924     return false;
6925   }
6926 
6927   // Arguments always reserve parameter save area.
6928   switch (ValVT.SimpleTy) {
6929   default:
6930     report_fatal_error("Unhandled value type for argument.");
6931   case MVT::i64:
6932     // i64 arguments should have been split to i32 for PPC32.
6933     assert(IsPPC64 && "PPC32 should have split i64 values.");
6934     LLVM_FALLTHROUGH;
6935   case MVT::i1:
6936   case MVT::i32: {
6937     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6938     // AIX integer arguments are always passed in register width.
6939     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6940       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6941                                   : CCValAssign::LocInfo::ZExt;
6942     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6943       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6944     else
6945       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6946 
6947     return false;
6948   }
6949   case MVT::f32:
6950   case MVT::f64: {
6951     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6952     const unsigned StoreSize = LocVT.getStoreSize();
6953     // Floats are always 4-byte aligned in the PSA on AIX.
6954     // This includes f64 in 64-bit mode for ABI compatibility.
6955     const unsigned Offset =
6956         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6957     unsigned FReg = State.AllocateReg(FPR);
6958     if (FReg)
6959       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6960 
6961     // Reserve and initialize GPRs or initialize the PSA as required.
6962     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6963       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6964         assert(FReg && "An FPR should be available when a GPR is reserved.");
6965         if (State.isVarArg()) {
6966           // Successfully reserved GPRs are only initialized for vararg calls.
6967           // Custom handling is required for:
6968           //   f64 in PPC32 needs to be split into 2 GPRs.
6969           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6970           State.addLoc(
6971               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6972         }
6973       } else {
6974         // If there are insufficient GPRs, the PSA needs to be initialized.
6975         // Initialization occurs even if an FPR was initialized for
6976         // compatibility with the AIX XL compiler. The full memory for the
6977         // argument will be initialized even if a prior word is saved in GPR.
6978         // A custom memLoc is used when the argument also passes in FPR so
6979         // that the callee handling can skip over it easily.
6980         State.addLoc(
6981             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6982                                              LocInfo)
6983                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6984         break;
6985       }
6986     }
6987 
6988     return false;
6989   }
6990   }
6991   return true;
6992 }
6993 
6994 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6995                                                     bool IsPPC64) {
6996   assert((IsPPC64 || SVT != MVT::i64) &&
6997          "i64 should have been split for 32-bit codegen.");
6998 
6999   switch (SVT) {
7000   default:
7001     report_fatal_error("Unexpected value type for formal argument");
7002   case MVT::i1:
7003   case MVT::i32:
7004   case MVT::i64:
7005     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7006   case MVT::f32:
7007     return &PPC::F4RCRegClass;
7008   case MVT::f64:
7009     return &PPC::F8RCRegClass;
7010   }
7011 }
7012 
7013 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7014                                         SelectionDAG &DAG, SDValue ArgValue,
7015                                         MVT LocVT, const SDLoc &dl) {
7016   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7017   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7018 
7019   if (Flags.isSExt())
7020     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7021                            DAG.getValueType(ValVT));
7022   else if (Flags.isZExt())
7023     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7024                            DAG.getValueType(ValVT));
7025 
7026   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7027 }
7028 
7029 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7030   const unsigned LASize = FL->getLinkageSize();
7031 
7032   if (PPC::GPRCRegClass.contains(Reg)) {
7033     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7034            "Reg must be a valid argument register!");
7035     return LASize + 4 * (Reg - PPC::R3);
7036   }
7037 
7038   if (PPC::G8RCRegClass.contains(Reg)) {
7039     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7040            "Reg must be a valid argument register!");
7041     return LASize + 8 * (Reg - PPC::X3);
7042   }
7043 
7044   llvm_unreachable("Only general purpose registers expected.");
7045 }
7046 
7047 //   AIX ABI Stack Frame Layout:
7048 //
7049 //   Low Memory +--------------------------------------------+
7050 //   SP   +---> | Back chain                                 | ---+
7051 //        |     +--------------------------------------------+    |
7052 //        |     | Saved Condition Register                   |    |
7053 //        |     +--------------------------------------------+    |
7054 //        |     | Saved Linkage Register                     |    |
7055 //        |     +--------------------------------------------+    | Linkage Area
7056 //        |     | Reserved for compilers                     |    |
7057 //        |     +--------------------------------------------+    |
7058 //        |     | Reserved for binders                       |    |
7059 //        |     +--------------------------------------------+    |
7060 //        |     | Saved TOC pointer                          | ---+
7061 //        |     +--------------------------------------------+
7062 //        |     | Parameter save area                        |
7063 //        |     +--------------------------------------------+
7064 //        |     | Alloca space                               |
7065 //        |     +--------------------------------------------+
7066 //        |     | Local variable space                       |
7067 //        |     +--------------------------------------------+
7068 //        |     | Float/int conversion temporary             |
7069 //        |     +--------------------------------------------+
7070 //        |     | Save area for AltiVec registers            |
7071 //        |     +--------------------------------------------+
7072 //        |     | AltiVec alignment padding                  |
7073 //        |     +--------------------------------------------+
7074 //        |     | Save area for VRSAVE register              |
7075 //        |     +--------------------------------------------+
7076 //        |     | Save area for General Purpose registers    |
7077 //        |     +--------------------------------------------+
7078 //        |     | Save area for Floating Point registers     |
7079 //        |     +--------------------------------------------+
7080 //        +---- | Back chain                                 |
7081 // High Memory  +--------------------------------------------+
7082 //
7083 //  Specifications:
7084 //  AIX 7.2 Assembler Language Reference
7085 //  Subroutine linkage convention
7086 
7087 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7088     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7089     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7090     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7091 
7092   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7093           CallConv == CallingConv::Fast) &&
7094          "Unexpected calling convention!");
7095 
7096   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7097     report_fatal_error("Tail call support is unimplemented on AIX.");
7098 
7099   if (useSoftFloat())
7100     report_fatal_error("Soft float support is unimplemented on AIX.");
7101 
7102   const PPCSubtarget &Subtarget =
7103       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7104 
7105   const bool IsPPC64 = Subtarget.isPPC64();
7106   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7107 
7108   // Assign locations to all of the incoming arguments.
7109   SmallVector<CCValAssign, 16> ArgLocs;
7110   MachineFunction &MF = DAG.getMachineFunction();
7111   MachineFrameInfo &MFI = MF.getFrameInfo();
7112   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7113 
7114   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7115   // Reserve space for the linkage area on the stack.
7116   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7117   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7118   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7119 
7120   SmallVector<SDValue, 8> MemOps;
7121 
7122   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7123     CCValAssign &VA = ArgLocs[I++];
7124     MVT LocVT = VA.getLocVT();
7125     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7126 
7127     // For compatibility with the AIX XL compiler, the float args in the
7128     // parameter save area are initialized even if the argument is available
7129     // in register.  The caller is required to initialize both the register
7130     // and memory, however, the callee can choose to expect it in either.
7131     // The memloc is dismissed here because the argument is retrieved from
7132     // the register.
7133     if (VA.isMemLoc() && VA.needsCustom())
7134       continue;
7135 
7136     if (Flags.isByVal() && VA.isMemLoc()) {
7137       const unsigned Size =
7138           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7139                   PtrByteSize);
7140       const int FI = MF.getFrameInfo().CreateFixedObject(
7141           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7142           /* IsAliased */ true);
7143       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7144       InVals.push_back(FIN);
7145 
7146       continue;
7147     }
7148 
7149     if (Flags.isByVal()) {
7150       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7151 
7152       const MCPhysReg ArgReg = VA.getLocReg();
7153       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7154 
7155       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7156         report_fatal_error("Over aligned byvals not supported yet.");
7157 
7158       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7159       const int FI = MF.getFrameInfo().CreateFixedObject(
7160           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7161           /* IsAliased */ true);
7162       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7163       InVals.push_back(FIN);
7164 
7165       // Add live ins for all the RegLocs for the same ByVal.
7166       const TargetRegisterClass *RegClass =
7167           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7168 
7169       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7170                                                unsigned Offset) {
7171         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7172         // Since the callers side has left justified the aggregate in the
7173         // register, we can simply store the entire register into the stack
7174         // slot.
7175         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7176         // The store to the fixedstack object is needed becuase accessing a
7177         // field of the ByVal will use a gep and load. Ideally we will optimize
7178         // to extracting the value from the register directly, and elide the
7179         // stores when the arguments address is not taken, but that will need to
7180         // be future work.
7181         SDValue Store = DAG.getStore(
7182             CopyFrom.getValue(1), dl, CopyFrom,
7183             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7184             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7185 
7186         MemOps.push_back(Store);
7187       };
7188 
7189       unsigned Offset = 0;
7190       HandleRegLoc(VA.getLocReg(), Offset);
7191       Offset += PtrByteSize;
7192       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7193            Offset += PtrByteSize) {
7194         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7195                "RegLocs should be for ByVal argument.");
7196 
7197         const CCValAssign RL = ArgLocs[I++];
7198         HandleRegLoc(RL.getLocReg(), Offset);
7199       }
7200 
7201       if (Offset != StackSize) {
7202         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7203                "Expected MemLoc for remaining bytes.");
7204         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7205         // Consume the MemLoc.The InVal has already been emitted, so nothing
7206         // more needs to be done.
7207         ++I;
7208       }
7209 
7210       continue;
7211     }
7212 
7213     EVT ValVT = VA.getValVT();
7214     if (VA.isRegLoc() && !VA.needsCustom()) {
7215       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7216       unsigned VReg =
7217           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7218       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7219       if (ValVT.isScalarInteger() &&
7220           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7221         ArgValue =
7222             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7223       }
7224       InVals.push_back(ArgValue);
7225       continue;
7226     }
7227     if (VA.isMemLoc()) {
7228       const unsigned LocSize = LocVT.getStoreSize();
7229       const unsigned ValSize = ValVT.getStoreSize();
7230       assert((ValSize <= LocSize) &&
7231              "Object size is larger than size of MemLoc");
7232       int CurArgOffset = VA.getLocMemOffset();
7233       // Objects are right-justified because AIX is big-endian.
7234       if (LocSize > ValSize)
7235         CurArgOffset += LocSize - ValSize;
7236       // Potential tail calls could cause overwriting of argument stack slots.
7237       const bool IsImmutable =
7238           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7239             (CallConv == CallingConv::Fast));
7240       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7241       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7242       SDValue ArgValue =
7243           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7244       InVals.push_back(ArgValue);
7245       continue;
7246     }
7247   }
7248 
7249   // On AIX a minimum of 8 words is saved to the parameter save area.
7250   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7251   // Area that is at least reserved in the caller of this function.
7252   unsigned CallerReservedArea =
7253       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7254 
7255   // Set the size that is at least reserved in caller of this function. Tail
7256   // call optimized function's reserved stack space needs to be aligned so
7257   // that taking the difference between two stack areas will result in an
7258   // aligned stack.
7259   CallerReservedArea =
7260       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7261   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7262   FuncInfo->setMinReservedArea(CallerReservedArea);
7263 
7264   if (isVarArg) {
7265     FuncInfo->setVarArgsFrameIndex(
7266         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7267     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7268 
7269     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7270                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7271 
7272     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7273                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7274     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7275 
7276     // The fixed integer arguments of a variadic function are stored to the
7277     // VarArgsFrameIndex on the stack so that they may be loaded by
7278     // dereferencing the result of va_next.
7279     for (unsigned GPRIndex =
7280              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7281          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7282 
7283       const unsigned VReg =
7284           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7285                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7286 
7287       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7288       SDValue Store =
7289           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7290       MemOps.push_back(Store);
7291       // Increment the address for the next argument to store.
7292       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7293       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7294     }
7295   }
7296 
7297   if (!MemOps.empty())
7298     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7299 
7300   return Chain;
7301 }
7302 
7303 SDValue PPCTargetLowering::LowerCall_AIX(
7304     SDValue Chain, SDValue Callee, CallFlags CFlags,
7305     const SmallVectorImpl<ISD::OutputArg> &Outs,
7306     const SmallVectorImpl<SDValue> &OutVals,
7307     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7308     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7309     const CallBase *CB) const {
7310   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7311   // AIX ABI stack frame layout.
7312 
7313   assert((CFlags.CallConv == CallingConv::C ||
7314           CFlags.CallConv == CallingConv::Cold ||
7315           CFlags.CallConv == CallingConv::Fast) &&
7316          "Unexpected calling convention!");
7317 
7318   if (CFlags.IsPatchPoint)
7319     report_fatal_error("This call type is unimplemented on AIX.");
7320 
7321   const PPCSubtarget& Subtarget =
7322       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7323   if (Subtarget.hasAltivec())
7324     report_fatal_error("Altivec support is unimplemented on AIX.");
7325 
7326   MachineFunction &MF = DAG.getMachineFunction();
7327   SmallVector<CCValAssign, 16> ArgLocs;
7328   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7329                  *DAG.getContext());
7330 
7331   // Reserve space for the linkage save area (LSA) on the stack.
7332   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7333   //   [SP][CR][LR][2 x reserved][TOC].
7334   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7335   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7336   const bool IsPPC64 = Subtarget.isPPC64();
7337   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7338   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7339   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7340   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7341 
7342   // The prolog code of the callee may store up to 8 GPR argument registers to
7343   // the stack, allowing va_start to index over them in memory if the callee
7344   // is variadic.
7345   // Because we cannot tell if this is needed on the caller side, we have to
7346   // conservatively assume that it is needed.  As such, make sure we have at
7347   // least enough stack space for the caller to store the 8 GPRs.
7348   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7349   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7350                                      CCInfo.getNextStackOffset());
7351 
7352   // Adjust the stack pointer for the new arguments...
7353   // These operations are automatically eliminated by the prolog/epilog pass.
7354   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7355   SDValue CallSeqStart = Chain;
7356 
7357   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7358   SmallVector<SDValue, 8> MemOpChains;
7359 
7360   // Set up a copy of the stack pointer for loading and storing any
7361   // arguments that may not fit in the registers available for argument
7362   // passing.
7363   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7364                                    : DAG.getRegister(PPC::R1, MVT::i32);
7365 
7366   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7367     const unsigned ValNo = ArgLocs[I].getValNo();
7368     SDValue Arg = OutVals[ValNo];
7369     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7370 
7371     if (Flags.isByVal()) {
7372       const unsigned ByValSize = Flags.getByValSize();
7373 
7374       // Nothing to do for zero-sized ByVals on the caller side.
7375       if (!ByValSize) {
7376         ++I;
7377         continue;
7378       }
7379 
7380       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7381         return DAG.getExtLoad(
7382             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7383             (LoadOffset != 0)
7384                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7385                 : Arg,
7386             MachinePointerInfo(), VT);
7387       };
7388 
7389       unsigned LoadOffset = 0;
7390 
7391       // Initialize registers, which are fully occupied by the by-val argument.
7392       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7393         SDValue Load = GetLoad(PtrVT, LoadOffset);
7394         MemOpChains.push_back(Load.getValue(1));
7395         LoadOffset += PtrByteSize;
7396         const CCValAssign &ByValVA = ArgLocs[I++];
7397         assert(ByValVA.getValNo() == ValNo &&
7398                "Unexpected location for pass-by-value argument.");
7399         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7400       }
7401 
7402       if (LoadOffset == ByValSize)
7403         continue;
7404 
7405       // There must be one more loc to handle the remainder.
7406       assert(ArgLocs[I].getValNo() == ValNo &&
7407              "Expected additional location for by-value argument.");
7408 
7409       if (ArgLocs[I].isMemLoc()) {
7410         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7411         const CCValAssign &ByValVA = ArgLocs[I++];
7412         ISD::ArgFlagsTy MemcpyFlags = Flags;
7413         // Only memcpy the bytes that don't pass in register.
7414         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7415         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7416             (LoadOffset != 0)
7417                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7418                 : Arg,
7419             DAG.getObjectPtrOffset(dl, StackPtr,
7420                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7421             CallSeqStart, MemcpyFlags, DAG, dl);
7422         continue;
7423       }
7424 
7425       // Initialize the final register residue.
7426       // Any residue that occupies the final by-val arg register must be
7427       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7428       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7429       // 2 and 1 byte loads.
7430       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7431       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7432              "Unexpected register residue for by-value argument.");
7433       SDValue ResidueVal;
7434       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7435         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7436         const MVT VT =
7437             N == 1 ? MVT::i8
7438                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7439         SDValue Load = GetLoad(VT, LoadOffset);
7440         MemOpChains.push_back(Load.getValue(1));
7441         LoadOffset += N;
7442         Bytes += N;
7443 
7444         // By-val arguments are passed left-justfied in register.
7445         // Every load here needs to be shifted, otherwise a full register load
7446         // should have been used.
7447         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7448                "Unexpected load emitted during handling of pass-by-value "
7449                "argument.");
7450         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7451         EVT ShiftAmountTy =
7452             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7453         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7454         SDValue ShiftedLoad =
7455             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7456         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7457                                               ShiftedLoad)
7458                                 : ShiftedLoad;
7459       }
7460 
7461       const CCValAssign &ByValVA = ArgLocs[I++];
7462       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7463       continue;
7464     }
7465 
7466     CCValAssign &VA = ArgLocs[I++];
7467     const MVT LocVT = VA.getLocVT();
7468     const MVT ValVT = VA.getValVT();
7469 
7470     switch (VA.getLocInfo()) {
7471     default:
7472       report_fatal_error("Unexpected argument extension type.");
7473     case CCValAssign::Full:
7474       break;
7475     case CCValAssign::ZExt:
7476       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7477       break;
7478     case CCValAssign::SExt:
7479       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7480       break;
7481     }
7482 
7483     if (VA.isRegLoc() && !VA.needsCustom()) {
7484       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7485       continue;
7486     }
7487 
7488     if (VA.isMemLoc()) {
7489       SDValue PtrOff =
7490           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7491       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7492       MemOpChains.push_back(
7493           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7494 
7495       continue;
7496     }
7497 
7498     // Custom handling is used for GPR initializations for vararg float
7499     // arguments.
7500     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7501            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7502            "Unexpected register handling for calling convention.");
7503 
7504     SDValue ArgAsInt =
7505         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7506 
7507     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7508       // f32 in 32-bit GPR
7509       // f64 in 64-bit GPR
7510       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7511     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7512       // f32 in 64-bit GPR.
7513       RegsToPass.push_back(std::make_pair(
7514           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7515     else {
7516       // f64 in two 32-bit GPRs
7517       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7518       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7519              "Unexpected custom register for argument!");
7520       CCValAssign &GPR1 = VA;
7521       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7522                                      DAG.getConstant(32, dl, MVT::i8));
7523       RegsToPass.push_back(std::make_pair(
7524           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7525 
7526       if (I != E) {
7527         // If only 1 GPR was available, there will only be one custom GPR and
7528         // the argument will also pass in memory.
7529         CCValAssign &PeekArg = ArgLocs[I];
7530         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7531           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7532           CCValAssign &GPR2 = ArgLocs[I++];
7533           RegsToPass.push_back(std::make_pair(
7534               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7535         }
7536       }
7537     }
7538   }
7539 
7540   if (!MemOpChains.empty())
7541     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7542 
7543   // For indirect calls, we need to save the TOC base to the stack for
7544   // restoration after the call.
7545   if (CFlags.IsIndirect) {
7546     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7547     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7548     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7549     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7550     const unsigned TOCSaveOffset =
7551         Subtarget.getFrameLowering()->getTOCSaveOffset();
7552 
7553     setUsesTOCBasePtr(DAG);
7554     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7555     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7556     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7557     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7558     Chain = DAG.getStore(
7559         Val.getValue(1), dl, Val, AddPtr,
7560         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7561   }
7562 
7563   // Build a sequence of copy-to-reg nodes chained together with token chain
7564   // and flag operands which copy the outgoing args into the appropriate regs.
7565   SDValue InFlag;
7566   for (auto Reg : RegsToPass) {
7567     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7568     InFlag = Chain.getValue(1);
7569   }
7570 
7571   const int SPDiff = 0;
7572   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7573                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7574 }
7575 
7576 bool
7577 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7578                                   MachineFunction &MF, bool isVarArg,
7579                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7580                                   LLVMContext &Context) const {
7581   SmallVector<CCValAssign, 16> RVLocs;
7582   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7583   return CCInfo.CheckReturn(
7584       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7585                 ? RetCC_PPC_Cold
7586                 : RetCC_PPC);
7587 }
7588 
7589 SDValue
7590 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7591                                bool isVarArg,
7592                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7593                                const SmallVectorImpl<SDValue> &OutVals,
7594                                const SDLoc &dl, SelectionDAG &DAG) const {
7595   SmallVector<CCValAssign, 16> RVLocs;
7596   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7597                  *DAG.getContext());
7598   CCInfo.AnalyzeReturn(Outs,
7599                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7600                            ? RetCC_PPC_Cold
7601                            : RetCC_PPC);
7602 
7603   SDValue Flag;
7604   SmallVector<SDValue, 4> RetOps(1, Chain);
7605 
7606   // Copy the result values into the output registers.
7607   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7608     CCValAssign &VA = RVLocs[i];
7609     assert(VA.isRegLoc() && "Can only return in registers!");
7610 
7611     SDValue Arg = OutVals[RealResIdx];
7612 
7613     switch (VA.getLocInfo()) {
7614     default: llvm_unreachable("Unknown loc info!");
7615     case CCValAssign::Full: break;
7616     case CCValAssign::AExt:
7617       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7618       break;
7619     case CCValAssign::ZExt:
7620       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7621       break;
7622     case CCValAssign::SExt:
7623       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7624       break;
7625     }
7626     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7627       bool isLittleEndian = Subtarget.isLittleEndian();
7628       // Legalize ret f64 -> ret 2 x i32.
7629       SDValue SVal =
7630           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7631                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7632       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7633       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7634       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7635                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7636       Flag = Chain.getValue(1);
7637       VA = RVLocs[++i]; // skip ahead to next loc
7638       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7639     } else
7640       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7641     Flag = Chain.getValue(1);
7642     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7643   }
7644 
7645   RetOps[0] = Chain;  // Update chain.
7646 
7647   // Add the flag if we have it.
7648   if (Flag.getNode())
7649     RetOps.push_back(Flag);
7650 
7651   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7652 }
7653 
7654 SDValue
7655 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7656                                                 SelectionDAG &DAG) const {
7657   SDLoc dl(Op);
7658 
7659   // Get the correct type for integers.
7660   EVT IntVT = Op.getValueType();
7661 
7662   // Get the inputs.
7663   SDValue Chain = Op.getOperand(0);
7664   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7665   // Build a DYNAREAOFFSET node.
7666   SDValue Ops[2] = {Chain, FPSIdx};
7667   SDVTList VTs = DAG.getVTList(IntVT);
7668   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7669 }
7670 
7671 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7672                                              SelectionDAG &DAG) const {
7673   // When we pop the dynamic allocation we need to restore the SP link.
7674   SDLoc dl(Op);
7675 
7676   // Get the correct type for pointers.
7677   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7678 
7679   // Construct the stack pointer operand.
7680   bool isPPC64 = Subtarget.isPPC64();
7681   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7682   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7683 
7684   // Get the operands for the STACKRESTORE.
7685   SDValue Chain = Op.getOperand(0);
7686   SDValue SaveSP = Op.getOperand(1);
7687 
7688   // Load the old link SP.
7689   SDValue LoadLinkSP =
7690       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7691 
7692   // Restore the stack pointer.
7693   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7694 
7695   // Store the old link SP.
7696   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7697 }
7698 
7699 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7700   MachineFunction &MF = DAG.getMachineFunction();
7701   bool isPPC64 = Subtarget.isPPC64();
7702   EVT PtrVT = getPointerTy(MF.getDataLayout());
7703 
7704   // Get current frame pointer save index.  The users of this index will be
7705   // primarily DYNALLOC instructions.
7706   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7707   int RASI = FI->getReturnAddrSaveIndex();
7708 
7709   // If the frame pointer save index hasn't been defined yet.
7710   if (!RASI) {
7711     // Find out what the fix offset of the frame pointer save area.
7712     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7713     // Allocate the frame index for frame pointer save area.
7714     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7715     // Save the result.
7716     FI->setReturnAddrSaveIndex(RASI);
7717   }
7718   return DAG.getFrameIndex(RASI, PtrVT);
7719 }
7720 
7721 SDValue
7722 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7723   MachineFunction &MF = DAG.getMachineFunction();
7724   bool isPPC64 = Subtarget.isPPC64();
7725   EVT PtrVT = getPointerTy(MF.getDataLayout());
7726 
7727   // Get current frame pointer save index.  The users of this index will be
7728   // primarily DYNALLOC instructions.
7729   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7730   int FPSI = FI->getFramePointerSaveIndex();
7731 
7732   // If the frame pointer save index hasn't been defined yet.
7733   if (!FPSI) {
7734     // Find out what the fix offset of the frame pointer save area.
7735     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7736     // Allocate the frame index for frame pointer save area.
7737     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7738     // Save the result.
7739     FI->setFramePointerSaveIndex(FPSI);
7740   }
7741   return DAG.getFrameIndex(FPSI, PtrVT);
7742 }
7743 
7744 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7745                                                    SelectionDAG &DAG) const {
7746   MachineFunction &MF = DAG.getMachineFunction();
7747   // Get the inputs.
7748   SDValue Chain = Op.getOperand(0);
7749   SDValue Size  = Op.getOperand(1);
7750   SDLoc dl(Op);
7751 
7752   // Get the correct type for pointers.
7753   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7754   // Negate the size.
7755   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7756                                 DAG.getConstant(0, dl, PtrVT), Size);
7757   // Construct a node for the frame pointer save index.
7758   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7759   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7760   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7761   if (hasInlineStackProbe(MF))
7762     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7763   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7764 }
7765 
7766 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7767                                                      SelectionDAG &DAG) const {
7768   MachineFunction &MF = DAG.getMachineFunction();
7769 
7770   bool isPPC64 = Subtarget.isPPC64();
7771   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7772 
7773   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7774   return DAG.getFrameIndex(FI, PtrVT);
7775 }
7776 
7777 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7778                                                SelectionDAG &DAG) const {
7779   SDLoc DL(Op);
7780   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7781                      DAG.getVTList(MVT::i32, MVT::Other),
7782                      Op.getOperand(0), Op.getOperand(1));
7783 }
7784 
7785 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7786                                                 SelectionDAG &DAG) const {
7787   SDLoc DL(Op);
7788   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7789                      Op.getOperand(0), Op.getOperand(1));
7790 }
7791 
7792 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7793 
7794   assert(Op.getValueType() == MVT::i1 &&
7795          "Custom lowering only for i1 loads");
7796 
7797   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7798 
7799   SDLoc dl(Op);
7800   LoadSDNode *LD = cast<LoadSDNode>(Op);
7801 
7802   SDValue Chain = LD->getChain();
7803   SDValue BasePtr = LD->getBasePtr();
7804   MachineMemOperand *MMO = LD->getMemOperand();
7805 
7806   SDValue NewLD =
7807       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7808                      BasePtr, MVT::i8, MMO);
7809   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7810 
7811   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7812   return DAG.getMergeValues(Ops, dl);
7813 }
7814 
7815 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7816   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7817          "Custom lowering only for i1 stores");
7818 
7819   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7820 
7821   SDLoc dl(Op);
7822   StoreSDNode *ST = cast<StoreSDNode>(Op);
7823 
7824   SDValue Chain = ST->getChain();
7825   SDValue BasePtr = ST->getBasePtr();
7826   SDValue Value = ST->getValue();
7827   MachineMemOperand *MMO = ST->getMemOperand();
7828 
7829   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7830                       Value);
7831   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7832 }
7833 
7834 // FIXME: Remove this once the ANDI glue bug is fixed:
7835 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7836   assert(Op.getValueType() == MVT::i1 &&
7837          "Custom lowering only for i1 results");
7838 
7839   SDLoc DL(Op);
7840   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7841 }
7842 
7843 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7844                                                SelectionDAG &DAG) const {
7845 
7846   // Implements a vector truncate that fits in a vector register as a shuffle.
7847   // We want to legalize vector truncates down to where the source fits in
7848   // a vector register (and target is therefore smaller than vector register
7849   // size).  At that point legalization will try to custom lower the sub-legal
7850   // result and get here - where we can contain the truncate as a single target
7851   // operation.
7852 
7853   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7854   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7855   //
7856   // We will implement it for big-endian ordering as this (where x denotes
7857   // undefined):
7858   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7859   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7860   //
7861   // The same operation in little-endian ordering will be:
7862   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7863   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7864 
7865   assert(Op.getValueType().isVector() && "Vector type expected.");
7866 
7867   SDLoc DL(Op);
7868   SDValue N1 = Op.getOperand(0);
7869   unsigned SrcSize = N1.getValueType().getSizeInBits();
7870   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7871   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7872 
7873   EVT TrgVT = Op.getValueType();
7874   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7875   EVT EltVT = TrgVT.getVectorElementType();
7876   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7877   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7878 
7879   // First list the elements we want to keep.
7880   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7881   SmallVector<int, 16> ShuffV;
7882   if (Subtarget.isLittleEndian())
7883     for (unsigned i = 0; i < TrgNumElts; ++i)
7884       ShuffV.push_back(i * SizeMult);
7885   else
7886     for (unsigned i = 1; i <= TrgNumElts; ++i)
7887       ShuffV.push_back(i * SizeMult - 1);
7888 
7889   // Populate the remaining elements with undefs.
7890   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7891     // ShuffV.push_back(i + WideNumElts);
7892     ShuffV.push_back(WideNumElts + 1);
7893 
7894   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7895   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7896 }
7897 
7898 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7899 /// possible.
7900 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7901   // Not FP, or using SPE? Not a fsel.
7902   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7903       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7904     return Op;
7905 
7906   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7907 
7908   EVT ResVT = Op.getValueType();
7909   EVT CmpVT = Op.getOperand(0).getValueType();
7910   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7911   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7912   SDLoc dl(Op);
7913   SDNodeFlags Flags = Op.getNode()->getFlags();
7914 
7915   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7916   // presence of infinities.
7917   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7918     switch (CC) {
7919     default:
7920       break;
7921     case ISD::SETOGT:
7922     case ISD::SETGT:
7923       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7924     case ISD::SETOLT:
7925     case ISD::SETLT:
7926       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7927     }
7928   }
7929 
7930   // We might be able to do better than this under some circumstances, but in
7931   // general, fsel-based lowering of select is a finite-math-only optimization.
7932   // For more information, see section F.3 of the 2.06 ISA specification.
7933   // With ISA 3.0
7934   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7935       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7936     return Op;
7937 
7938   // If the RHS of the comparison is a 0.0, we don't need to do the
7939   // subtraction at all.
7940   SDValue Sel1;
7941   if (isFloatingPointZero(RHS))
7942     switch (CC) {
7943     default: break;       // SETUO etc aren't handled by fsel.
7944     case ISD::SETNE:
7945       std::swap(TV, FV);
7946       LLVM_FALLTHROUGH;
7947     case ISD::SETEQ:
7948       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7949         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7950       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7951       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7952         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7953       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7954                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7955     case ISD::SETULT:
7956     case ISD::SETLT:
7957       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7958       LLVM_FALLTHROUGH;
7959     case ISD::SETOGE:
7960     case ISD::SETGE:
7961       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7962         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7963       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7964     case ISD::SETUGT:
7965     case ISD::SETGT:
7966       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7967       LLVM_FALLTHROUGH;
7968     case ISD::SETOLE:
7969     case ISD::SETLE:
7970       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7971         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7972       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7973                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7974     }
7975 
7976   SDValue Cmp;
7977   switch (CC) {
7978   default: break;       // SETUO etc aren't handled by fsel.
7979   case ISD::SETNE:
7980     std::swap(TV, FV);
7981     LLVM_FALLTHROUGH;
7982   case ISD::SETEQ:
7983     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7984     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7985       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7986     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7987     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7988       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7989     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7990                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7991   case ISD::SETULT:
7992   case ISD::SETLT:
7993     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, 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::SETOGE:
7998   case ISD::SETGE:
7999     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, 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   case ISD::SETUGT:
8004   case ISD::SETGT:
8005     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8006     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8007       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8008     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8009   case ISD::SETOLE:
8010   case ISD::SETLE:
8011     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8012     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8013       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8014     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8015   }
8016   return Op;
8017 }
8018 
8019 static unsigned getPPCStrictOpcode(unsigned Opc) {
8020   switch (Opc) {
8021   default:
8022     llvm_unreachable("No strict version of this opcode!");
8023   case PPCISD::FCTIDZ:
8024     return PPCISD::STRICT_FCTIDZ;
8025   case PPCISD::FCTIWZ:
8026     return PPCISD::STRICT_FCTIWZ;
8027   case PPCISD::FCTIDUZ:
8028     return PPCISD::STRICT_FCTIDUZ;
8029   case PPCISD::FCTIWUZ:
8030     return PPCISD::STRICT_FCTIWUZ;
8031   case PPCISD::FCFID:
8032     return PPCISD::STRICT_FCFID;
8033   case PPCISD::FCFIDU:
8034     return PPCISD::STRICT_FCFIDU;
8035   case PPCISD::FCFIDS:
8036     return PPCISD::STRICT_FCFIDS;
8037   case PPCISD::FCFIDUS:
8038     return PPCISD::STRICT_FCFIDUS;
8039   }
8040 }
8041 
8042 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8043                               const PPCSubtarget &Subtarget) {
8044   SDLoc dl(Op);
8045   bool IsStrict = Op->isStrictFPOpcode();
8046   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8047                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8048   // For strict nodes, source is the second operand.
8049   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8050   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8051   assert(Src.getValueType().isFloatingPoint());
8052   if (Src.getValueType() == MVT::f32) {
8053     if (IsStrict) {
8054       Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other},
8055                         {Chain, Src});
8056       Chain = Src.getValue(1);
8057     } else
8058       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8059   }
8060   SDValue Conv;
8061   unsigned Opc = ISD::DELETED_NODE;
8062   switch (Op.getSimpleValueType().SimpleTy) {
8063   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8064   case MVT::i32:
8065     Opc = IsSigned ? PPCISD::FCTIWZ
8066                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8067     break;
8068   case MVT::i64:
8069     assert((IsSigned || Subtarget.hasFPCVT()) &&
8070            "i64 FP_TO_UINT is supported only with FPCVT");
8071     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8072   }
8073   if (IsStrict) {
8074     Opc = getPPCStrictOpcode(Opc);
8075     Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src});
8076   } else {
8077     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8078   }
8079   return Conv;
8080 }
8081 
8082 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8083                                                SelectionDAG &DAG,
8084                                                const SDLoc &dl) const {
8085   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8086   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8087                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8088   bool IsStrict = Op->isStrictFPOpcode();
8089 
8090   // Convert the FP value to an int value through memory.
8091   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8092                   (IsSigned || Subtarget.hasFPCVT());
8093   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8094   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8095   MachinePointerInfo MPI =
8096       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8097 
8098   // Emit a store to the stack slot.
8099   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8100   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8101   if (i32Stack) {
8102     MachineFunction &MF = DAG.getMachineFunction();
8103     Alignment = Align(4);
8104     MachineMemOperand *MMO =
8105         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8106     SDValue Ops[] = { Chain, Tmp, FIPtr };
8107     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8108               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8109   } else
8110     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8111 
8112   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8113   // add in a bias on big endian.
8114   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8115     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8116                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8117     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8118   }
8119 
8120   RLI.Chain = Chain;
8121   RLI.Ptr = FIPtr;
8122   RLI.MPI = MPI;
8123   RLI.Alignment = Alignment;
8124 }
8125 
8126 /// Custom lowers floating point to integer conversions to use
8127 /// the direct move instructions available in ISA 2.07 to avoid the
8128 /// need for load/store combinations.
8129 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8130                                                     SelectionDAG &DAG,
8131                                                     const SDLoc &dl) const {
8132   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8133   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8134   if (Op->isStrictFPOpcode())
8135     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8136   else
8137     return Mov;
8138 }
8139 
8140 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8141                                           const SDLoc &dl) const {
8142   bool IsStrict = Op->isStrictFPOpcode();
8143   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8144                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8145   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8146   // FP to INT conversions are legal for f128.
8147   if (Src.getValueType() == MVT::f128)
8148     return Op;
8149 
8150   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8151   // PPC (the libcall is not available).
8152   if (Src.getValueType() == MVT::ppcf128 && !IsStrict) {
8153     if (Op.getValueType() == MVT::i32) {
8154       if (IsSigned) {
8155         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8156                                  DAG.getIntPtrConstant(0, dl));
8157         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8158                                  DAG.getIntPtrConstant(1, dl));
8159 
8160         // Add the two halves of the long double in round-to-zero mode.
8161         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8162 
8163         // Now use a smaller FP_TO_SINT.
8164         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8165       } else {
8166         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8167         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8168         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8169         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8170         // FIXME: generated code sucks.
8171         // TODO: Are there fast-math-flags to propagate to this FSUB?
8172         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp);
8173         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8174         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8175                            DAG.getConstant(0x80000000, dl, MVT::i32));
8176         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8177         return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE);
8178       }
8179     }
8180 
8181     return SDValue();
8182   }
8183 
8184   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8185     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8186 
8187   ReuseLoadInfo RLI;
8188   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8189 
8190   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8191                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8192 }
8193 
8194 // We're trying to insert a regular store, S, and then a load, L. If the
8195 // incoming value, O, is a load, we might just be able to have our load use the
8196 // address used by O. However, we don't know if anything else will store to
8197 // that address before we can load from it. To prevent this situation, we need
8198 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8199 // the same chain operand as O, we create a token factor from the chain results
8200 // of O and L, and we replace all uses of O's chain result with that token
8201 // factor (see spliceIntoChain below for this last part).
8202 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8203                                             ReuseLoadInfo &RLI,
8204                                             SelectionDAG &DAG,
8205                                             ISD::LoadExtType ET) const {
8206   // Conservatively skip reusing for constrained FP nodes.
8207   if (Op->isStrictFPOpcode())
8208     return false;
8209 
8210   SDLoc dl(Op);
8211   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8212                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8213   if (ET == ISD::NON_EXTLOAD &&
8214       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8215       isOperationLegalOrCustom(Op.getOpcode(),
8216                                Op.getOperand(0).getValueType())) {
8217 
8218     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8219     return true;
8220   }
8221 
8222   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8223   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8224       LD->isNonTemporal())
8225     return false;
8226   if (LD->getMemoryVT() != MemVT)
8227     return false;
8228 
8229   RLI.Ptr = LD->getBasePtr();
8230   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8231     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8232            "Non-pre-inc AM on PPC?");
8233     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8234                           LD->getOffset());
8235   }
8236 
8237   RLI.Chain = LD->getChain();
8238   RLI.MPI = LD->getPointerInfo();
8239   RLI.IsDereferenceable = LD->isDereferenceable();
8240   RLI.IsInvariant = LD->isInvariant();
8241   RLI.Alignment = LD->getAlign();
8242   RLI.AAInfo = LD->getAAInfo();
8243   RLI.Ranges = LD->getRanges();
8244 
8245   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8246   return true;
8247 }
8248 
8249 // Given the head of the old chain, ResChain, insert a token factor containing
8250 // it and NewResChain, and make users of ResChain now be users of that token
8251 // factor.
8252 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8253 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8254                                         SDValue NewResChain,
8255                                         SelectionDAG &DAG) const {
8256   if (!ResChain)
8257     return;
8258 
8259   SDLoc dl(NewResChain);
8260 
8261   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8262                            NewResChain, DAG.getUNDEF(MVT::Other));
8263   assert(TF.getNode() != NewResChain.getNode() &&
8264          "A new TF really is required here");
8265 
8266   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8267   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8268 }
8269 
8270 /// Analyze profitability of direct move
8271 /// prefer float load to int load plus direct move
8272 /// when there is no integer use of int load
8273 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8274   SDNode *Origin = Op.getOperand(0).getNode();
8275   if (Origin->getOpcode() != ISD::LOAD)
8276     return true;
8277 
8278   // If there is no LXSIBZX/LXSIHZX, like Power8,
8279   // prefer direct move if the memory size is 1 or 2 bytes.
8280   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8281   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8282     return true;
8283 
8284   for (SDNode::use_iterator UI = Origin->use_begin(),
8285                             UE = Origin->use_end();
8286        UI != UE; ++UI) {
8287 
8288     // Only look at the users of the loaded value.
8289     if (UI.getUse().get().getResNo() != 0)
8290       continue;
8291 
8292     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8293         UI->getOpcode() != ISD::UINT_TO_FP &&
8294         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8295         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8296       return true;
8297   }
8298 
8299   return false;
8300 }
8301 
8302 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8303                               const PPCSubtarget &Subtarget,
8304                               SDValue Chain = SDValue()) {
8305   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8306                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8307   SDLoc dl(Op);
8308   // If we have FCFIDS, then use it when converting to single-precision.
8309   // Otherwise, convert to double-precision and then round.
8310   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8311   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8312                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8313   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8314   if (Op->isStrictFPOpcode()) {
8315     if (!Chain)
8316       Chain = Op.getOperand(0);
8317     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, {ConvTy, MVT::Other},
8318                        {Chain, Src});
8319   } else
8320     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8321 }
8322 
8323 /// Custom lowers integer to floating point conversions to use
8324 /// the direct move instructions available in ISA 2.07 to avoid the
8325 /// need for load/store combinations.
8326 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8327                                                     SelectionDAG &DAG,
8328                                                     const SDLoc &dl) const {
8329   assert((Op.getValueType() == MVT::f32 ||
8330           Op.getValueType() == MVT::f64) &&
8331          "Invalid floating point type as target of conversion");
8332   assert(Subtarget.hasFPCVT() &&
8333          "Int to FP conversions with direct moves require FPCVT");
8334   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8335   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8336   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8337                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8338   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8339   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8340   return convertIntToFP(Op, Mov, DAG, Subtarget);
8341 }
8342 
8343 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8344 
8345   EVT VecVT = Vec.getValueType();
8346   assert(VecVT.isVector() && "Expected a vector type.");
8347   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8348 
8349   EVT EltVT = VecVT.getVectorElementType();
8350   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8351   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8352 
8353   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8354   SmallVector<SDValue, 16> Ops(NumConcat);
8355   Ops[0] = Vec;
8356   SDValue UndefVec = DAG.getUNDEF(VecVT);
8357   for (unsigned i = 1; i < NumConcat; ++i)
8358     Ops[i] = UndefVec;
8359 
8360   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8361 }
8362 
8363 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8364                                                 const SDLoc &dl) const {
8365   bool IsStrict = Op->isStrictFPOpcode();
8366   unsigned Opc = Op.getOpcode();
8367   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8368   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8369           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8370          "Unexpected conversion type");
8371   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8372          "Supports conversions to v2f64/v4f32 only.");
8373 
8374   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8375   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8376 
8377   SDValue Wide = widenVec(DAG, Src, dl);
8378   EVT WideVT = Wide.getValueType();
8379   unsigned WideNumElts = WideVT.getVectorNumElements();
8380   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8381 
8382   SmallVector<int, 16> ShuffV;
8383   for (unsigned i = 0; i < WideNumElts; ++i)
8384     ShuffV.push_back(i + WideNumElts);
8385 
8386   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8387   int SaveElts = FourEltRes ? 4 : 2;
8388   if (Subtarget.isLittleEndian())
8389     for (int i = 0; i < SaveElts; i++)
8390       ShuffV[i * Stride] = i;
8391   else
8392     for (int i = 1; i <= SaveElts; i++)
8393       ShuffV[i * Stride - 1] = i - 1;
8394 
8395   SDValue ShuffleSrc2 =
8396       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8397   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8398 
8399   SDValue Extend;
8400   if (SignedConv) {
8401     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8402     EVT ExtVT = Src.getValueType();
8403     if (Subtarget.hasP9Altivec())
8404       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8405                                IntermediateVT.getVectorNumElements());
8406 
8407     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8408                          DAG.getValueType(ExtVT));
8409   } else
8410     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8411 
8412   if (IsStrict)
8413     return DAG.getNode(Opc, dl, {Op.getValueType(), MVT::Other},
8414                        {Op.getOperand(0), Extend});
8415 
8416   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8417 }
8418 
8419 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8420                                           SelectionDAG &DAG) const {
8421   SDLoc dl(Op);
8422   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8423                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8424   bool IsStrict = Op->isStrictFPOpcode();
8425   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8426   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8427 
8428   EVT InVT = Src.getValueType();
8429   EVT OutVT = Op.getValueType();
8430   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8431       isOperationCustom(Op.getOpcode(), InVT))
8432     return LowerINT_TO_FPVector(Op, DAG, dl);
8433 
8434   // Conversions to f128 are legal.
8435   if (Op.getValueType() == MVT::f128)
8436     return Op;
8437 
8438   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8439   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8440     return SDValue();
8441 
8442   if (Src.getValueType() == MVT::i1)
8443     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8444                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8445                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8446 
8447   // If we have direct moves, we can do all the conversion, skip the store/load
8448   // however, without FPCVT we can't do most conversions.
8449   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8450       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8451     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8452 
8453   assert((IsSigned || Subtarget.hasFPCVT()) &&
8454          "UINT_TO_FP is supported only with FPCVT");
8455 
8456   if (Src.getValueType() == MVT::i64) {
8457     SDValue SINT = Src;
8458     // When converting to single-precision, we actually need to convert
8459     // to double-precision first and then round to single-precision.
8460     // To avoid double-rounding effects during that operation, we have
8461     // to prepare the input operand.  Bits that might be truncated when
8462     // converting to double-precision are replaced by a bit that won't
8463     // be lost at this stage, but is below the single-precision rounding
8464     // position.
8465     //
8466     // However, if -enable-unsafe-fp-math is in effect, accept double
8467     // rounding to avoid the extra overhead.
8468     if (Op.getValueType() == MVT::f32 &&
8469         !Subtarget.hasFPCVT() &&
8470         !DAG.getTarget().Options.UnsafeFPMath) {
8471 
8472       // Twiddle input to make sure the low 11 bits are zero.  (If this
8473       // is the case, we are guaranteed the value will fit into the 53 bit
8474       // mantissa of an IEEE double-precision value without rounding.)
8475       // If any of those low 11 bits were not zero originally, make sure
8476       // bit 12 (value 2048) is set instead, so that the final rounding
8477       // to single-precision gets the correct result.
8478       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8479                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8480       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8481                           Round, DAG.getConstant(2047, dl, MVT::i64));
8482       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8483       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8484                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8485 
8486       // However, we cannot use that value unconditionally: if the magnitude
8487       // of the input value is small, the bit-twiddling we did above might
8488       // end up visibly changing the output.  Fortunately, in that case, we
8489       // don't need to twiddle bits since the original input will convert
8490       // exactly to double-precision floating-point already.  Therefore,
8491       // construct a conditional to use the original value if the top 11
8492       // bits are all sign-bit copies, and use the rounded value computed
8493       // above otherwise.
8494       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8495                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8496       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8497                          Cond, DAG.getConstant(1, dl, MVT::i64));
8498       Cond = DAG.getSetCC(
8499           dl,
8500           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8501           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8502 
8503       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8504     }
8505 
8506     ReuseLoadInfo RLI;
8507     SDValue Bits;
8508 
8509     MachineFunction &MF = DAG.getMachineFunction();
8510     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8511       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8512                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8513       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8514     } else if (Subtarget.hasLFIWAX() &&
8515                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8516       MachineMemOperand *MMO =
8517         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8518                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8519       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8520       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8521                                      DAG.getVTList(MVT::f64, MVT::Other),
8522                                      Ops, MVT::i32, MMO);
8523       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8524     } else if (Subtarget.hasFPCVT() &&
8525                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8526       MachineMemOperand *MMO =
8527         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8528                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8529       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8530       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8531                                      DAG.getVTList(MVT::f64, MVT::Other),
8532                                      Ops, MVT::i32, MMO);
8533       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8534     } else if (((Subtarget.hasLFIWAX() &&
8535                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8536                 (Subtarget.hasFPCVT() &&
8537                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8538                SINT.getOperand(0).getValueType() == MVT::i32) {
8539       MachineFrameInfo &MFI = MF.getFrameInfo();
8540       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8541 
8542       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8543       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8544 
8545       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8546                                    MachinePointerInfo::getFixedStack(
8547                                        DAG.getMachineFunction(), FrameIdx));
8548       Chain = Store;
8549 
8550       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8551              "Expected an i32 store");
8552 
8553       RLI.Ptr = FIdx;
8554       RLI.Chain = Chain;
8555       RLI.MPI =
8556           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8557       RLI.Alignment = Align(4);
8558 
8559       MachineMemOperand *MMO =
8560         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8561                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8562       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8563       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8564                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8565                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8566                                      Ops, MVT::i32, MMO);
8567       Chain = Bits.getValue(1);
8568     } else
8569       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8570 
8571     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8572     if (IsStrict)
8573       Chain = FP.getValue(1);
8574 
8575     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8576       if (IsStrict)
8577         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other},
8578                          {Chain, FP, DAG.getIntPtrConstant(0, dl)});
8579       else
8580         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8581                          DAG.getIntPtrConstant(0, dl));
8582     }
8583     return FP;
8584   }
8585 
8586   assert(Src.getValueType() == MVT::i32 &&
8587          "Unhandled INT_TO_FP type in custom expander!");
8588   // Since we only generate this in 64-bit mode, we can take advantage of
8589   // 64-bit registers.  In particular, sign extend the input value into the
8590   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8591   // then lfd it and fcfid it.
8592   MachineFunction &MF = DAG.getMachineFunction();
8593   MachineFrameInfo &MFI = MF.getFrameInfo();
8594   EVT PtrVT = getPointerTy(MF.getDataLayout());
8595 
8596   SDValue Ld;
8597   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8598     ReuseLoadInfo RLI;
8599     bool ReusingLoad;
8600     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8601       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8602       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8603 
8604       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8605                                    MachinePointerInfo::getFixedStack(
8606                                        DAG.getMachineFunction(), FrameIdx));
8607       Chain = Store;
8608 
8609       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8610              "Expected an i32 store");
8611 
8612       RLI.Ptr = FIdx;
8613       RLI.Chain = Chain;
8614       RLI.MPI =
8615           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8616       RLI.Alignment = Align(4);
8617     }
8618 
8619     MachineMemOperand *MMO =
8620       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8621                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8622     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8623     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8624                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8625                                  MVT::i32, MMO);
8626     Chain = Ld.getValue(1);
8627     if (ReusingLoad)
8628       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8629   } else {
8630     assert(Subtarget.isPPC64() &&
8631            "i32->FP without LFIWAX supported only on PPC64");
8632 
8633     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8634     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8635 
8636     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8637 
8638     // STD the extended value into the stack slot.
8639     SDValue Store = DAG.getStore(
8640         Chain, dl, Ext64, FIdx,
8641         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8642     Chain = Store;
8643 
8644     // Load the value as a double.
8645     Ld = DAG.getLoad(
8646         MVT::f64, dl, Chain, FIdx,
8647         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8648     Chain = Ld.getValue(1);
8649   }
8650 
8651   // FCFID it and return it.
8652   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8653   if (IsStrict)
8654     Chain = FP.getValue(1);
8655   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8656     if (IsStrict)
8657       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other},
8658                        {Chain, FP, DAG.getIntPtrConstant(0, dl)});
8659     else
8660       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8661                        DAG.getIntPtrConstant(0, dl));
8662   }
8663   return FP;
8664 }
8665 
8666 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8667                                             SelectionDAG &DAG) const {
8668   SDLoc dl(Op);
8669   /*
8670    The rounding mode is in bits 30:31 of FPSR, and has the following
8671    settings:
8672      00 Round to nearest
8673      01 Round to 0
8674      10 Round to +inf
8675      11 Round to -inf
8676 
8677   FLT_ROUNDS, on the other hand, expects the following:
8678     -1 Undefined
8679      0 Round to 0
8680      1 Round to nearest
8681      2 Round to +inf
8682      3 Round to -inf
8683 
8684   To perform the conversion, we do:
8685     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8686   */
8687 
8688   MachineFunction &MF = DAG.getMachineFunction();
8689   EVT VT = Op.getValueType();
8690   EVT PtrVT = getPointerTy(MF.getDataLayout());
8691 
8692   // Save FP Control Word to register
8693   SDValue Chain = Op.getOperand(0);
8694   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8695   Chain = MFFS.getValue(1);
8696 
8697   // Save FP register to stack slot
8698   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8699   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8700   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8701 
8702   // Load FP Control Word from low 32 bits of stack slot.
8703   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8704   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8705   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8706   Chain = CWD.getValue(1);
8707 
8708   // Transform as necessary
8709   SDValue CWD1 =
8710     DAG.getNode(ISD::AND, dl, MVT::i32,
8711                 CWD, DAG.getConstant(3, dl, MVT::i32));
8712   SDValue CWD2 =
8713     DAG.getNode(ISD::SRL, dl, MVT::i32,
8714                 DAG.getNode(ISD::AND, dl, MVT::i32,
8715                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8716                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8717                             DAG.getConstant(3, dl, MVT::i32)),
8718                 DAG.getConstant(1, dl, MVT::i32));
8719 
8720   SDValue RetVal =
8721     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8722 
8723   RetVal =
8724       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8725                   dl, VT, RetVal);
8726 
8727   return DAG.getMergeValues({RetVal, Chain}, dl);
8728 }
8729 
8730 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8731   EVT VT = Op.getValueType();
8732   unsigned BitWidth = VT.getSizeInBits();
8733   SDLoc dl(Op);
8734   assert(Op.getNumOperands() == 3 &&
8735          VT == Op.getOperand(1).getValueType() &&
8736          "Unexpected SHL!");
8737 
8738   // Expand into a bunch of logical ops.  Note that these ops
8739   // depend on the PPC behavior for oversized shift amounts.
8740   SDValue Lo = Op.getOperand(0);
8741   SDValue Hi = Op.getOperand(1);
8742   SDValue Amt = Op.getOperand(2);
8743   EVT AmtVT = Amt.getValueType();
8744 
8745   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8746                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8747   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8748   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8749   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8750   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8751                              DAG.getConstant(-BitWidth, dl, AmtVT));
8752   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8753   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8754   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8755   SDValue OutOps[] = { OutLo, OutHi };
8756   return DAG.getMergeValues(OutOps, dl);
8757 }
8758 
8759 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8760   EVT VT = Op.getValueType();
8761   SDLoc dl(Op);
8762   unsigned BitWidth = VT.getSizeInBits();
8763   assert(Op.getNumOperands() == 3 &&
8764          VT == Op.getOperand(1).getValueType() &&
8765          "Unexpected SRL!");
8766 
8767   // Expand into a bunch of logical ops.  Note that these ops
8768   // depend on the PPC behavior for oversized shift amounts.
8769   SDValue Lo = Op.getOperand(0);
8770   SDValue Hi = Op.getOperand(1);
8771   SDValue Amt = Op.getOperand(2);
8772   EVT AmtVT = Amt.getValueType();
8773 
8774   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8775                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8776   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8777   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8778   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8779   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8780                              DAG.getConstant(-BitWidth, dl, AmtVT));
8781   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8782   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8783   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8784   SDValue OutOps[] = { OutLo, OutHi };
8785   return DAG.getMergeValues(OutOps, dl);
8786 }
8787 
8788 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8789   SDLoc dl(Op);
8790   EVT VT = Op.getValueType();
8791   unsigned BitWidth = VT.getSizeInBits();
8792   assert(Op.getNumOperands() == 3 &&
8793          VT == Op.getOperand(1).getValueType() &&
8794          "Unexpected SRA!");
8795 
8796   // Expand into a bunch of logical ops, followed by a select_cc.
8797   SDValue Lo = Op.getOperand(0);
8798   SDValue Hi = Op.getOperand(1);
8799   SDValue Amt = Op.getOperand(2);
8800   EVT AmtVT = Amt.getValueType();
8801 
8802   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8803                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8804   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8805   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8806   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8807   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8808                              DAG.getConstant(-BitWidth, dl, AmtVT));
8809   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8810   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8811   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8812                                   Tmp4, Tmp6, ISD::SETLE);
8813   SDValue OutOps[] = { OutLo, OutHi };
8814   return DAG.getMergeValues(OutOps, dl);
8815 }
8816 
8817 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8818                                             SelectionDAG &DAG) const {
8819   SDLoc dl(Op);
8820   EVT VT = Op.getValueType();
8821   unsigned BitWidth = VT.getSizeInBits();
8822 
8823   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8824   SDValue X = Op.getOperand(0);
8825   SDValue Y = Op.getOperand(1);
8826   SDValue Z = Op.getOperand(2);
8827   EVT AmtVT = Z.getValueType();
8828 
8829   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8830   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8831   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8832   // on PowerPC shift by BW being well defined.
8833   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8834                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8835   SDValue SubZ =
8836       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8837   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8838   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8839   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8840 }
8841 
8842 //===----------------------------------------------------------------------===//
8843 // Vector related lowering.
8844 //
8845 
8846 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8847 /// element size of SplatSize. Cast the result to VT.
8848 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8849                                       SelectionDAG &DAG, const SDLoc &dl) {
8850   static const MVT VTys[] = { // canonical VT to use for each size.
8851     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8852   };
8853 
8854   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8855 
8856   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8857   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8858     SplatSize = 1;
8859     Val = 0xFF;
8860   }
8861 
8862   EVT CanonicalVT = VTys[SplatSize-1];
8863 
8864   // Build a canonical splat for this value.
8865   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8866 }
8867 
8868 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8869 /// specified intrinsic ID.
8870 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8871                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8872   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8873   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8874                      DAG.getConstant(IID, dl, MVT::i32), Op);
8875 }
8876 
8877 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8878 /// specified intrinsic ID.
8879 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8880                                 SelectionDAG &DAG, const SDLoc &dl,
8881                                 EVT DestVT = MVT::Other) {
8882   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8883   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8884                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8885 }
8886 
8887 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8888 /// specified intrinsic ID.
8889 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8890                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8891                                 EVT DestVT = MVT::Other) {
8892   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8893   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8894                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8895 }
8896 
8897 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8898 /// amount.  The result has the specified value type.
8899 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8900                            SelectionDAG &DAG, const SDLoc &dl) {
8901   // Force LHS/RHS to be the right type.
8902   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8903   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8904 
8905   int Ops[16];
8906   for (unsigned i = 0; i != 16; ++i)
8907     Ops[i] = i + Amt;
8908   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8909   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8910 }
8911 
8912 /// Do we have an efficient pattern in a .td file for this node?
8913 ///
8914 /// \param V - pointer to the BuildVectorSDNode being matched
8915 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8916 ///
8917 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8918 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8919 /// the opposite is true (expansion is beneficial) are:
8920 /// - The node builds a vector out of integers that are not 32 or 64-bits
8921 /// - The node builds a vector out of constants
8922 /// - The node is a "load-and-splat"
8923 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8924 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8925                                             bool HasDirectMove,
8926                                             bool HasP8Vector) {
8927   EVT VecVT = V->getValueType(0);
8928   bool RightType = VecVT == MVT::v2f64 ||
8929     (HasP8Vector && VecVT == MVT::v4f32) ||
8930     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8931   if (!RightType)
8932     return false;
8933 
8934   bool IsSplat = true;
8935   bool IsLoad = false;
8936   SDValue Op0 = V->getOperand(0);
8937 
8938   // This function is called in a block that confirms the node is not a constant
8939   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8940   // different constants.
8941   if (V->isConstant())
8942     return false;
8943   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8944     if (V->getOperand(i).isUndef())
8945       return false;
8946     // We want to expand nodes that represent load-and-splat even if the
8947     // loaded value is a floating point truncation or conversion to int.
8948     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8949         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8950          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8951         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8952          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8953         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8954          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8955       IsLoad = true;
8956     // If the operands are different or the input is not a load and has more
8957     // uses than just this BV node, then it isn't a splat.
8958     if (V->getOperand(i) != Op0 ||
8959         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8960       IsSplat = false;
8961   }
8962   return !(IsSplat && IsLoad);
8963 }
8964 
8965 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8966 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8967 
8968   SDLoc dl(Op);
8969   SDValue Op0 = Op->getOperand(0);
8970 
8971   if ((Op.getValueType() != MVT::f128) ||
8972       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8973       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8974       (Op0.getOperand(1).getValueType() != MVT::i64))
8975     return SDValue();
8976 
8977   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8978                      Op0.getOperand(1));
8979 }
8980 
8981 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8982   const SDValue *InputLoad = &Op;
8983   if (InputLoad->getOpcode() == ISD::BITCAST)
8984     InputLoad = &InputLoad->getOperand(0);
8985   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8986       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8987     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8988     InputLoad = &InputLoad->getOperand(0);
8989   }
8990   if (InputLoad->getOpcode() != ISD::LOAD)
8991     return nullptr;
8992   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8993   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8994 }
8995 
8996 // Convert the argument APFloat to a single precision APFloat if there is no
8997 // loss in information during the conversion to single precision APFloat and the
8998 // resulting number is not a denormal number. Return true if successful.
8999 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9000   APFloat APFloatToConvert = ArgAPFloat;
9001   bool LosesInfo = true;
9002   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9003                            &LosesInfo);
9004   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9005   if (Success)
9006     ArgAPFloat = APFloatToConvert;
9007   return Success;
9008 }
9009 
9010 // Bitcast the argument APInt to a double and convert it to a single precision
9011 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9012 // argument if there is no loss in information during the conversion from
9013 // double to single precision APFloat and the resulting number is not a denormal
9014 // number. Return true if successful.
9015 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9016   double DpValue = ArgAPInt.bitsToDouble();
9017   APFloat APFloatDp(DpValue);
9018   bool Success = convertToNonDenormSingle(APFloatDp);
9019   if (Success)
9020     ArgAPInt = APFloatDp.bitcastToAPInt();
9021   return Success;
9022 }
9023 
9024 // If this is a case we can't handle, return null and let the default
9025 // expansion code take care of it.  If we CAN select this case, and if it
9026 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9027 // this case more efficiently than a constant pool load, lower it to the
9028 // sequence of ops that should be used.
9029 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9030                                              SelectionDAG &DAG) const {
9031   SDLoc dl(Op);
9032   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9033   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9034 
9035   // Check if this is a splat of a constant value.
9036   APInt APSplatBits, APSplatUndef;
9037   unsigned SplatBitSize;
9038   bool HasAnyUndefs;
9039   bool BVNIsConstantSplat =
9040       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9041                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9042 
9043   // If it is a splat of a double, check if we can shrink it to a 32 bit
9044   // non-denormal float which when converted back to double gives us the same
9045   // double. This is to exploit the XXSPLTIDP instruction.
9046   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9047       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9048       convertToNonDenormSingle(APSplatBits)) {
9049     SDValue SplatNode = DAG.getNode(
9050         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9051         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9052     return DAG.getBitcast(Op.getValueType(), SplatNode);
9053   }
9054 
9055   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9056 
9057     bool IsPermutedLoad = false;
9058     const SDValue *InputLoad =
9059         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9060     // Handle load-and-splat patterns as we have instructions that will do this
9061     // in one go.
9062     if (InputLoad && DAG.isSplatValue(Op, true)) {
9063       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9064 
9065       // We have handling for 4 and 8 byte elements.
9066       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9067 
9068       // Checking for a single use of this load, we have to check for vector
9069       // width (128 bits) / ElementSize uses (since each operand of the
9070       // BUILD_VECTOR is a separate use of the value.
9071       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9072           ((Subtarget.hasVSX() && ElementSize == 64) ||
9073            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9074         SDValue Ops[] = {
9075           LD->getChain(),    // Chain
9076           LD->getBasePtr(),  // Ptr
9077           DAG.getValueType(Op.getValueType()) // VT
9078         };
9079         return
9080           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9081                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9082                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9083       }
9084     }
9085 
9086     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9087     // lowered to VSX instructions under certain conditions.
9088     // Without VSX, there is no pattern more efficient than expanding the node.
9089     if (Subtarget.hasVSX() &&
9090         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9091                                         Subtarget.hasP8Vector()))
9092       return Op;
9093     return SDValue();
9094   }
9095 
9096   uint64_t SplatBits = APSplatBits.getZExtValue();
9097   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9098   unsigned SplatSize = SplatBitSize / 8;
9099 
9100   // First, handle single instruction cases.
9101 
9102   // All zeros?
9103   if (SplatBits == 0) {
9104     // Canonicalize all zero vectors to be v4i32.
9105     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9106       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9107       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9108     }
9109     return Op;
9110   }
9111 
9112   // We have XXSPLTIW for constant splats four bytes wide.
9113   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9114   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9115   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9116   // turned into a 4-byte splat of 0xABABABAB.
9117   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9118     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
9119                                   Op.getValueType(), DAG, dl);
9120 
9121   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9122     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9123                                   dl);
9124 
9125   // We have XXSPLTIB for constant splats one byte wide.
9126   if (Subtarget.hasP9Vector() && SplatSize == 1)
9127     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9128                                   dl);
9129 
9130   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9131   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9132                     (32-SplatBitSize));
9133   if (SextVal >= -16 && SextVal <= 15)
9134     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9135                                   dl);
9136 
9137   // Two instruction sequences.
9138 
9139   // If this value is in the range [-32,30] and is even, use:
9140   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9141   // If this value is in the range [17,31] and is odd, use:
9142   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9143   // If this value is in the range [-31,-17] and is odd, use:
9144   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9145   // Note the last two are three-instruction sequences.
9146   if (SextVal >= -32 && SextVal <= 31) {
9147     // To avoid having these optimizations undone by constant folding,
9148     // we convert to a pseudo that will be expanded later into one of
9149     // the above forms.
9150     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9151     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9152               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9153     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9154     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9155     if (VT == Op.getValueType())
9156       return RetVal;
9157     else
9158       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9159   }
9160 
9161   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9162   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9163   // for fneg/fabs.
9164   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9165     // Make -1 and vspltisw -1:
9166     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9167 
9168     // Make the VSLW intrinsic, computing 0x8000_0000.
9169     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9170                                    OnesV, DAG, dl);
9171 
9172     // xor by OnesV to invert it.
9173     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9174     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9175   }
9176 
9177   // Check to see if this is a wide variety of vsplti*, binop self cases.
9178   static const signed char SplatCsts[] = {
9179     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9180     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9181   };
9182 
9183   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9184     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9185     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9186     int i = SplatCsts[idx];
9187 
9188     // Figure out what shift amount will be used by altivec if shifted by i in
9189     // this splat size.
9190     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9191 
9192     // vsplti + shl self.
9193     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9194       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9195       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9196         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9197         Intrinsic::ppc_altivec_vslw
9198       };
9199       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9200       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9201     }
9202 
9203     // vsplti + srl self.
9204     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9205       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9206       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9207         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9208         Intrinsic::ppc_altivec_vsrw
9209       };
9210       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9211       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9212     }
9213 
9214     // vsplti + sra self.
9215     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9216       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9217       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9218         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9219         Intrinsic::ppc_altivec_vsraw
9220       };
9221       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9222       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9223     }
9224 
9225     // vsplti + rol self.
9226     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9227                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9228       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9229       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9230         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9231         Intrinsic::ppc_altivec_vrlw
9232       };
9233       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9234       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9235     }
9236 
9237     // t = vsplti c, result = vsldoi t, t, 1
9238     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9239       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9240       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9241       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9242     }
9243     // t = vsplti c, result = vsldoi t, t, 2
9244     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9245       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9246       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9247       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9248     }
9249     // t = vsplti c, result = vsldoi t, t, 3
9250     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9251       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9252       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9253       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9254     }
9255   }
9256 
9257   return SDValue();
9258 }
9259 
9260 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9261 /// the specified operations to build the shuffle.
9262 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9263                                       SDValue RHS, SelectionDAG &DAG,
9264                                       const SDLoc &dl) {
9265   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9266   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9267   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9268 
9269   enum {
9270     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9271     OP_VMRGHW,
9272     OP_VMRGLW,
9273     OP_VSPLTISW0,
9274     OP_VSPLTISW1,
9275     OP_VSPLTISW2,
9276     OP_VSPLTISW3,
9277     OP_VSLDOI4,
9278     OP_VSLDOI8,
9279     OP_VSLDOI12
9280   };
9281 
9282   if (OpNum == OP_COPY) {
9283     if (LHSID == (1*9+2)*9+3) return LHS;
9284     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9285     return RHS;
9286   }
9287 
9288   SDValue OpLHS, OpRHS;
9289   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9290   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9291 
9292   int ShufIdxs[16];
9293   switch (OpNum) {
9294   default: llvm_unreachable("Unknown i32 permute!");
9295   case OP_VMRGHW:
9296     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9297     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9298     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9299     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9300     break;
9301   case OP_VMRGLW:
9302     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9303     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9304     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9305     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9306     break;
9307   case OP_VSPLTISW0:
9308     for (unsigned i = 0; i != 16; ++i)
9309       ShufIdxs[i] = (i&3)+0;
9310     break;
9311   case OP_VSPLTISW1:
9312     for (unsigned i = 0; i != 16; ++i)
9313       ShufIdxs[i] = (i&3)+4;
9314     break;
9315   case OP_VSPLTISW2:
9316     for (unsigned i = 0; i != 16; ++i)
9317       ShufIdxs[i] = (i&3)+8;
9318     break;
9319   case OP_VSPLTISW3:
9320     for (unsigned i = 0; i != 16; ++i)
9321       ShufIdxs[i] = (i&3)+12;
9322     break;
9323   case OP_VSLDOI4:
9324     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9325   case OP_VSLDOI8:
9326     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9327   case OP_VSLDOI12:
9328     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9329   }
9330   EVT VT = OpLHS.getValueType();
9331   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9332   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9333   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9334   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9335 }
9336 
9337 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9338 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9339 /// SDValue.
9340 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9341                                            SelectionDAG &DAG) const {
9342   const unsigned BytesInVector = 16;
9343   bool IsLE = Subtarget.isLittleEndian();
9344   SDLoc dl(N);
9345   SDValue V1 = N->getOperand(0);
9346   SDValue V2 = N->getOperand(1);
9347   unsigned ShiftElts = 0, InsertAtByte = 0;
9348   bool Swap = false;
9349 
9350   // Shifts required to get the byte we want at element 7.
9351   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9352                                    0, 15, 14, 13, 12, 11, 10, 9};
9353   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9354                                 1, 2,  3,  4,  5,  6,  7,  8};
9355 
9356   ArrayRef<int> Mask = N->getMask();
9357   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9358 
9359   // For each mask element, find out if we're just inserting something
9360   // from V2 into V1 or vice versa.
9361   // Possible permutations inserting an element from V2 into V1:
9362   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9363   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9364   //   ...
9365   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9366   // Inserting from V1 into V2 will be similar, except mask range will be
9367   // [16,31].
9368 
9369   bool FoundCandidate = false;
9370   // If both vector operands for the shuffle are the same vector, the mask
9371   // will contain only elements from the first one and the second one will be
9372   // undef.
9373   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9374   // Go through the mask of half-words to find an element that's being moved
9375   // from one vector to the other.
9376   for (unsigned i = 0; i < BytesInVector; ++i) {
9377     unsigned CurrentElement = Mask[i];
9378     // If 2nd operand is undefined, we should only look for element 7 in the
9379     // Mask.
9380     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9381       continue;
9382 
9383     bool OtherElementsInOrder = true;
9384     // Examine the other elements in the Mask to see if they're in original
9385     // order.
9386     for (unsigned j = 0; j < BytesInVector; ++j) {
9387       if (j == i)
9388         continue;
9389       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9390       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9391       // in which we always assume we're always picking from the 1st operand.
9392       int MaskOffset =
9393           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9394       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9395         OtherElementsInOrder = false;
9396         break;
9397       }
9398     }
9399     // If other elements are in original order, we record the number of shifts
9400     // we need to get the element we want into element 7. Also record which byte
9401     // in the vector we should insert into.
9402     if (OtherElementsInOrder) {
9403       // If 2nd operand is undefined, we assume no shifts and no swapping.
9404       if (V2.isUndef()) {
9405         ShiftElts = 0;
9406         Swap = false;
9407       } else {
9408         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9409         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9410                          : BigEndianShifts[CurrentElement & 0xF];
9411         Swap = CurrentElement < BytesInVector;
9412       }
9413       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9414       FoundCandidate = true;
9415       break;
9416     }
9417   }
9418 
9419   if (!FoundCandidate)
9420     return SDValue();
9421 
9422   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9423   // optionally with VECSHL if shift is required.
9424   if (Swap)
9425     std::swap(V1, V2);
9426   if (V2.isUndef())
9427     V2 = V1;
9428   if (ShiftElts) {
9429     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9430                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9431     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9432                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9433   }
9434   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9435                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9436 }
9437 
9438 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9439 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9440 /// SDValue.
9441 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9442                                            SelectionDAG &DAG) const {
9443   const unsigned NumHalfWords = 8;
9444   const unsigned BytesInVector = NumHalfWords * 2;
9445   // Check that the shuffle is on half-words.
9446   if (!isNByteElemShuffleMask(N, 2, 1))
9447     return SDValue();
9448 
9449   bool IsLE = Subtarget.isLittleEndian();
9450   SDLoc dl(N);
9451   SDValue V1 = N->getOperand(0);
9452   SDValue V2 = N->getOperand(1);
9453   unsigned ShiftElts = 0, InsertAtByte = 0;
9454   bool Swap = false;
9455 
9456   // Shifts required to get the half-word we want at element 3.
9457   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9458   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9459 
9460   uint32_t Mask = 0;
9461   uint32_t OriginalOrderLow = 0x1234567;
9462   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9463   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9464   // 32-bit space, only need 4-bit nibbles per element.
9465   for (unsigned i = 0; i < NumHalfWords; ++i) {
9466     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9467     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9468   }
9469 
9470   // For each mask element, find out if we're just inserting something
9471   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9472   // from V2 into V1:
9473   //   X, 1, 2, 3, 4, 5, 6, 7
9474   //   0, X, 2, 3, 4, 5, 6, 7
9475   //   0, 1, X, 3, 4, 5, 6, 7
9476   //   0, 1, 2, X, 4, 5, 6, 7
9477   //   0, 1, 2, 3, X, 5, 6, 7
9478   //   0, 1, 2, 3, 4, X, 6, 7
9479   //   0, 1, 2, 3, 4, 5, X, 7
9480   //   0, 1, 2, 3, 4, 5, 6, X
9481   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9482 
9483   bool FoundCandidate = false;
9484   // Go through the mask of half-words to find an element that's being moved
9485   // from one vector to the other.
9486   for (unsigned i = 0; i < NumHalfWords; ++i) {
9487     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9488     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9489     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9490     uint32_t TargetOrder = 0x0;
9491 
9492     // If both vector operands for the shuffle are the same vector, the mask
9493     // will contain only elements from the first one and the second one will be
9494     // undef.
9495     if (V2.isUndef()) {
9496       ShiftElts = 0;
9497       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9498       TargetOrder = OriginalOrderLow;
9499       Swap = false;
9500       // Skip if not the correct element or mask of other elements don't equal
9501       // to our expected order.
9502       if (MaskOneElt == VINSERTHSrcElem &&
9503           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9504         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9505         FoundCandidate = true;
9506         break;
9507       }
9508     } else { // If both operands are defined.
9509       // Target order is [8,15] if the current mask is between [0,7].
9510       TargetOrder =
9511           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9512       // Skip if mask of other elements don't equal our expected order.
9513       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9514         // We only need the last 3 bits for the number of shifts.
9515         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9516                          : BigEndianShifts[MaskOneElt & 0x7];
9517         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9518         Swap = MaskOneElt < NumHalfWords;
9519         FoundCandidate = true;
9520         break;
9521       }
9522     }
9523   }
9524 
9525   if (!FoundCandidate)
9526     return SDValue();
9527 
9528   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9529   // optionally with VECSHL if shift is required.
9530   if (Swap)
9531     std::swap(V1, V2);
9532   if (V2.isUndef())
9533     V2 = V1;
9534   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9535   if (ShiftElts) {
9536     // Double ShiftElts because we're left shifting on v16i8 type.
9537     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9538                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9539     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9540     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9541                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9542     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9543   }
9544   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9545   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9546                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9547   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9548 }
9549 
9550 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9551 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9552 /// return the default SDValue.
9553 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9554                                               SelectionDAG &DAG) const {
9555   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9556   // to v16i8. Peek through the bitcasts to get the actual operands.
9557   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9558   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9559 
9560   auto ShuffleMask = SVN->getMask();
9561   SDValue VecShuffle(SVN, 0);
9562   SDLoc DL(SVN);
9563 
9564   // Check that we have a four byte shuffle.
9565   if (!isNByteElemShuffleMask(SVN, 4, 1))
9566     return SDValue();
9567 
9568   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9569   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9570     std::swap(LHS, RHS);
9571     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9572     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9573   }
9574 
9575   // Ensure that the RHS is a vector of constants.
9576   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9577   if (!BVN)
9578     return SDValue();
9579 
9580   // Check if RHS is a splat of 4-bytes (or smaller).
9581   APInt APSplatValue, APSplatUndef;
9582   unsigned SplatBitSize;
9583   bool HasAnyUndefs;
9584   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9585                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9586       SplatBitSize > 32)
9587     return SDValue();
9588 
9589   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9590   // The instruction splats a constant C into two words of the source vector
9591   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9592   // Thus we check that the shuffle mask is the equivalent  of
9593   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9594   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9595   // within each word are consecutive, so we only need to check the first byte.
9596   SDValue Index;
9597   bool IsLE = Subtarget.isLittleEndian();
9598   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9599       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9600        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9601     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9602   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9603            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9604             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9605     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9606   else
9607     return SDValue();
9608 
9609   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9610   // for XXSPLTI32DX.
9611   unsigned SplatVal = APSplatValue.getZExtValue();
9612   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9613     SplatVal |= (SplatVal << SplatBitSize);
9614 
9615   SDValue SplatNode = DAG.getNode(
9616       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9617       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9618   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9619 }
9620 
9621 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9622 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9623 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9624 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9625 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9626   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9627   assert(Op.getValueType() == MVT::v1i128 &&
9628          "Only set v1i128 as custom, other type shouldn't reach here!");
9629   SDLoc dl(Op);
9630   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9631   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9632   unsigned SHLAmt = N1.getConstantOperandVal(0);
9633   if (SHLAmt % 8 == 0) {
9634     SmallVector<int, 16> Mask(16, 0);
9635     std::iota(Mask.begin(), Mask.end(), 0);
9636     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9637     if (SDValue Shuffle =
9638             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9639                                  DAG.getUNDEF(MVT::v16i8), Mask))
9640       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9641   }
9642   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9643   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9644                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9645   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9646                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9647   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9648   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9649 }
9650 
9651 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9652 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9653 /// return the code it can be lowered into.  Worst case, it can always be
9654 /// lowered into a vperm.
9655 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9656                                                SelectionDAG &DAG) const {
9657   SDLoc dl(Op);
9658   SDValue V1 = Op.getOperand(0);
9659   SDValue V2 = Op.getOperand(1);
9660   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9661 
9662   // Any nodes that were combined in the target-independent combiner prior
9663   // to vector legalization will not be sent to the target combine. Try to
9664   // combine it here.
9665   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9666     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9667       return NewShuffle;
9668     Op = NewShuffle;
9669     SVOp = cast<ShuffleVectorSDNode>(Op);
9670     V1 = Op.getOperand(0);
9671     V2 = Op.getOperand(1);
9672   }
9673   EVT VT = Op.getValueType();
9674   bool isLittleEndian = Subtarget.isLittleEndian();
9675 
9676   unsigned ShiftElts, InsertAtByte;
9677   bool Swap = false;
9678 
9679   // If this is a load-and-splat, we can do that with a single instruction
9680   // in some cases. However if the load has multiple uses, we don't want to
9681   // combine it because that will just produce multiple loads.
9682   bool IsPermutedLoad = false;
9683   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9684   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9685       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9686       InputLoad->hasOneUse()) {
9687     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9688     int SplatIdx =
9689       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9690 
9691     // The splat index for permuted loads will be in the left half of the vector
9692     // which is strictly wider than the loaded value by 8 bytes. So we need to
9693     // adjust the splat index to point to the correct address in memory.
9694     if (IsPermutedLoad) {
9695       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9696       SplatIdx += IsFourByte ? 2 : 1;
9697       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9698              "Splat of a value outside of the loaded memory");
9699     }
9700 
9701     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9702     // For 4-byte load-and-splat, we need Power9.
9703     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9704       uint64_t Offset = 0;
9705       if (IsFourByte)
9706         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9707       else
9708         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9709 
9710       SDValue BasePtr = LD->getBasePtr();
9711       if (Offset != 0)
9712         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9713                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9714       SDValue Ops[] = {
9715         LD->getChain(),    // Chain
9716         BasePtr,           // BasePtr
9717         DAG.getValueType(Op.getValueType()) // VT
9718       };
9719       SDVTList VTL =
9720         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9721       SDValue LdSplt =
9722         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9723                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9724       if (LdSplt.getValueType() != SVOp->getValueType(0))
9725         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9726       return LdSplt;
9727     }
9728   }
9729   if (Subtarget.hasP9Vector() &&
9730       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9731                            isLittleEndian)) {
9732     if (Swap)
9733       std::swap(V1, V2);
9734     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9735     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9736     if (ShiftElts) {
9737       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9738                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9739       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9740                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9741       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9742     }
9743     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9744                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9745     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9746   }
9747 
9748   if (Subtarget.hasPrefixInstrs()) {
9749     SDValue SplatInsertNode;
9750     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9751       return SplatInsertNode;
9752   }
9753 
9754   if (Subtarget.hasP9Altivec()) {
9755     SDValue NewISDNode;
9756     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9757       return NewISDNode;
9758 
9759     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9760       return NewISDNode;
9761   }
9762 
9763   if (Subtarget.hasVSX() &&
9764       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9765     if (Swap)
9766       std::swap(V1, V2);
9767     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9768     SDValue Conv2 =
9769         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9770 
9771     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9772                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9773     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9774   }
9775 
9776   if (Subtarget.hasVSX() &&
9777     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9778     if (Swap)
9779       std::swap(V1, V2);
9780     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9781     SDValue Conv2 =
9782         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9783 
9784     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9785                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9786     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9787   }
9788 
9789   if (Subtarget.hasP9Vector()) {
9790      if (PPC::isXXBRHShuffleMask(SVOp)) {
9791       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9792       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9793       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9794     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9795       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9796       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9797       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9798     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9799       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9800       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9801       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9802     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9803       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9804       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9805       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9806     }
9807   }
9808 
9809   if (Subtarget.hasVSX()) {
9810     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9811       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9812 
9813       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9814       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9815                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9816       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9817     }
9818 
9819     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9820     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9821       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9822       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9823       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9824     }
9825   }
9826 
9827   // Cases that are handled by instructions that take permute immediates
9828   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9829   // selected by the instruction selector.
9830   if (V2.isUndef()) {
9831     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9832         PPC::isSplatShuffleMask(SVOp, 2) ||
9833         PPC::isSplatShuffleMask(SVOp, 4) ||
9834         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9835         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9836         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9837         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9838         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9839         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9840         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9841         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9842         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9843         (Subtarget.hasP8Altivec() && (
9844          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9845          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9846          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9847       return Op;
9848     }
9849   }
9850 
9851   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9852   // and produce a fixed permutation.  If any of these match, do not lower to
9853   // VPERM.
9854   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9855   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9856       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9857       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9858       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9859       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9860       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9861       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9862       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9863       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9864       (Subtarget.hasP8Altivec() && (
9865        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9866        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9867        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9868     return Op;
9869 
9870   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9871   // perfect shuffle table to emit an optimal matching sequence.
9872   ArrayRef<int> PermMask = SVOp->getMask();
9873 
9874   unsigned PFIndexes[4];
9875   bool isFourElementShuffle = true;
9876   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9877     unsigned EltNo = 8;   // Start out undef.
9878     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9879       if (PermMask[i*4+j] < 0)
9880         continue;   // Undef, ignore it.
9881 
9882       unsigned ByteSource = PermMask[i*4+j];
9883       if ((ByteSource & 3) != j) {
9884         isFourElementShuffle = false;
9885         break;
9886       }
9887 
9888       if (EltNo == 8) {
9889         EltNo = ByteSource/4;
9890       } else if (EltNo != ByteSource/4) {
9891         isFourElementShuffle = false;
9892         break;
9893       }
9894     }
9895     PFIndexes[i] = EltNo;
9896   }
9897 
9898   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9899   // perfect shuffle vector to determine if it is cost effective to do this as
9900   // discrete instructions, or whether we should use a vperm.
9901   // For now, we skip this for little endian until such time as we have a
9902   // little-endian perfect shuffle table.
9903   if (isFourElementShuffle && !isLittleEndian) {
9904     // Compute the index in the perfect shuffle table.
9905     unsigned PFTableIndex =
9906       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9907 
9908     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9909     unsigned Cost  = (PFEntry >> 30);
9910 
9911     // Determining when to avoid vperm is tricky.  Many things affect the cost
9912     // of vperm, particularly how many times the perm mask needs to be computed.
9913     // For example, if the perm mask can be hoisted out of a loop or is already
9914     // used (perhaps because there are multiple permutes with the same shuffle
9915     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9916     // the loop requires an extra register.
9917     //
9918     // As a compromise, we only emit discrete instructions if the shuffle can be
9919     // generated in 3 or fewer operations.  When we have loop information
9920     // available, if this block is within a loop, we should avoid using vperm
9921     // for 3-operation perms and use a constant pool load instead.
9922     if (Cost < 3)
9923       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9924   }
9925 
9926   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9927   // vector that will get spilled to the constant pool.
9928   if (V2.isUndef()) V2 = V1;
9929 
9930   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9931   // that it is in input element units, not in bytes.  Convert now.
9932 
9933   // For little endian, the order of the input vectors is reversed, and
9934   // the permutation mask is complemented with respect to 31.  This is
9935   // necessary to produce proper semantics with the big-endian-biased vperm
9936   // instruction.
9937   EVT EltVT = V1.getValueType().getVectorElementType();
9938   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9939 
9940   SmallVector<SDValue, 16> ResultMask;
9941   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9942     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9943 
9944     for (unsigned j = 0; j != BytesPerElement; ++j)
9945       if (isLittleEndian)
9946         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9947                                              dl, MVT::i32));
9948       else
9949         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9950                                              MVT::i32));
9951   }
9952 
9953   ShufflesHandledWithVPERM++;
9954   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9955   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9956   LLVM_DEBUG(SVOp->dump());
9957   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9958   LLVM_DEBUG(VPermMask.dump());
9959 
9960   if (isLittleEndian)
9961     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9962                        V2, V1, VPermMask);
9963   else
9964     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9965                        V1, V2, VPermMask);
9966 }
9967 
9968 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9969 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9970 /// information about the intrinsic.
9971 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9972                                  bool &isDot, const PPCSubtarget &Subtarget) {
9973   unsigned IntrinsicID =
9974       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9975   CompareOpc = -1;
9976   isDot = false;
9977   switch (IntrinsicID) {
9978   default:
9979     return false;
9980   // Comparison predicates.
9981   case Intrinsic::ppc_altivec_vcmpbfp_p:
9982     CompareOpc = 966;
9983     isDot = true;
9984     break;
9985   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9986     CompareOpc = 198;
9987     isDot = true;
9988     break;
9989   case Intrinsic::ppc_altivec_vcmpequb_p:
9990     CompareOpc = 6;
9991     isDot = true;
9992     break;
9993   case Intrinsic::ppc_altivec_vcmpequh_p:
9994     CompareOpc = 70;
9995     isDot = true;
9996     break;
9997   case Intrinsic::ppc_altivec_vcmpequw_p:
9998     CompareOpc = 134;
9999     isDot = true;
10000     break;
10001   case Intrinsic::ppc_altivec_vcmpequd_p:
10002     if (Subtarget.hasP8Altivec()) {
10003       CompareOpc = 199;
10004       isDot = true;
10005     } else
10006       return false;
10007     break;
10008   case Intrinsic::ppc_altivec_vcmpneb_p:
10009   case Intrinsic::ppc_altivec_vcmpneh_p:
10010   case Intrinsic::ppc_altivec_vcmpnew_p:
10011   case Intrinsic::ppc_altivec_vcmpnezb_p:
10012   case Intrinsic::ppc_altivec_vcmpnezh_p:
10013   case Intrinsic::ppc_altivec_vcmpnezw_p:
10014     if (Subtarget.hasP9Altivec()) {
10015       switch (IntrinsicID) {
10016       default:
10017         llvm_unreachable("Unknown comparison intrinsic.");
10018       case Intrinsic::ppc_altivec_vcmpneb_p:
10019         CompareOpc = 7;
10020         break;
10021       case Intrinsic::ppc_altivec_vcmpneh_p:
10022         CompareOpc = 71;
10023         break;
10024       case Intrinsic::ppc_altivec_vcmpnew_p:
10025         CompareOpc = 135;
10026         break;
10027       case Intrinsic::ppc_altivec_vcmpnezb_p:
10028         CompareOpc = 263;
10029         break;
10030       case Intrinsic::ppc_altivec_vcmpnezh_p:
10031         CompareOpc = 327;
10032         break;
10033       case Intrinsic::ppc_altivec_vcmpnezw_p:
10034         CompareOpc = 391;
10035         break;
10036       }
10037       isDot = true;
10038     } else
10039       return false;
10040     break;
10041   case Intrinsic::ppc_altivec_vcmpgefp_p:
10042     CompareOpc = 454;
10043     isDot = true;
10044     break;
10045   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10046     CompareOpc = 710;
10047     isDot = true;
10048     break;
10049   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10050     CompareOpc = 774;
10051     isDot = true;
10052     break;
10053   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10054     CompareOpc = 838;
10055     isDot = true;
10056     break;
10057   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10058     CompareOpc = 902;
10059     isDot = true;
10060     break;
10061   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10062     if (Subtarget.hasP8Altivec()) {
10063       CompareOpc = 967;
10064       isDot = true;
10065     } else
10066       return false;
10067     break;
10068   case Intrinsic::ppc_altivec_vcmpgtub_p:
10069     CompareOpc = 518;
10070     isDot = true;
10071     break;
10072   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10073     CompareOpc = 582;
10074     isDot = true;
10075     break;
10076   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10077     CompareOpc = 646;
10078     isDot = true;
10079     break;
10080   case Intrinsic::ppc_altivec_vcmpgtud_p:
10081     if (Subtarget.hasP8Altivec()) {
10082       CompareOpc = 711;
10083       isDot = true;
10084     } else
10085       return false;
10086     break;
10087 
10088   // VSX predicate comparisons use the same infrastructure
10089   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10090   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10091   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10092   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10093   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10094   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10095     if (Subtarget.hasVSX()) {
10096       switch (IntrinsicID) {
10097       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10098         CompareOpc = 99;
10099         break;
10100       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10101         CompareOpc = 115;
10102         break;
10103       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10104         CompareOpc = 107;
10105         break;
10106       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10107         CompareOpc = 67;
10108         break;
10109       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10110         CompareOpc = 83;
10111         break;
10112       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10113         CompareOpc = 75;
10114         break;
10115       }
10116       isDot = true;
10117     } else
10118       return false;
10119     break;
10120 
10121   // Normal Comparisons.
10122   case Intrinsic::ppc_altivec_vcmpbfp:
10123     CompareOpc = 966;
10124     break;
10125   case Intrinsic::ppc_altivec_vcmpeqfp:
10126     CompareOpc = 198;
10127     break;
10128   case Intrinsic::ppc_altivec_vcmpequb:
10129     CompareOpc = 6;
10130     break;
10131   case Intrinsic::ppc_altivec_vcmpequh:
10132     CompareOpc = 70;
10133     break;
10134   case Intrinsic::ppc_altivec_vcmpequw:
10135     CompareOpc = 134;
10136     break;
10137   case Intrinsic::ppc_altivec_vcmpequd:
10138     if (Subtarget.hasP8Altivec())
10139       CompareOpc = 199;
10140     else
10141       return false;
10142     break;
10143   case Intrinsic::ppc_altivec_vcmpneb:
10144   case Intrinsic::ppc_altivec_vcmpneh:
10145   case Intrinsic::ppc_altivec_vcmpnew:
10146   case Intrinsic::ppc_altivec_vcmpnezb:
10147   case Intrinsic::ppc_altivec_vcmpnezh:
10148   case Intrinsic::ppc_altivec_vcmpnezw:
10149     if (Subtarget.hasP9Altivec())
10150       switch (IntrinsicID) {
10151       default:
10152         llvm_unreachable("Unknown comparison intrinsic.");
10153       case Intrinsic::ppc_altivec_vcmpneb:
10154         CompareOpc = 7;
10155         break;
10156       case Intrinsic::ppc_altivec_vcmpneh:
10157         CompareOpc = 71;
10158         break;
10159       case Intrinsic::ppc_altivec_vcmpnew:
10160         CompareOpc = 135;
10161         break;
10162       case Intrinsic::ppc_altivec_vcmpnezb:
10163         CompareOpc = 263;
10164         break;
10165       case Intrinsic::ppc_altivec_vcmpnezh:
10166         CompareOpc = 327;
10167         break;
10168       case Intrinsic::ppc_altivec_vcmpnezw:
10169         CompareOpc = 391;
10170         break;
10171       }
10172     else
10173       return false;
10174     break;
10175   case Intrinsic::ppc_altivec_vcmpgefp:
10176     CompareOpc = 454;
10177     break;
10178   case Intrinsic::ppc_altivec_vcmpgtfp:
10179     CompareOpc = 710;
10180     break;
10181   case Intrinsic::ppc_altivec_vcmpgtsb:
10182     CompareOpc = 774;
10183     break;
10184   case Intrinsic::ppc_altivec_vcmpgtsh:
10185     CompareOpc = 838;
10186     break;
10187   case Intrinsic::ppc_altivec_vcmpgtsw:
10188     CompareOpc = 902;
10189     break;
10190   case Intrinsic::ppc_altivec_vcmpgtsd:
10191     if (Subtarget.hasP8Altivec())
10192       CompareOpc = 967;
10193     else
10194       return false;
10195     break;
10196   case Intrinsic::ppc_altivec_vcmpgtub:
10197     CompareOpc = 518;
10198     break;
10199   case Intrinsic::ppc_altivec_vcmpgtuh:
10200     CompareOpc = 582;
10201     break;
10202   case Intrinsic::ppc_altivec_vcmpgtuw:
10203     CompareOpc = 646;
10204     break;
10205   case Intrinsic::ppc_altivec_vcmpgtud:
10206     if (Subtarget.hasP8Altivec())
10207       CompareOpc = 711;
10208     else
10209       return false;
10210     break;
10211   }
10212   return true;
10213 }
10214 
10215 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10216 /// lower, do it, otherwise return null.
10217 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10218                                                    SelectionDAG &DAG) const {
10219   unsigned IntrinsicID =
10220     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10221 
10222   SDLoc dl(Op);
10223 
10224   if (IntrinsicID == Intrinsic::thread_pointer) {
10225     // Reads the thread pointer register, used for __builtin_thread_pointer.
10226     if (Subtarget.isPPC64())
10227       return DAG.getRegister(PPC::X13, MVT::i64);
10228     return DAG.getRegister(PPC::R2, MVT::i32);
10229   }
10230 
10231   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10232   // opcode number of the comparison.
10233   int CompareOpc;
10234   bool isDot;
10235   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10236     return SDValue();    // Don't custom lower most intrinsics.
10237 
10238   // If this is a non-dot comparison, make the VCMP node and we are done.
10239   if (!isDot) {
10240     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10241                               Op.getOperand(1), Op.getOperand(2),
10242                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10243     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10244   }
10245 
10246   // Create the PPCISD altivec 'dot' comparison node.
10247   SDValue Ops[] = {
10248     Op.getOperand(2),  // LHS
10249     Op.getOperand(3),  // RHS
10250     DAG.getConstant(CompareOpc, dl, MVT::i32)
10251   };
10252   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10253   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10254 
10255   // Now that we have the comparison, emit a copy from the CR to a GPR.
10256   // This is flagged to the above dot comparison.
10257   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10258                                 DAG.getRegister(PPC::CR6, MVT::i32),
10259                                 CompNode.getValue(1));
10260 
10261   // Unpack the result based on how the target uses it.
10262   unsigned BitNo;   // Bit # of CR6.
10263   bool InvertBit;   // Invert result?
10264   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10265   default:  // Can't happen, don't crash on invalid number though.
10266   case 0:   // Return the value of the EQ bit of CR6.
10267     BitNo = 0; InvertBit = false;
10268     break;
10269   case 1:   // Return the inverted value of the EQ bit of CR6.
10270     BitNo = 0; InvertBit = true;
10271     break;
10272   case 2:   // Return the value of the LT bit of CR6.
10273     BitNo = 2; InvertBit = false;
10274     break;
10275   case 3:   // Return the inverted value of the LT bit of CR6.
10276     BitNo = 2; InvertBit = true;
10277     break;
10278   }
10279 
10280   // Shift the bit into the low position.
10281   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10282                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10283   // Isolate the bit.
10284   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10285                       DAG.getConstant(1, dl, MVT::i32));
10286 
10287   // If we are supposed to, toggle the bit.
10288   if (InvertBit)
10289     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10290                         DAG.getConstant(1, dl, MVT::i32));
10291   return Flags;
10292 }
10293 
10294 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10295                                                SelectionDAG &DAG) const {
10296   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10297   // the beginning of the argument list.
10298   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10299   SDLoc DL(Op);
10300   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10301   case Intrinsic::ppc_cfence: {
10302     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10303     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10304     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10305                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10306                                                   Op.getOperand(ArgStart + 1)),
10307                                       Op.getOperand(0)),
10308                    0);
10309   }
10310   default:
10311     break;
10312   }
10313   return SDValue();
10314 }
10315 
10316 // Lower scalar BSWAP64 to xxbrd.
10317 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10318   SDLoc dl(Op);
10319   // MTVSRDD
10320   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10321                    Op.getOperand(0));
10322   // XXBRD
10323   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10324   // MFVSRD
10325   int VectorIndex = 0;
10326   if (Subtarget.isLittleEndian())
10327     VectorIndex = 1;
10328   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10329                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10330   return Op;
10331 }
10332 
10333 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10334 // compared to a value that is atomically loaded (atomic loads zero-extend).
10335 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10336                                                 SelectionDAG &DAG) const {
10337   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10338          "Expecting an atomic compare-and-swap here.");
10339   SDLoc dl(Op);
10340   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10341   EVT MemVT = AtomicNode->getMemoryVT();
10342   if (MemVT.getSizeInBits() >= 32)
10343     return Op;
10344 
10345   SDValue CmpOp = Op.getOperand(2);
10346   // If this is already correctly zero-extended, leave it alone.
10347   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10348   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10349     return Op;
10350 
10351   // Clear the high bits of the compare operand.
10352   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10353   SDValue NewCmpOp =
10354     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10355                 DAG.getConstant(MaskVal, dl, MVT::i32));
10356 
10357   // Replace the existing compare operand with the properly zero-extended one.
10358   SmallVector<SDValue, 4> Ops;
10359   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10360     Ops.push_back(AtomicNode->getOperand(i));
10361   Ops[2] = NewCmpOp;
10362   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10363   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10364   auto NodeTy =
10365     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10366   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10367 }
10368 
10369 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10370                                                  SelectionDAG &DAG) const {
10371   SDLoc dl(Op);
10372   // Create a stack slot that is 16-byte aligned.
10373   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10374   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10375   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10376   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10377 
10378   // Store the input value into Value#0 of the stack slot.
10379   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10380                                MachinePointerInfo());
10381   // Load it out.
10382   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10383 }
10384 
10385 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10386                                                   SelectionDAG &DAG) const {
10387   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10388          "Should only be called for ISD::INSERT_VECTOR_ELT");
10389 
10390   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10391   // We have legal lowering for constant indices but not for variable ones.
10392   if (!C)
10393     return SDValue();
10394 
10395   EVT VT = Op.getValueType();
10396   SDLoc dl(Op);
10397   SDValue V1 = Op.getOperand(0);
10398   SDValue V2 = Op.getOperand(1);
10399   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10400   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10401     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10402     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10403     unsigned InsertAtElement = C->getZExtValue();
10404     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10405     if (Subtarget.isLittleEndian()) {
10406       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10407     }
10408     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10409                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10410   }
10411   return Op;
10412 }
10413 
10414 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10415   SDLoc dl(Op);
10416   if (Op.getValueType() == MVT::v4i32) {
10417     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10418 
10419     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10420     // +16 as shift amt.
10421     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10422     SDValue RHSSwap =   // = vrlw RHS, 16
10423       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10424 
10425     // Shrinkify inputs to v8i16.
10426     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10427     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10428     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10429 
10430     // Low parts multiplied together, generating 32-bit results (we ignore the
10431     // top parts).
10432     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10433                                         LHS, RHS, DAG, dl, MVT::v4i32);
10434 
10435     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10436                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10437     // Shift the high parts up 16 bits.
10438     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10439                               Neg16, DAG, dl);
10440     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10441   } else if (Op.getValueType() == MVT::v16i8) {
10442     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10443     bool isLittleEndian = Subtarget.isLittleEndian();
10444 
10445     // Multiply the even 8-bit parts, producing 16-bit sums.
10446     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10447                                            LHS, RHS, DAG, dl, MVT::v8i16);
10448     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10449 
10450     // Multiply the odd 8-bit parts, producing 16-bit sums.
10451     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10452                                           LHS, RHS, DAG, dl, MVT::v8i16);
10453     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10454 
10455     // Merge the results together.  Because vmuleub and vmuloub are
10456     // instructions with a big-endian bias, we must reverse the
10457     // element numbering and reverse the meaning of "odd" and "even"
10458     // when generating little endian code.
10459     int Ops[16];
10460     for (unsigned i = 0; i != 8; ++i) {
10461       if (isLittleEndian) {
10462         Ops[i*2  ] = 2*i;
10463         Ops[i*2+1] = 2*i+16;
10464       } else {
10465         Ops[i*2  ] = 2*i+1;
10466         Ops[i*2+1] = 2*i+1+16;
10467       }
10468     }
10469     if (isLittleEndian)
10470       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10471     else
10472       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10473   } else {
10474     llvm_unreachable("Unknown mul to lower!");
10475   }
10476 }
10477 
10478 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10479 
10480   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10481 
10482   EVT VT = Op.getValueType();
10483   assert(VT.isVector() &&
10484          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10485   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10486           VT == MVT::v16i8) &&
10487          "Unexpected vector element type!");
10488   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10489          "Current subtarget doesn't support smax v2i64!");
10490 
10491   // For vector abs, it can be lowered to:
10492   // abs x
10493   // ==>
10494   // y = -x
10495   // smax(x, y)
10496 
10497   SDLoc dl(Op);
10498   SDValue X = Op.getOperand(0);
10499   SDValue Zero = DAG.getConstant(0, dl, VT);
10500   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10501 
10502   // SMAX patch https://reviews.llvm.org/D47332
10503   // hasn't landed yet, so use intrinsic first here.
10504   // TODO: Should use SMAX directly once SMAX patch landed
10505   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10506   if (VT == MVT::v2i64)
10507     BifID = Intrinsic::ppc_altivec_vmaxsd;
10508   else if (VT == MVT::v8i16)
10509     BifID = Intrinsic::ppc_altivec_vmaxsh;
10510   else if (VT == MVT::v16i8)
10511     BifID = Intrinsic::ppc_altivec_vmaxsb;
10512 
10513   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10514 }
10515 
10516 // Custom lowering for fpext vf32 to v2f64
10517 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10518 
10519   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10520          "Should only be called for ISD::FP_EXTEND");
10521 
10522   // FIXME: handle extends from half precision float vectors on P9.
10523   // We only want to custom lower an extend from v2f32 to v2f64.
10524   if (Op.getValueType() != MVT::v2f64 ||
10525       Op.getOperand(0).getValueType() != MVT::v2f32)
10526     return SDValue();
10527 
10528   SDLoc dl(Op);
10529   SDValue Op0 = Op.getOperand(0);
10530 
10531   switch (Op0.getOpcode()) {
10532   default:
10533     return SDValue();
10534   case ISD::EXTRACT_SUBVECTOR: {
10535     assert(Op0.getNumOperands() == 2 &&
10536            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10537            "Node should have 2 operands with second one being a constant!");
10538 
10539     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10540       return SDValue();
10541 
10542     // Custom lower is only done for high or low doubleword.
10543     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10544     if (Idx % 2 != 0)
10545       return SDValue();
10546 
10547     // Since input is v4f32, at this point Idx is either 0 or 2.
10548     // Shift to get the doubleword position we want.
10549     int DWord = Idx >> 1;
10550 
10551     // High and low word positions are different on little endian.
10552     if (Subtarget.isLittleEndian())
10553       DWord ^= 0x1;
10554 
10555     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10556                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10557   }
10558   case ISD::FADD:
10559   case ISD::FMUL:
10560   case ISD::FSUB: {
10561     SDValue NewLoad[2];
10562     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10563       // Ensure both input are loads.
10564       SDValue LdOp = Op0.getOperand(i);
10565       if (LdOp.getOpcode() != ISD::LOAD)
10566         return SDValue();
10567       // Generate new load node.
10568       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10569       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10570       NewLoad[i] = DAG.getMemIntrinsicNode(
10571           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10572           LD->getMemoryVT(), LD->getMemOperand());
10573     }
10574     SDValue NewOp =
10575         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10576                     NewLoad[1], Op0.getNode()->getFlags());
10577     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10578                        DAG.getConstant(0, dl, MVT::i32));
10579   }
10580   case ISD::LOAD: {
10581     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10582     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10583     SDValue NewLd = DAG.getMemIntrinsicNode(
10584         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10585         LD->getMemoryVT(), LD->getMemOperand());
10586     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10587                        DAG.getConstant(0, dl, MVT::i32));
10588   }
10589   }
10590   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10591 }
10592 
10593 /// LowerOperation - Provide custom lowering hooks for some operations.
10594 ///
10595 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10596   switch (Op.getOpcode()) {
10597   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10598   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10599   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10600   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10601   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10602   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10603   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10604   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10605   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10606 
10607   // Variable argument lowering.
10608   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10609   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10610   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10611 
10612   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10613   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10614   case ISD::GET_DYNAMIC_AREA_OFFSET:
10615     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10616 
10617   // Exception handling lowering.
10618   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10619   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10620   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10621 
10622   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10623   case ISD::STORE:              return LowerSTORE(Op, DAG);
10624   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10625   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10626   case ISD::STRICT_FP_TO_UINT:
10627   case ISD::STRICT_FP_TO_SINT:
10628   case ISD::FP_TO_UINT:
10629   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10630   case ISD::STRICT_UINT_TO_FP:
10631   case ISD::STRICT_SINT_TO_FP:
10632   case ISD::UINT_TO_FP:
10633   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10634   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10635 
10636   // Lower 64-bit shifts.
10637   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10638   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10639   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10640 
10641   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10642   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10643 
10644   // Vector-related lowering.
10645   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10646   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10647   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10648   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10649   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10650   case ISD::MUL:                return LowerMUL(Op, DAG);
10651   case ISD::ABS:                return LowerABS(Op, DAG);
10652   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10653   case ISD::ROTL:               return LowerROTL(Op, DAG);
10654 
10655   // For counter-based loop handling.
10656   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10657 
10658   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10659 
10660   // Frame & Return address.
10661   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10662   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10663 
10664   case ISD::INTRINSIC_VOID:
10665     return LowerINTRINSIC_VOID(Op, DAG);
10666   case ISD::BSWAP:
10667     return LowerBSWAP(Op, DAG);
10668   case ISD::ATOMIC_CMP_SWAP:
10669     return LowerATOMIC_CMP_SWAP(Op, DAG);
10670   }
10671 }
10672 
10673 void PPCTargetLowering::LowerOperationWrapper(SDNode *N,
10674                                               SmallVectorImpl<SDValue> &Results,
10675                                               SelectionDAG &DAG) const {
10676   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10677 
10678   if (!Res.getNode())
10679     return;
10680 
10681   // Take the return value as-is if original node has only one result.
10682   if (N->getNumValues() == 1) {
10683     Results.push_back(Res);
10684     return;
10685   }
10686 
10687   // New node should have the same number of results.
10688   assert((N->getNumValues() == Res->getNumValues()) &&
10689       "Lowering returned the wrong number of results!");
10690 
10691   for (unsigned i = 0; i < N->getNumValues(); ++i)
10692     Results.push_back(Res.getValue(i));
10693 }
10694 
10695 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10696                                            SmallVectorImpl<SDValue>&Results,
10697                                            SelectionDAG &DAG) const {
10698   SDLoc dl(N);
10699   switch (N->getOpcode()) {
10700   default:
10701     llvm_unreachable("Do not know how to custom type legalize this operation!");
10702   case ISD::READCYCLECOUNTER: {
10703     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10704     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10705 
10706     Results.push_back(
10707         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10708     Results.push_back(RTB.getValue(2));
10709     break;
10710   }
10711   case ISD::INTRINSIC_W_CHAIN: {
10712     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10713         Intrinsic::loop_decrement)
10714       break;
10715 
10716     assert(N->getValueType(0) == MVT::i1 &&
10717            "Unexpected result type for CTR decrement intrinsic");
10718     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10719                                  N->getValueType(0));
10720     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10721     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10722                                  N->getOperand(1));
10723 
10724     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10725     Results.push_back(NewInt.getValue(1));
10726     break;
10727   }
10728   case ISD::VAARG: {
10729     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10730       return;
10731 
10732     EVT VT = N->getValueType(0);
10733 
10734     if (VT == MVT::i64) {
10735       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10736 
10737       Results.push_back(NewNode);
10738       Results.push_back(NewNode.getValue(1));
10739     }
10740     return;
10741   }
10742   case ISD::STRICT_FP_TO_SINT:
10743   case ISD::STRICT_FP_TO_UINT:
10744   case ISD::FP_TO_SINT:
10745   case ISD::FP_TO_UINT:
10746     // LowerFP_TO_INT() can only handle f32 and f64.
10747     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10748         MVT::ppcf128)
10749       return;
10750     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10751     return;
10752   case ISD::TRUNCATE: {
10753     EVT TrgVT = N->getValueType(0);
10754     EVT OpVT = N->getOperand(0).getValueType();
10755     if (TrgVT.isVector() &&
10756         isOperationCustom(N->getOpcode(), TrgVT) &&
10757         OpVT.getSizeInBits() <= 128 &&
10758         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10759       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10760     return;
10761   }
10762   case ISD::BITCAST:
10763     // Don't handle bitcast here.
10764     return;
10765   case ISD::FP_EXTEND:
10766     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10767     if (Lowered)
10768       Results.push_back(Lowered);
10769     return;
10770   }
10771 }
10772 
10773 //===----------------------------------------------------------------------===//
10774 //  Other Lowering Code
10775 //===----------------------------------------------------------------------===//
10776 
10777 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10778   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10779   Function *Func = Intrinsic::getDeclaration(M, Id);
10780   return Builder.CreateCall(Func, {});
10781 }
10782 
10783 // The mappings for emitLeading/TrailingFence is taken from
10784 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10785 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10786                                                  Instruction *Inst,
10787                                                  AtomicOrdering Ord) const {
10788   if (Ord == AtomicOrdering::SequentiallyConsistent)
10789     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10790   if (isReleaseOrStronger(Ord))
10791     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10792   return nullptr;
10793 }
10794 
10795 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10796                                                   Instruction *Inst,
10797                                                   AtomicOrdering Ord) const {
10798   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10799     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10800     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10801     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10802     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10803       return Builder.CreateCall(
10804           Intrinsic::getDeclaration(
10805               Builder.GetInsertBlock()->getParent()->getParent(),
10806               Intrinsic::ppc_cfence, {Inst->getType()}),
10807           {Inst});
10808     // FIXME: Can use isync for rmw operation.
10809     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10810   }
10811   return nullptr;
10812 }
10813 
10814 MachineBasicBlock *
10815 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10816                                     unsigned AtomicSize,
10817                                     unsigned BinOpcode,
10818                                     unsigned CmpOpcode,
10819                                     unsigned CmpPred) const {
10820   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10821   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10822 
10823   auto LoadMnemonic = PPC::LDARX;
10824   auto StoreMnemonic = PPC::STDCX;
10825   switch (AtomicSize) {
10826   default:
10827     llvm_unreachable("Unexpected size of atomic entity");
10828   case 1:
10829     LoadMnemonic = PPC::LBARX;
10830     StoreMnemonic = PPC::STBCX;
10831     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10832     break;
10833   case 2:
10834     LoadMnemonic = PPC::LHARX;
10835     StoreMnemonic = PPC::STHCX;
10836     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10837     break;
10838   case 4:
10839     LoadMnemonic = PPC::LWARX;
10840     StoreMnemonic = PPC::STWCX;
10841     break;
10842   case 8:
10843     LoadMnemonic = PPC::LDARX;
10844     StoreMnemonic = PPC::STDCX;
10845     break;
10846   }
10847 
10848   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10849   MachineFunction *F = BB->getParent();
10850   MachineFunction::iterator It = ++BB->getIterator();
10851 
10852   Register dest = MI.getOperand(0).getReg();
10853   Register ptrA = MI.getOperand(1).getReg();
10854   Register ptrB = MI.getOperand(2).getReg();
10855   Register incr = MI.getOperand(3).getReg();
10856   DebugLoc dl = MI.getDebugLoc();
10857 
10858   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10859   MachineBasicBlock *loop2MBB =
10860     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10861   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10862   F->insert(It, loopMBB);
10863   if (CmpOpcode)
10864     F->insert(It, loop2MBB);
10865   F->insert(It, exitMBB);
10866   exitMBB->splice(exitMBB->begin(), BB,
10867                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10868   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10869 
10870   MachineRegisterInfo &RegInfo = F->getRegInfo();
10871   Register TmpReg = (!BinOpcode) ? incr :
10872     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10873                                            : &PPC::GPRCRegClass);
10874 
10875   //  thisMBB:
10876   //   ...
10877   //   fallthrough --> loopMBB
10878   BB->addSuccessor(loopMBB);
10879 
10880   //  loopMBB:
10881   //   l[wd]arx dest, ptr
10882   //   add r0, dest, incr
10883   //   st[wd]cx. r0, ptr
10884   //   bne- loopMBB
10885   //   fallthrough --> exitMBB
10886 
10887   // For max/min...
10888   //  loopMBB:
10889   //   l[wd]arx dest, ptr
10890   //   cmpl?[wd] incr, dest
10891   //   bgt exitMBB
10892   //  loop2MBB:
10893   //   st[wd]cx. dest, ptr
10894   //   bne- loopMBB
10895   //   fallthrough --> exitMBB
10896 
10897   BB = loopMBB;
10898   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10899     .addReg(ptrA).addReg(ptrB);
10900   if (BinOpcode)
10901     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10902   if (CmpOpcode) {
10903     // Signed comparisons of byte or halfword values must be sign-extended.
10904     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10905       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10906       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10907               ExtReg).addReg(dest);
10908       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10909         .addReg(incr).addReg(ExtReg);
10910     } else
10911       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10912         .addReg(incr).addReg(dest);
10913 
10914     BuildMI(BB, dl, TII->get(PPC::BCC))
10915       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10916     BB->addSuccessor(loop2MBB);
10917     BB->addSuccessor(exitMBB);
10918     BB = loop2MBB;
10919   }
10920   BuildMI(BB, dl, TII->get(StoreMnemonic))
10921     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10922   BuildMI(BB, dl, TII->get(PPC::BCC))
10923     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10924   BB->addSuccessor(loopMBB);
10925   BB->addSuccessor(exitMBB);
10926 
10927   //  exitMBB:
10928   //   ...
10929   BB = exitMBB;
10930   return BB;
10931 }
10932 
10933 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10934     MachineInstr &MI, MachineBasicBlock *BB,
10935     bool is8bit, // operation
10936     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10937   // If we support part-word atomic mnemonics, just use them
10938   if (Subtarget.hasPartwordAtomics())
10939     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10940                             CmpPred);
10941 
10942   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10943   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10944   // In 64 bit mode we have to use 64 bits for addresses, even though the
10945   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10946   // registers without caring whether they're 32 or 64, but here we're
10947   // doing actual arithmetic on the addresses.
10948   bool is64bit = Subtarget.isPPC64();
10949   bool isLittleEndian = Subtarget.isLittleEndian();
10950   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10951 
10952   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10953   MachineFunction *F = BB->getParent();
10954   MachineFunction::iterator It = ++BB->getIterator();
10955 
10956   Register dest = MI.getOperand(0).getReg();
10957   Register ptrA = MI.getOperand(1).getReg();
10958   Register ptrB = MI.getOperand(2).getReg();
10959   Register incr = MI.getOperand(3).getReg();
10960   DebugLoc dl = MI.getDebugLoc();
10961 
10962   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10963   MachineBasicBlock *loop2MBB =
10964       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10965   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10966   F->insert(It, loopMBB);
10967   if (CmpOpcode)
10968     F->insert(It, loop2MBB);
10969   F->insert(It, exitMBB);
10970   exitMBB->splice(exitMBB->begin(), BB,
10971                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10972   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10973 
10974   MachineRegisterInfo &RegInfo = F->getRegInfo();
10975   const TargetRegisterClass *RC =
10976       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10977   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10978 
10979   Register PtrReg = RegInfo.createVirtualRegister(RC);
10980   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10981   Register ShiftReg =
10982       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10983   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10984   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10985   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10986   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10987   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10988   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10989   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10990   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10991   Register Ptr1Reg;
10992   Register TmpReg =
10993       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10994 
10995   //  thisMBB:
10996   //   ...
10997   //   fallthrough --> loopMBB
10998   BB->addSuccessor(loopMBB);
10999 
11000   // The 4-byte load must be aligned, while a char or short may be
11001   // anywhere in the word.  Hence all this nasty bookkeeping code.
11002   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11003   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11004   //   xori shift, shift1, 24 [16]
11005   //   rlwinm ptr, ptr1, 0, 0, 29
11006   //   slw incr2, incr, shift
11007   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11008   //   slw mask, mask2, shift
11009   //  loopMBB:
11010   //   lwarx tmpDest, ptr
11011   //   add tmp, tmpDest, incr2
11012   //   andc tmp2, tmpDest, mask
11013   //   and tmp3, tmp, mask
11014   //   or tmp4, tmp3, tmp2
11015   //   stwcx. tmp4, ptr
11016   //   bne- loopMBB
11017   //   fallthrough --> exitMBB
11018   //   srw dest, tmpDest, shift
11019   if (ptrA != ZeroReg) {
11020     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11021     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11022         .addReg(ptrA)
11023         .addReg(ptrB);
11024   } else {
11025     Ptr1Reg = ptrB;
11026   }
11027   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11028   // mode.
11029   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11030       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11031       .addImm(3)
11032       .addImm(27)
11033       .addImm(is8bit ? 28 : 27);
11034   if (!isLittleEndian)
11035     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11036         .addReg(Shift1Reg)
11037         .addImm(is8bit ? 24 : 16);
11038   if (is64bit)
11039     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11040         .addReg(Ptr1Reg)
11041         .addImm(0)
11042         .addImm(61);
11043   else
11044     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11045         .addReg(Ptr1Reg)
11046         .addImm(0)
11047         .addImm(0)
11048         .addImm(29);
11049   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11050   if (is8bit)
11051     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11052   else {
11053     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11054     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11055         .addReg(Mask3Reg)
11056         .addImm(65535);
11057   }
11058   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11059       .addReg(Mask2Reg)
11060       .addReg(ShiftReg);
11061 
11062   BB = loopMBB;
11063   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11064       .addReg(ZeroReg)
11065       .addReg(PtrReg);
11066   if (BinOpcode)
11067     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11068         .addReg(Incr2Reg)
11069         .addReg(TmpDestReg);
11070   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11071       .addReg(TmpDestReg)
11072       .addReg(MaskReg);
11073   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11074   if (CmpOpcode) {
11075     // For unsigned comparisons, we can directly compare the shifted values.
11076     // For signed comparisons we shift and sign extend.
11077     Register SReg = RegInfo.createVirtualRegister(GPRC);
11078     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11079         .addReg(TmpDestReg)
11080         .addReg(MaskReg);
11081     unsigned ValueReg = SReg;
11082     unsigned CmpReg = Incr2Reg;
11083     if (CmpOpcode == PPC::CMPW) {
11084       ValueReg = RegInfo.createVirtualRegister(GPRC);
11085       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11086           .addReg(SReg)
11087           .addReg(ShiftReg);
11088       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11089       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11090           .addReg(ValueReg);
11091       ValueReg = ValueSReg;
11092       CmpReg = incr;
11093     }
11094     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11095         .addReg(CmpReg)
11096         .addReg(ValueReg);
11097     BuildMI(BB, dl, TII->get(PPC::BCC))
11098         .addImm(CmpPred)
11099         .addReg(PPC::CR0)
11100         .addMBB(exitMBB);
11101     BB->addSuccessor(loop2MBB);
11102     BB->addSuccessor(exitMBB);
11103     BB = loop2MBB;
11104   }
11105   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11106   BuildMI(BB, dl, TII->get(PPC::STWCX))
11107       .addReg(Tmp4Reg)
11108       .addReg(ZeroReg)
11109       .addReg(PtrReg);
11110   BuildMI(BB, dl, TII->get(PPC::BCC))
11111       .addImm(PPC::PRED_NE)
11112       .addReg(PPC::CR0)
11113       .addMBB(loopMBB);
11114   BB->addSuccessor(loopMBB);
11115   BB->addSuccessor(exitMBB);
11116 
11117   //  exitMBB:
11118   //   ...
11119   BB = exitMBB;
11120   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11121       .addReg(TmpDestReg)
11122       .addReg(ShiftReg);
11123   return BB;
11124 }
11125 
11126 llvm::MachineBasicBlock *
11127 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11128                                     MachineBasicBlock *MBB) const {
11129   DebugLoc DL = MI.getDebugLoc();
11130   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11131   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11132 
11133   MachineFunction *MF = MBB->getParent();
11134   MachineRegisterInfo &MRI = MF->getRegInfo();
11135 
11136   const BasicBlock *BB = MBB->getBasicBlock();
11137   MachineFunction::iterator I = ++MBB->getIterator();
11138 
11139   Register DstReg = MI.getOperand(0).getReg();
11140   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11141   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11142   Register mainDstReg = MRI.createVirtualRegister(RC);
11143   Register restoreDstReg = MRI.createVirtualRegister(RC);
11144 
11145   MVT PVT = getPointerTy(MF->getDataLayout());
11146   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11147          "Invalid Pointer Size!");
11148   // For v = setjmp(buf), we generate
11149   //
11150   // thisMBB:
11151   //  SjLjSetup mainMBB
11152   //  bl mainMBB
11153   //  v_restore = 1
11154   //  b sinkMBB
11155   //
11156   // mainMBB:
11157   //  buf[LabelOffset] = LR
11158   //  v_main = 0
11159   //
11160   // sinkMBB:
11161   //  v = phi(main, restore)
11162   //
11163 
11164   MachineBasicBlock *thisMBB = MBB;
11165   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11166   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11167   MF->insert(I, mainMBB);
11168   MF->insert(I, sinkMBB);
11169 
11170   MachineInstrBuilder MIB;
11171 
11172   // Transfer the remainder of BB and its successor edges to sinkMBB.
11173   sinkMBB->splice(sinkMBB->begin(), MBB,
11174                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11175   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11176 
11177   // Note that the structure of the jmp_buf used here is not compatible
11178   // with that used by libc, and is not designed to be. Specifically, it
11179   // stores only those 'reserved' registers that LLVM does not otherwise
11180   // understand how to spill. Also, by convention, by the time this
11181   // intrinsic is called, Clang has already stored the frame address in the
11182   // first slot of the buffer and stack address in the third. Following the
11183   // X86 target code, we'll store the jump address in the second slot. We also
11184   // need to save the TOC pointer (R2) to handle jumps between shared
11185   // libraries, and that will be stored in the fourth slot. The thread
11186   // identifier (R13) is not affected.
11187 
11188   // thisMBB:
11189   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11190   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11191   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11192 
11193   // Prepare IP either in reg.
11194   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11195   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11196   Register BufReg = MI.getOperand(1).getReg();
11197 
11198   if (Subtarget.is64BitELFABI()) {
11199     setUsesTOCBasePtr(*MBB->getParent());
11200     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11201               .addReg(PPC::X2)
11202               .addImm(TOCOffset)
11203               .addReg(BufReg)
11204               .cloneMemRefs(MI);
11205   }
11206 
11207   // Naked functions never have a base pointer, and so we use r1. For all
11208   // other functions, this decision must be delayed until during PEI.
11209   unsigned BaseReg;
11210   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11211     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11212   else
11213     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11214 
11215   MIB = BuildMI(*thisMBB, MI, DL,
11216                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11217             .addReg(BaseReg)
11218             .addImm(BPOffset)
11219             .addReg(BufReg)
11220             .cloneMemRefs(MI);
11221 
11222   // Setup
11223   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11224   MIB.addRegMask(TRI->getNoPreservedMask());
11225 
11226   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11227 
11228   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11229           .addMBB(mainMBB);
11230   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11231 
11232   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11233   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11234 
11235   // mainMBB:
11236   //  mainDstReg = 0
11237   MIB =
11238       BuildMI(mainMBB, DL,
11239               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11240 
11241   // Store IP
11242   if (Subtarget.isPPC64()) {
11243     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11244             .addReg(LabelReg)
11245             .addImm(LabelOffset)
11246             .addReg(BufReg);
11247   } else {
11248     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11249             .addReg(LabelReg)
11250             .addImm(LabelOffset)
11251             .addReg(BufReg);
11252   }
11253   MIB.cloneMemRefs(MI);
11254 
11255   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11256   mainMBB->addSuccessor(sinkMBB);
11257 
11258   // sinkMBB:
11259   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11260           TII->get(PPC::PHI), DstReg)
11261     .addReg(mainDstReg).addMBB(mainMBB)
11262     .addReg(restoreDstReg).addMBB(thisMBB);
11263 
11264   MI.eraseFromParent();
11265   return sinkMBB;
11266 }
11267 
11268 MachineBasicBlock *
11269 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11270                                      MachineBasicBlock *MBB) const {
11271   DebugLoc DL = MI.getDebugLoc();
11272   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11273 
11274   MachineFunction *MF = MBB->getParent();
11275   MachineRegisterInfo &MRI = MF->getRegInfo();
11276 
11277   MVT PVT = getPointerTy(MF->getDataLayout());
11278   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11279          "Invalid Pointer Size!");
11280 
11281   const TargetRegisterClass *RC =
11282     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11283   Register Tmp = MRI.createVirtualRegister(RC);
11284   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11285   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11286   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11287   unsigned BP =
11288       (PVT == MVT::i64)
11289           ? PPC::X30
11290           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11291                                                               : PPC::R30);
11292 
11293   MachineInstrBuilder MIB;
11294 
11295   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11296   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11297   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11298   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11299 
11300   Register BufReg = MI.getOperand(0).getReg();
11301 
11302   // Reload FP (the jumped-to function may not have had a
11303   // frame pointer, and if so, then its r31 will be restored
11304   // as necessary).
11305   if (PVT == MVT::i64) {
11306     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11307             .addImm(0)
11308             .addReg(BufReg);
11309   } else {
11310     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11311             .addImm(0)
11312             .addReg(BufReg);
11313   }
11314   MIB.cloneMemRefs(MI);
11315 
11316   // Reload IP
11317   if (PVT == MVT::i64) {
11318     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11319             .addImm(LabelOffset)
11320             .addReg(BufReg);
11321   } else {
11322     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11323             .addImm(LabelOffset)
11324             .addReg(BufReg);
11325   }
11326   MIB.cloneMemRefs(MI);
11327 
11328   // Reload SP
11329   if (PVT == MVT::i64) {
11330     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11331             .addImm(SPOffset)
11332             .addReg(BufReg);
11333   } else {
11334     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11335             .addImm(SPOffset)
11336             .addReg(BufReg);
11337   }
11338   MIB.cloneMemRefs(MI);
11339 
11340   // Reload BP
11341   if (PVT == MVT::i64) {
11342     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11343             .addImm(BPOffset)
11344             .addReg(BufReg);
11345   } else {
11346     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11347             .addImm(BPOffset)
11348             .addReg(BufReg);
11349   }
11350   MIB.cloneMemRefs(MI);
11351 
11352   // Reload TOC
11353   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11354     setUsesTOCBasePtr(*MBB->getParent());
11355     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11356               .addImm(TOCOffset)
11357               .addReg(BufReg)
11358               .cloneMemRefs(MI);
11359   }
11360 
11361   // Jump
11362   BuildMI(*MBB, MI, DL,
11363           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11364   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11365 
11366   MI.eraseFromParent();
11367   return MBB;
11368 }
11369 
11370 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11371   // If the function specifically requests inline stack probes, emit them.
11372   if (MF.getFunction().hasFnAttribute("probe-stack"))
11373     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11374            "inline-asm";
11375   return false;
11376 }
11377 
11378 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11379   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11380   unsigned StackAlign = TFI->getStackAlignment();
11381   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11382          "Unexpected stack alignment");
11383   // The default stack probe size is 4096 if the function has no
11384   // stack-probe-size attribute.
11385   unsigned StackProbeSize = 4096;
11386   const Function &Fn = MF.getFunction();
11387   if (Fn.hasFnAttribute("stack-probe-size"))
11388     Fn.getFnAttribute("stack-probe-size")
11389         .getValueAsString()
11390         .getAsInteger(0, StackProbeSize);
11391   // Round down to the stack alignment.
11392   StackProbeSize &= ~(StackAlign - 1);
11393   return StackProbeSize ? StackProbeSize : StackAlign;
11394 }
11395 
11396 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11397 // into three phases. In the first phase, it uses pseudo instruction
11398 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11399 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11400 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11401 // MaxCallFrameSize so that it can calculate correct data area pointer.
11402 MachineBasicBlock *
11403 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11404                                     MachineBasicBlock *MBB) const {
11405   const bool isPPC64 = Subtarget.isPPC64();
11406   MachineFunction *MF = MBB->getParent();
11407   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11408   DebugLoc DL = MI.getDebugLoc();
11409   const unsigned ProbeSize = getStackProbeSize(*MF);
11410   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11411   MachineRegisterInfo &MRI = MF->getRegInfo();
11412   // The CFG of probing stack looks as
11413   //         +-----+
11414   //         | MBB |
11415   //         +--+--+
11416   //            |
11417   //       +----v----+
11418   //  +--->+ TestMBB +---+
11419   //  |    +----+----+   |
11420   //  |         |        |
11421   //  |   +-----v----+   |
11422   //  +---+ BlockMBB |   |
11423   //      +----------+   |
11424   //                     |
11425   //       +---------+   |
11426   //       | TailMBB +<--+
11427   //       +---------+
11428   // In MBB, calculate previous frame pointer and final stack pointer.
11429   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11430   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11431   // TailMBB is spliced via \p MI.
11432   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11433   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11434   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11435 
11436   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11437   MF->insert(MBBIter, TestMBB);
11438   MF->insert(MBBIter, BlockMBB);
11439   MF->insert(MBBIter, TailMBB);
11440 
11441   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11442   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11443 
11444   Register DstReg = MI.getOperand(0).getReg();
11445   Register NegSizeReg = MI.getOperand(1).getReg();
11446   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11447   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11448   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11449   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11450 
11451   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11452   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11453   // NegSize.
11454   unsigned ProbeOpc;
11455   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11456     ProbeOpc =
11457         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11458   else
11459     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11460     // and NegSizeReg will be allocated in the same phyreg to avoid
11461     // redundant copy when NegSizeReg has only one use which is current MI and
11462     // will be replaced by PREPARE_PROBED_ALLOCA then.
11463     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11464                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11465   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11466       .addDef(ActualNegSizeReg)
11467       .addReg(NegSizeReg)
11468       .add(MI.getOperand(2))
11469       .add(MI.getOperand(3));
11470 
11471   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11472   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11473           FinalStackPtr)
11474       .addReg(SPReg)
11475       .addReg(ActualNegSizeReg);
11476 
11477   // Materialize a scratch register for update.
11478   int64_t NegProbeSize = -(int64_t)ProbeSize;
11479   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11480   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11481   if (!isInt<16>(NegProbeSize)) {
11482     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11483     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11484         .addImm(NegProbeSize >> 16);
11485     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11486             ScratchReg)
11487         .addReg(TempReg)
11488         .addImm(NegProbeSize & 0xFFFF);
11489   } else
11490     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11491         .addImm(NegProbeSize);
11492 
11493   {
11494     // Probing leading residual part.
11495     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11496     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11497         .addReg(ActualNegSizeReg)
11498         .addReg(ScratchReg);
11499     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11500     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11501         .addReg(Div)
11502         .addReg(ScratchReg);
11503     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11504     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11505         .addReg(Mul)
11506         .addReg(ActualNegSizeReg);
11507     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11508         .addReg(FramePointer)
11509         .addReg(SPReg)
11510         .addReg(NegMod);
11511   }
11512 
11513   {
11514     // Remaining part should be multiple of ProbeSize.
11515     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11516     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11517         .addReg(SPReg)
11518         .addReg(FinalStackPtr);
11519     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11520         .addImm(PPC::PRED_EQ)
11521         .addReg(CmpResult)
11522         .addMBB(TailMBB);
11523     TestMBB->addSuccessor(BlockMBB);
11524     TestMBB->addSuccessor(TailMBB);
11525   }
11526 
11527   {
11528     // Touch the block.
11529     // |P...|P...|P...
11530     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11531         .addReg(FramePointer)
11532         .addReg(SPReg)
11533         .addReg(ScratchReg);
11534     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11535     BlockMBB->addSuccessor(TestMBB);
11536   }
11537 
11538   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11539   // DYNAREAOFFSET pseudo instruction to get the future result.
11540   Register MaxCallFrameSizeReg =
11541       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11542   BuildMI(TailMBB, DL,
11543           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11544           MaxCallFrameSizeReg)
11545       .add(MI.getOperand(2))
11546       .add(MI.getOperand(3));
11547   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11548       .addReg(SPReg)
11549       .addReg(MaxCallFrameSizeReg);
11550 
11551   // Splice instructions after MI to TailMBB.
11552   TailMBB->splice(TailMBB->end(), MBB,
11553                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11554   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11555   MBB->addSuccessor(TestMBB);
11556 
11557   // Delete the pseudo instruction.
11558   MI.eraseFromParent();
11559 
11560   ++NumDynamicAllocaProbed;
11561   return TailMBB;
11562 }
11563 
11564 MachineBasicBlock *
11565 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11566                                                MachineBasicBlock *BB) const {
11567   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11568       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11569     if (Subtarget.is64BitELFABI() &&
11570         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11571         !Subtarget.isUsingPCRelativeCalls()) {
11572       // Call lowering should have added an r2 operand to indicate a dependence
11573       // on the TOC base pointer value. It can't however, because there is no
11574       // way to mark the dependence as implicit there, and so the stackmap code
11575       // will confuse it with a regular operand. Instead, add the dependence
11576       // here.
11577       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11578     }
11579 
11580     return emitPatchPoint(MI, BB);
11581   }
11582 
11583   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11584       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11585     return emitEHSjLjSetJmp(MI, BB);
11586   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11587              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11588     return emitEHSjLjLongJmp(MI, BB);
11589   }
11590 
11591   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11592 
11593   // To "insert" these instructions we actually have to insert their
11594   // control-flow patterns.
11595   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11596   MachineFunction::iterator It = ++BB->getIterator();
11597 
11598   MachineFunction *F = BB->getParent();
11599 
11600   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11601       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11602       MI.getOpcode() == PPC::SELECT_I8) {
11603     SmallVector<MachineOperand, 2> Cond;
11604     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11605         MI.getOpcode() == PPC::SELECT_CC_I8)
11606       Cond.push_back(MI.getOperand(4));
11607     else
11608       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11609     Cond.push_back(MI.getOperand(1));
11610 
11611     DebugLoc dl = MI.getDebugLoc();
11612     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11613                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11614   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11615              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11616              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11617              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11618              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11619              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11620              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11621              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11622              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11623              MI.getOpcode() == PPC::SELECT_F4 ||
11624              MI.getOpcode() == PPC::SELECT_F8 ||
11625              MI.getOpcode() == PPC::SELECT_F16 ||
11626              MI.getOpcode() == PPC::SELECT_SPE ||
11627              MI.getOpcode() == PPC::SELECT_SPE4 ||
11628              MI.getOpcode() == PPC::SELECT_VRRC ||
11629              MI.getOpcode() == PPC::SELECT_VSFRC ||
11630              MI.getOpcode() == PPC::SELECT_VSSRC ||
11631              MI.getOpcode() == PPC::SELECT_VSRC) {
11632     // The incoming instruction knows the destination vreg to set, the
11633     // condition code register to branch on, the true/false values to
11634     // select between, and a branch opcode to use.
11635 
11636     //  thisMBB:
11637     //  ...
11638     //   TrueVal = ...
11639     //   cmpTY ccX, r1, r2
11640     //   bCC copy1MBB
11641     //   fallthrough --> copy0MBB
11642     MachineBasicBlock *thisMBB = BB;
11643     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11644     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11645     DebugLoc dl = MI.getDebugLoc();
11646     F->insert(It, copy0MBB);
11647     F->insert(It, sinkMBB);
11648 
11649     // Transfer the remainder of BB and its successor edges to sinkMBB.
11650     sinkMBB->splice(sinkMBB->begin(), BB,
11651                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11652     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11653 
11654     // Next, add the true and fallthrough blocks as its successors.
11655     BB->addSuccessor(copy0MBB);
11656     BB->addSuccessor(sinkMBB);
11657 
11658     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11659         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11660         MI.getOpcode() == PPC::SELECT_F16 ||
11661         MI.getOpcode() == PPC::SELECT_SPE4 ||
11662         MI.getOpcode() == PPC::SELECT_SPE ||
11663         MI.getOpcode() == PPC::SELECT_VRRC ||
11664         MI.getOpcode() == PPC::SELECT_VSFRC ||
11665         MI.getOpcode() == PPC::SELECT_VSSRC ||
11666         MI.getOpcode() == PPC::SELECT_VSRC) {
11667       BuildMI(BB, dl, TII->get(PPC::BC))
11668           .addReg(MI.getOperand(1).getReg())
11669           .addMBB(sinkMBB);
11670     } else {
11671       unsigned SelectPred = MI.getOperand(4).getImm();
11672       BuildMI(BB, dl, TII->get(PPC::BCC))
11673           .addImm(SelectPred)
11674           .addReg(MI.getOperand(1).getReg())
11675           .addMBB(sinkMBB);
11676     }
11677 
11678     //  copy0MBB:
11679     //   %FalseValue = ...
11680     //   # fallthrough to sinkMBB
11681     BB = copy0MBB;
11682 
11683     // Update machine-CFG edges
11684     BB->addSuccessor(sinkMBB);
11685 
11686     //  sinkMBB:
11687     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11688     //  ...
11689     BB = sinkMBB;
11690     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11691         .addReg(MI.getOperand(3).getReg())
11692         .addMBB(copy0MBB)
11693         .addReg(MI.getOperand(2).getReg())
11694         .addMBB(thisMBB);
11695   } else if (MI.getOpcode() == PPC::ReadTB) {
11696     // To read the 64-bit time-base register on a 32-bit target, we read the
11697     // two halves. Should the counter have wrapped while it was being read, we
11698     // need to try again.
11699     // ...
11700     // readLoop:
11701     // mfspr Rx,TBU # load from TBU
11702     // mfspr Ry,TB  # load from TB
11703     // mfspr Rz,TBU # load from TBU
11704     // cmpw crX,Rx,Rz # check if 'old'='new'
11705     // bne readLoop   # branch if they're not equal
11706     // ...
11707 
11708     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11709     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11710     DebugLoc dl = MI.getDebugLoc();
11711     F->insert(It, readMBB);
11712     F->insert(It, sinkMBB);
11713 
11714     // Transfer the remainder of BB and its successor edges to sinkMBB.
11715     sinkMBB->splice(sinkMBB->begin(), BB,
11716                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11717     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11718 
11719     BB->addSuccessor(readMBB);
11720     BB = readMBB;
11721 
11722     MachineRegisterInfo &RegInfo = F->getRegInfo();
11723     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11724     Register LoReg = MI.getOperand(0).getReg();
11725     Register HiReg = MI.getOperand(1).getReg();
11726 
11727     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11728     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11729     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11730 
11731     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11732 
11733     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11734         .addReg(HiReg)
11735         .addReg(ReadAgainReg);
11736     BuildMI(BB, dl, TII->get(PPC::BCC))
11737         .addImm(PPC::PRED_NE)
11738         .addReg(CmpReg)
11739         .addMBB(readMBB);
11740 
11741     BB->addSuccessor(readMBB);
11742     BB->addSuccessor(sinkMBB);
11743   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11744     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11745   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11746     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11747   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11748     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11749   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11750     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11751 
11752   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11753     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11754   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11755     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11756   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11757     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11758   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11759     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11760 
11761   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11762     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11763   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11764     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11765   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11766     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11767   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11768     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11769 
11770   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11771     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11772   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11773     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11774   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11775     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11776   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11777     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11778 
11779   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11780     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11781   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11782     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11783   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11784     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11785   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11786     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11787 
11788   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11789     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11790   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11791     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11792   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11793     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11794   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11795     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11796 
11797   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11798     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11799   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11800     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11801   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11802     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11803   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11804     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11805 
11806   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11807     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11808   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11809     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11810   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11811     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11812   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11813     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11814 
11815   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11816     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11817   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11818     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11819   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11820     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11821   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11822     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11823 
11824   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11825     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11826   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11827     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11828   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11829     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11830   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11831     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11832 
11833   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11834     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11835   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11836     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11837   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11838     BB = EmitAtomicBinary(MI, BB, 4, 0);
11839   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11840     BB = EmitAtomicBinary(MI, BB, 8, 0);
11841   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11842            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11843            (Subtarget.hasPartwordAtomics() &&
11844             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11845            (Subtarget.hasPartwordAtomics() &&
11846             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11847     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11848 
11849     auto LoadMnemonic = PPC::LDARX;
11850     auto StoreMnemonic = PPC::STDCX;
11851     switch (MI.getOpcode()) {
11852     default:
11853       llvm_unreachable("Compare and swap of unknown size");
11854     case PPC::ATOMIC_CMP_SWAP_I8:
11855       LoadMnemonic = PPC::LBARX;
11856       StoreMnemonic = PPC::STBCX;
11857       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11858       break;
11859     case PPC::ATOMIC_CMP_SWAP_I16:
11860       LoadMnemonic = PPC::LHARX;
11861       StoreMnemonic = PPC::STHCX;
11862       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11863       break;
11864     case PPC::ATOMIC_CMP_SWAP_I32:
11865       LoadMnemonic = PPC::LWARX;
11866       StoreMnemonic = PPC::STWCX;
11867       break;
11868     case PPC::ATOMIC_CMP_SWAP_I64:
11869       LoadMnemonic = PPC::LDARX;
11870       StoreMnemonic = PPC::STDCX;
11871       break;
11872     }
11873     Register dest = MI.getOperand(0).getReg();
11874     Register ptrA = MI.getOperand(1).getReg();
11875     Register ptrB = MI.getOperand(2).getReg();
11876     Register oldval = MI.getOperand(3).getReg();
11877     Register newval = MI.getOperand(4).getReg();
11878     DebugLoc dl = MI.getDebugLoc();
11879 
11880     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11881     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11882     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11883     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11884     F->insert(It, loop1MBB);
11885     F->insert(It, loop2MBB);
11886     F->insert(It, midMBB);
11887     F->insert(It, exitMBB);
11888     exitMBB->splice(exitMBB->begin(), BB,
11889                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11890     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11891 
11892     //  thisMBB:
11893     //   ...
11894     //   fallthrough --> loopMBB
11895     BB->addSuccessor(loop1MBB);
11896 
11897     // loop1MBB:
11898     //   l[bhwd]arx dest, ptr
11899     //   cmp[wd] dest, oldval
11900     //   bne- midMBB
11901     // loop2MBB:
11902     //   st[bhwd]cx. newval, ptr
11903     //   bne- loopMBB
11904     //   b exitBB
11905     // midMBB:
11906     //   st[bhwd]cx. dest, ptr
11907     // exitBB:
11908     BB = loop1MBB;
11909     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11910     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11911         .addReg(oldval)
11912         .addReg(dest);
11913     BuildMI(BB, dl, TII->get(PPC::BCC))
11914         .addImm(PPC::PRED_NE)
11915         .addReg(PPC::CR0)
11916         .addMBB(midMBB);
11917     BB->addSuccessor(loop2MBB);
11918     BB->addSuccessor(midMBB);
11919 
11920     BB = loop2MBB;
11921     BuildMI(BB, dl, TII->get(StoreMnemonic))
11922         .addReg(newval)
11923         .addReg(ptrA)
11924         .addReg(ptrB);
11925     BuildMI(BB, dl, TII->get(PPC::BCC))
11926         .addImm(PPC::PRED_NE)
11927         .addReg(PPC::CR0)
11928         .addMBB(loop1MBB);
11929     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11930     BB->addSuccessor(loop1MBB);
11931     BB->addSuccessor(exitMBB);
11932 
11933     BB = midMBB;
11934     BuildMI(BB, dl, TII->get(StoreMnemonic))
11935         .addReg(dest)
11936         .addReg(ptrA)
11937         .addReg(ptrB);
11938     BB->addSuccessor(exitMBB);
11939 
11940     //  exitMBB:
11941     //   ...
11942     BB = exitMBB;
11943   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11944              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11945     // We must use 64-bit registers for addresses when targeting 64-bit,
11946     // since we're actually doing arithmetic on them.  Other registers
11947     // can be 32-bit.
11948     bool is64bit = Subtarget.isPPC64();
11949     bool isLittleEndian = Subtarget.isLittleEndian();
11950     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11951 
11952     Register dest = MI.getOperand(0).getReg();
11953     Register ptrA = MI.getOperand(1).getReg();
11954     Register ptrB = MI.getOperand(2).getReg();
11955     Register oldval = MI.getOperand(3).getReg();
11956     Register newval = MI.getOperand(4).getReg();
11957     DebugLoc dl = MI.getDebugLoc();
11958 
11959     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11960     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11961     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11962     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11963     F->insert(It, loop1MBB);
11964     F->insert(It, loop2MBB);
11965     F->insert(It, midMBB);
11966     F->insert(It, exitMBB);
11967     exitMBB->splice(exitMBB->begin(), BB,
11968                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11969     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11970 
11971     MachineRegisterInfo &RegInfo = F->getRegInfo();
11972     const TargetRegisterClass *RC =
11973         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11974     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11975 
11976     Register PtrReg = RegInfo.createVirtualRegister(RC);
11977     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11978     Register ShiftReg =
11979         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11980     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11981     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11982     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11983     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11984     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11985     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11986     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11987     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11988     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11989     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11990     Register Ptr1Reg;
11991     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11992     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11993     //  thisMBB:
11994     //   ...
11995     //   fallthrough --> loopMBB
11996     BB->addSuccessor(loop1MBB);
11997 
11998     // The 4-byte load must be aligned, while a char or short may be
11999     // anywhere in the word.  Hence all this nasty bookkeeping code.
12000     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12001     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12002     //   xori shift, shift1, 24 [16]
12003     //   rlwinm ptr, ptr1, 0, 0, 29
12004     //   slw newval2, newval, shift
12005     //   slw oldval2, oldval,shift
12006     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12007     //   slw mask, mask2, shift
12008     //   and newval3, newval2, mask
12009     //   and oldval3, oldval2, mask
12010     // loop1MBB:
12011     //   lwarx tmpDest, ptr
12012     //   and tmp, tmpDest, mask
12013     //   cmpw tmp, oldval3
12014     //   bne- midMBB
12015     // loop2MBB:
12016     //   andc tmp2, tmpDest, mask
12017     //   or tmp4, tmp2, newval3
12018     //   stwcx. tmp4, ptr
12019     //   bne- loop1MBB
12020     //   b exitBB
12021     // midMBB:
12022     //   stwcx. tmpDest, ptr
12023     // exitBB:
12024     //   srw dest, tmpDest, shift
12025     if (ptrA != ZeroReg) {
12026       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12027       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12028           .addReg(ptrA)
12029           .addReg(ptrB);
12030     } else {
12031       Ptr1Reg = ptrB;
12032     }
12033 
12034     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12035     // mode.
12036     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12037         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12038         .addImm(3)
12039         .addImm(27)
12040         .addImm(is8bit ? 28 : 27);
12041     if (!isLittleEndian)
12042       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12043           .addReg(Shift1Reg)
12044           .addImm(is8bit ? 24 : 16);
12045     if (is64bit)
12046       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12047           .addReg(Ptr1Reg)
12048           .addImm(0)
12049           .addImm(61);
12050     else
12051       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12052           .addReg(Ptr1Reg)
12053           .addImm(0)
12054           .addImm(0)
12055           .addImm(29);
12056     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12057         .addReg(newval)
12058         .addReg(ShiftReg);
12059     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12060         .addReg(oldval)
12061         .addReg(ShiftReg);
12062     if (is8bit)
12063       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12064     else {
12065       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12066       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12067           .addReg(Mask3Reg)
12068           .addImm(65535);
12069     }
12070     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12071         .addReg(Mask2Reg)
12072         .addReg(ShiftReg);
12073     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12074         .addReg(NewVal2Reg)
12075         .addReg(MaskReg);
12076     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12077         .addReg(OldVal2Reg)
12078         .addReg(MaskReg);
12079 
12080     BB = loop1MBB;
12081     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12082         .addReg(ZeroReg)
12083         .addReg(PtrReg);
12084     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12085         .addReg(TmpDestReg)
12086         .addReg(MaskReg);
12087     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12088         .addReg(TmpReg)
12089         .addReg(OldVal3Reg);
12090     BuildMI(BB, dl, TII->get(PPC::BCC))
12091         .addImm(PPC::PRED_NE)
12092         .addReg(PPC::CR0)
12093         .addMBB(midMBB);
12094     BB->addSuccessor(loop2MBB);
12095     BB->addSuccessor(midMBB);
12096 
12097     BB = loop2MBB;
12098     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12099         .addReg(TmpDestReg)
12100         .addReg(MaskReg);
12101     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12102         .addReg(Tmp2Reg)
12103         .addReg(NewVal3Reg);
12104     BuildMI(BB, dl, TII->get(PPC::STWCX))
12105         .addReg(Tmp4Reg)
12106         .addReg(ZeroReg)
12107         .addReg(PtrReg);
12108     BuildMI(BB, dl, TII->get(PPC::BCC))
12109         .addImm(PPC::PRED_NE)
12110         .addReg(PPC::CR0)
12111         .addMBB(loop1MBB);
12112     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12113     BB->addSuccessor(loop1MBB);
12114     BB->addSuccessor(exitMBB);
12115 
12116     BB = midMBB;
12117     BuildMI(BB, dl, TII->get(PPC::STWCX))
12118         .addReg(TmpDestReg)
12119         .addReg(ZeroReg)
12120         .addReg(PtrReg);
12121     BB->addSuccessor(exitMBB);
12122 
12123     //  exitMBB:
12124     //   ...
12125     BB = exitMBB;
12126     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12127         .addReg(TmpReg)
12128         .addReg(ShiftReg);
12129   } else if (MI.getOpcode() == PPC::FADDrtz) {
12130     // This pseudo performs an FADD with rounding mode temporarily forced
12131     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12132     // is not modeled at the SelectionDAG level.
12133     Register Dest = MI.getOperand(0).getReg();
12134     Register Src1 = MI.getOperand(1).getReg();
12135     Register Src2 = MI.getOperand(2).getReg();
12136     DebugLoc dl = MI.getDebugLoc();
12137 
12138     MachineRegisterInfo &RegInfo = F->getRegInfo();
12139     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12140 
12141     // Save FPSCR value.
12142     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12143 
12144     // Set rounding mode to round-to-zero.
12145     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12146         .addImm(31)
12147         .addReg(PPC::RM, RegState::ImplicitDefine);
12148 
12149     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12150         .addImm(30)
12151         .addReg(PPC::RM, RegState::ImplicitDefine);
12152 
12153     // Perform addition.
12154     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12155 
12156     // Restore FPSCR value.
12157     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12158   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12159              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12160              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12161              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12162     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12163                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12164                           ? PPC::ANDI8_rec
12165                           : PPC::ANDI_rec;
12166     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12167                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12168 
12169     MachineRegisterInfo &RegInfo = F->getRegInfo();
12170     Register Dest = RegInfo.createVirtualRegister(
12171         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12172 
12173     DebugLoc Dl = MI.getDebugLoc();
12174     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12175         .addReg(MI.getOperand(1).getReg())
12176         .addImm(1);
12177     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12178             MI.getOperand(0).getReg())
12179         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12180   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12181     DebugLoc Dl = MI.getDebugLoc();
12182     MachineRegisterInfo &RegInfo = F->getRegInfo();
12183     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12184     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12185     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12186             MI.getOperand(0).getReg())
12187         .addReg(CRReg);
12188   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12189     DebugLoc Dl = MI.getDebugLoc();
12190     unsigned Imm = MI.getOperand(1).getImm();
12191     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12192     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12193             MI.getOperand(0).getReg())
12194         .addReg(PPC::CR0EQ);
12195   } else if (MI.getOpcode() == PPC::SETRNDi) {
12196     DebugLoc dl = MI.getDebugLoc();
12197     Register OldFPSCRReg = MI.getOperand(0).getReg();
12198 
12199     // Save FPSCR value.
12200     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12201 
12202     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12203     // the following settings:
12204     //   00 Round to nearest
12205     //   01 Round to 0
12206     //   10 Round to +inf
12207     //   11 Round to -inf
12208 
12209     // When the operand is immediate, using the two least significant bits of
12210     // the immediate to set the bits 62:63 of FPSCR.
12211     unsigned Mode = MI.getOperand(1).getImm();
12212     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12213         .addImm(31)
12214         .addReg(PPC::RM, RegState::ImplicitDefine);
12215 
12216     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12217         .addImm(30)
12218         .addReg(PPC::RM, RegState::ImplicitDefine);
12219   } else if (MI.getOpcode() == PPC::SETRND) {
12220     DebugLoc dl = MI.getDebugLoc();
12221 
12222     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12223     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12224     // If the target doesn't have DirectMove, we should use stack to do the
12225     // conversion, because the target doesn't have the instructions like mtvsrd
12226     // or mfvsrd to do this conversion directly.
12227     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12228       if (Subtarget.hasDirectMove()) {
12229         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12230           .addReg(SrcReg);
12231       } else {
12232         // Use stack to do the register copy.
12233         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12234         MachineRegisterInfo &RegInfo = F->getRegInfo();
12235         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12236         if (RC == &PPC::F8RCRegClass) {
12237           // Copy register from F8RCRegClass to G8RCRegclass.
12238           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12239                  "Unsupported RegClass.");
12240 
12241           StoreOp = PPC::STFD;
12242           LoadOp = PPC::LD;
12243         } else {
12244           // Copy register from G8RCRegClass to F8RCRegclass.
12245           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12246                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12247                  "Unsupported RegClass.");
12248         }
12249 
12250         MachineFrameInfo &MFI = F->getFrameInfo();
12251         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12252 
12253         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12254             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12255             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12256             MFI.getObjectAlign(FrameIdx));
12257 
12258         // Store the SrcReg into the stack.
12259         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12260           .addReg(SrcReg)
12261           .addImm(0)
12262           .addFrameIndex(FrameIdx)
12263           .addMemOperand(MMOStore);
12264 
12265         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12266             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12267             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12268             MFI.getObjectAlign(FrameIdx));
12269 
12270         // Load from the stack where SrcReg is stored, and save to DestReg,
12271         // so we have done the RegClass conversion from RegClass::SrcReg to
12272         // RegClass::DestReg.
12273         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12274           .addImm(0)
12275           .addFrameIndex(FrameIdx)
12276           .addMemOperand(MMOLoad);
12277       }
12278     };
12279 
12280     Register OldFPSCRReg = MI.getOperand(0).getReg();
12281 
12282     // Save FPSCR value.
12283     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12284 
12285     // When the operand is gprc register, use two least significant bits of the
12286     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12287     //
12288     // copy OldFPSCRTmpReg, OldFPSCRReg
12289     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12290     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12291     // copy NewFPSCRReg, NewFPSCRTmpReg
12292     // mtfsf 255, NewFPSCRReg
12293     MachineOperand SrcOp = MI.getOperand(1);
12294     MachineRegisterInfo &RegInfo = F->getRegInfo();
12295     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12296 
12297     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12298 
12299     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12300     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12301 
12302     // The first operand of INSERT_SUBREG should be a register which has
12303     // subregisters, we only care about its RegClass, so we should use an
12304     // IMPLICIT_DEF register.
12305     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12306     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12307       .addReg(ImDefReg)
12308       .add(SrcOp)
12309       .addImm(1);
12310 
12311     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12312     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12313       .addReg(OldFPSCRTmpReg)
12314       .addReg(ExtSrcReg)
12315       .addImm(0)
12316       .addImm(62);
12317 
12318     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12319     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12320 
12321     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12322     // bits of FPSCR.
12323     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12324       .addImm(255)
12325       .addReg(NewFPSCRReg)
12326       .addImm(0)
12327       .addImm(0);
12328   } else if (MI.getOpcode() == PPC::SETFLM) {
12329     DebugLoc Dl = MI.getDebugLoc();
12330 
12331     // Result of setflm is previous FPSCR content, so we need to save it first.
12332     Register OldFPSCRReg = MI.getOperand(0).getReg();
12333     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12334 
12335     // Put bits in 32:63 to FPSCR.
12336     Register NewFPSCRReg = MI.getOperand(1).getReg();
12337     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12338         .addImm(255)
12339         .addReg(NewFPSCRReg)
12340         .addImm(0)
12341         .addImm(0);
12342   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12343              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12344     return emitProbedAlloca(MI, BB);
12345   } else {
12346     llvm_unreachable("Unexpected instr type to insert");
12347   }
12348 
12349   MI.eraseFromParent(); // The pseudo instruction is gone now.
12350   return BB;
12351 }
12352 
12353 //===----------------------------------------------------------------------===//
12354 // Target Optimization Hooks
12355 //===----------------------------------------------------------------------===//
12356 
12357 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12358   // For the estimates, convergence is quadratic, so we essentially double the
12359   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12360   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12361   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12362   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12363   if (VT.getScalarType() == MVT::f64)
12364     RefinementSteps++;
12365   return RefinementSteps;
12366 }
12367 
12368 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12369                                            int Enabled, int &RefinementSteps,
12370                                            bool &UseOneConstNR,
12371                                            bool Reciprocal) const {
12372   EVT VT = Operand.getValueType();
12373   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12374       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12375       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12376       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12377     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12378       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12379 
12380     // The Newton-Raphson computation with a single constant does not provide
12381     // enough accuracy on some CPUs.
12382     UseOneConstNR = !Subtarget.needsTwoConstNR();
12383     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12384   }
12385   return SDValue();
12386 }
12387 
12388 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12389                                             int Enabled,
12390                                             int &RefinementSteps) const {
12391   EVT VT = Operand.getValueType();
12392   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12393       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12394       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12395       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12396     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12397       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12398     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12399   }
12400   return SDValue();
12401 }
12402 
12403 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12404   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12405   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12406   // enabled for division), this functionality is redundant with the default
12407   // combiner logic (once the division -> reciprocal/multiply transformation
12408   // has taken place). As a result, this matters more for older cores than for
12409   // newer ones.
12410 
12411   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12412   // reciprocal if there are two or more FDIVs (for embedded cores with only
12413   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12414   switch (Subtarget.getCPUDirective()) {
12415   default:
12416     return 3;
12417   case PPC::DIR_440:
12418   case PPC::DIR_A2:
12419   case PPC::DIR_E500:
12420   case PPC::DIR_E500mc:
12421   case PPC::DIR_E5500:
12422     return 2;
12423   }
12424 }
12425 
12426 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12427 // collapsed, and so we need to look through chains of them.
12428 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12429                                      int64_t& Offset, SelectionDAG &DAG) {
12430   if (DAG.isBaseWithConstantOffset(Loc)) {
12431     Base = Loc.getOperand(0);
12432     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12433 
12434     // The base might itself be a base plus an offset, and if so, accumulate
12435     // that as well.
12436     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12437   }
12438 }
12439 
12440 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12441                             unsigned Bytes, int Dist,
12442                             SelectionDAG &DAG) {
12443   if (VT.getSizeInBits() / 8 != Bytes)
12444     return false;
12445 
12446   SDValue BaseLoc = Base->getBasePtr();
12447   if (Loc.getOpcode() == ISD::FrameIndex) {
12448     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12449       return false;
12450     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12451     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12452     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12453     int FS  = MFI.getObjectSize(FI);
12454     int BFS = MFI.getObjectSize(BFI);
12455     if (FS != BFS || FS != (int)Bytes) return false;
12456     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12457   }
12458 
12459   SDValue Base1 = Loc, Base2 = BaseLoc;
12460   int64_t Offset1 = 0, Offset2 = 0;
12461   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12462   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12463   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12464     return true;
12465 
12466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12467   const GlobalValue *GV1 = nullptr;
12468   const GlobalValue *GV2 = nullptr;
12469   Offset1 = 0;
12470   Offset2 = 0;
12471   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12472   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12473   if (isGA1 && isGA2 && GV1 == GV2)
12474     return Offset1 == (Offset2 + Dist*Bytes);
12475   return false;
12476 }
12477 
12478 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12479 // not enforce equality of the chain operands.
12480 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12481                             unsigned Bytes, int Dist,
12482                             SelectionDAG &DAG) {
12483   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12484     EVT VT = LS->getMemoryVT();
12485     SDValue Loc = LS->getBasePtr();
12486     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12487   }
12488 
12489   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12490     EVT VT;
12491     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12492     default: return false;
12493     case Intrinsic::ppc_altivec_lvx:
12494     case Intrinsic::ppc_altivec_lvxl:
12495     case Intrinsic::ppc_vsx_lxvw4x:
12496     case Intrinsic::ppc_vsx_lxvw4x_be:
12497       VT = MVT::v4i32;
12498       break;
12499     case Intrinsic::ppc_vsx_lxvd2x:
12500     case Intrinsic::ppc_vsx_lxvd2x_be:
12501       VT = MVT::v2f64;
12502       break;
12503     case Intrinsic::ppc_altivec_lvebx:
12504       VT = MVT::i8;
12505       break;
12506     case Intrinsic::ppc_altivec_lvehx:
12507       VT = MVT::i16;
12508       break;
12509     case Intrinsic::ppc_altivec_lvewx:
12510       VT = MVT::i32;
12511       break;
12512     }
12513 
12514     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12515   }
12516 
12517   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12518     EVT VT;
12519     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12520     default: return false;
12521     case Intrinsic::ppc_altivec_stvx:
12522     case Intrinsic::ppc_altivec_stvxl:
12523     case Intrinsic::ppc_vsx_stxvw4x:
12524       VT = MVT::v4i32;
12525       break;
12526     case Intrinsic::ppc_vsx_stxvd2x:
12527       VT = MVT::v2f64;
12528       break;
12529     case Intrinsic::ppc_vsx_stxvw4x_be:
12530       VT = MVT::v4i32;
12531       break;
12532     case Intrinsic::ppc_vsx_stxvd2x_be:
12533       VT = MVT::v2f64;
12534       break;
12535     case Intrinsic::ppc_altivec_stvebx:
12536       VT = MVT::i8;
12537       break;
12538     case Intrinsic::ppc_altivec_stvehx:
12539       VT = MVT::i16;
12540       break;
12541     case Intrinsic::ppc_altivec_stvewx:
12542       VT = MVT::i32;
12543       break;
12544     }
12545 
12546     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12547   }
12548 
12549   return false;
12550 }
12551 
12552 // Return true is there is a nearyby consecutive load to the one provided
12553 // (regardless of alignment). We search up and down the chain, looking though
12554 // token factors and other loads (but nothing else). As a result, a true result
12555 // indicates that it is safe to create a new consecutive load adjacent to the
12556 // load provided.
12557 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12558   SDValue Chain = LD->getChain();
12559   EVT VT = LD->getMemoryVT();
12560 
12561   SmallSet<SDNode *, 16> LoadRoots;
12562   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12563   SmallSet<SDNode *, 16> Visited;
12564 
12565   // First, search up the chain, branching to follow all token-factor operands.
12566   // If we find a consecutive load, then we're done, otherwise, record all
12567   // nodes just above the top-level loads and token factors.
12568   while (!Queue.empty()) {
12569     SDNode *ChainNext = Queue.pop_back_val();
12570     if (!Visited.insert(ChainNext).second)
12571       continue;
12572 
12573     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12574       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12575         return true;
12576 
12577       if (!Visited.count(ChainLD->getChain().getNode()))
12578         Queue.push_back(ChainLD->getChain().getNode());
12579     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12580       for (const SDUse &O : ChainNext->ops())
12581         if (!Visited.count(O.getNode()))
12582           Queue.push_back(O.getNode());
12583     } else
12584       LoadRoots.insert(ChainNext);
12585   }
12586 
12587   // Second, search down the chain, starting from the top-level nodes recorded
12588   // in the first phase. These top-level nodes are the nodes just above all
12589   // loads and token factors. Starting with their uses, recursively look though
12590   // all loads (just the chain uses) and token factors to find a consecutive
12591   // load.
12592   Visited.clear();
12593   Queue.clear();
12594 
12595   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12596        IE = LoadRoots.end(); I != IE; ++I) {
12597     Queue.push_back(*I);
12598 
12599     while (!Queue.empty()) {
12600       SDNode *LoadRoot = Queue.pop_back_val();
12601       if (!Visited.insert(LoadRoot).second)
12602         continue;
12603 
12604       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12605         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12606           return true;
12607 
12608       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12609            UE = LoadRoot->use_end(); UI != UE; ++UI)
12610         if (((isa<MemSDNode>(*UI) &&
12611             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12612             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12613           Queue.push_back(*UI);
12614     }
12615   }
12616 
12617   return false;
12618 }
12619 
12620 /// This function is called when we have proved that a SETCC node can be replaced
12621 /// by subtraction (and other supporting instructions) so that the result of
12622 /// comparison is kept in a GPR instead of CR. This function is purely for
12623 /// codegen purposes and has some flags to guide the codegen process.
12624 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12625                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12626   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12627 
12628   // Zero extend the operands to the largest legal integer. Originally, they
12629   // must be of a strictly smaller size.
12630   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12631                          DAG.getConstant(Size, DL, MVT::i32));
12632   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12633                          DAG.getConstant(Size, DL, MVT::i32));
12634 
12635   // Swap if needed. Depends on the condition code.
12636   if (Swap)
12637     std::swap(Op0, Op1);
12638 
12639   // Subtract extended integers.
12640   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12641 
12642   // Move the sign bit to the least significant position and zero out the rest.
12643   // Now the least significant bit carries the result of original comparison.
12644   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12645                              DAG.getConstant(Size - 1, DL, MVT::i32));
12646   auto Final = Shifted;
12647 
12648   // Complement the result if needed. Based on the condition code.
12649   if (Complement)
12650     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12651                         DAG.getConstant(1, DL, MVT::i64));
12652 
12653   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12654 }
12655 
12656 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12657                                                   DAGCombinerInfo &DCI) const {
12658   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12659 
12660   SelectionDAG &DAG = DCI.DAG;
12661   SDLoc DL(N);
12662 
12663   // Size of integers being compared has a critical role in the following
12664   // analysis, so we prefer to do this when all types are legal.
12665   if (!DCI.isAfterLegalizeDAG())
12666     return SDValue();
12667 
12668   // If all users of SETCC extend its value to a legal integer type
12669   // then we replace SETCC with a subtraction
12670   for (SDNode::use_iterator UI = N->use_begin(),
12671        UE = N->use_end(); UI != UE; ++UI) {
12672     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12673       return SDValue();
12674   }
12675 
12676   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12677   auto OpSize = N->getOperand(0).getValueSizeInBits();
12678 
12679   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12680 
12681   if (OpSize < Size) {
12682     switch (CC) {
12683     default: break;
12684     case ISD::SETULT:
12685       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12686     case ISD::SETULE:
12687       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12688     case ISD::SETUGT:
12689       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12690     case ISD::SETUGE:
12691       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12692     }
12693   }
12694 
12695   return SDValue();
12696 }
12697 
12698 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12699                                                   DAGCombinerInfo &DCI) const {
12700   SelectionDAG &DAG = DCI.DAG;
12701   SDLoc dl(N);
12702 
12703   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12704   // If we're tracking CR bits, we need to be careful that we don't have:
12705   //   trunc(binary-ops(zext(x), zext(y)))
12706   // or
12707   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12708   // such that we're unnecessarily moving things into GPRs when it would be
12709   // better to keep them in CR bits.
12710 
12711   // Note that trunc here can be an actual i1 trunc, or can be the effective
12712   // truncation that comes from a setcc or select_cc.
12713   if (N->getOpcode() == ISD::TRUNCATE &&
12714       N->getValueType(0) != MVT::i1)
12715     return SDValue();
12716 
12717   if (N->getOperand(0).getValueType() != MVT::i32 &&
12718       N->getOperand(0).getValueType() != MVT::i64)
12719     return SDValue();
12720 
12721   if (N->getOpcode() == ISD::SETCC ||
12722       N->getOpcode() == ISD::SELECT_CC) {
12723     // If we're looking at a comparison, then we need to make sure that the
12724     // high bits (all except for the first) don't matter the result.
12725     ISD::CondCode CC =
12726       cast<CondCodeSDNode>(N->getOperand(
12727         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12728     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12729 
12730     if (ISD::isSignedIntSetCC(CC)) {
12731       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12732           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12733         return SDValue();
12734     } else if (ISD::isUnsignedIntSetCC(CC)) {
12735       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12736                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12737           !DAG.MaskedValueIsZero(N->getOperand(1),
12738                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12739         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12740                                              : SDValue());
12741     } else {
12742       // This is neither a signed nor an unsigned comparison, just make sure
12743       // that the high bits are equal.
12744       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12745       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12746 
12747       // We don't really care about what is known about the first bit (if
12748       // anything), so clear it in all masks prior to comparing them.
12749       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12750       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12751 
12752       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12753         return SDValue();
12754     }
12755   }
12756 
12757   // We now know that the higher-order bits are irrelevant, we just need to
12758   // make sure that all of the intermediate operations are bit operations, and
12759   // all inputs are extensions.
12760   if (N->getOperand(0).getOpcode() != ISD::AND &&
12761       N->getOperand(0).getOpcode() != ISD::OR  &&
12762       N->getOperand(0).getOpcode() != ISD::XOR &&
12763       N->getOperand(0).getOpcode() != ISD::SELECT &&
12764       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12765       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12766       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12767       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12768       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12769     return SDValue();
12770 
12771   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12772       N->getOperand(1).getOpcode() != ISD::AND &&
12773       N->getOperand(1).getOpcode() != ISD::OR  &&
12774       N->getOperand(1).getOpcode() != ISD::XOR &&
12775       N->getOperand(1).getOpcode() != ISD::SELECT &&
12776       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12777       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12778       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12779       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12780       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12781     return SDValue();
12782 
12783   SmallVector<SDValue, 4> Inputs;
12784   SmallVector<SDValue, 8> BinOps, PromOps;
12785   SmallPtrSet<SDNode *, 16> Visited;
12786 
12787   for (unsigned i = 0; i < 2; ++i) {
12788     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12789           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12790           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12791           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12792         isa<ConstantSDNode>(N->getOperand(i)))
12793       Inputs.push_back(N->getOperand(i));
12794     else
12795       BinOps.push_back(N->getOperand(i));
12796 
12797     if (N->getOpcode() == ISD::TRUNCATE)
12798       break;
12799   }
12800 
12801   // Visit all inputs, collect all binary operations (and, or, xor and
12802   // select) that are all fed by extensions.
12803   while (!BinOps.empty()) {
12804     SDValue BinOp = BinOps.back();
12805     BinOps.pop_back();
12806 
12807     if (!Visited.insert(BinOp.getNode()).second)
12808       continue;
12809 
12810     PromOps.push_back(BinOp);
12811 
12812     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12813       // The condition of the select is not promoted.
12814       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12815         continue;
12816       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12817         continue;
12818 
12819       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12820             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12821             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12822            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12823           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12824         Inputs.push_back(BinOp.getOperand(i));
12825       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12826                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12827                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12828                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12829                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12830                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12831                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12832                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12833                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12834         BinOps.push_back(BinOp.getOperand(i));
12835       } else {
12836         // We have an input that is not an extension or another binary
12837         // operation; we'll abort this transformation.
12838         return SDValue();
12839       }
12840     }
12841   }
12842 
12843   // Make sure that this is a self-contained cluster of operations (which
12844   // is not quite the same thing as saying that everything has only one
12845   // use).
12846   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12847     if (isa<ConstantSDNode>(Inputs[i]))
12848       continue;
12849 
12850     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12851                               UE = Inputs[i].getNode()->use_end();
12852          UI != UE; ++UI) {
12853       SDNode *User = *UI;
12854       if (User != N && !Visited.count(User))
12855         return SDValue();
12856 
12857       // Make sure that we're not going to promote the non-output-value
12858       // operand(s) or SELECT or SELECT_CC.
12859       // FIXME: Although we could sometimes handle this, and it does occur in
12860       // practice that one of the condition inputs to the select is also one of
12861       // the outputs, we currently can't deal with this.
12862       if (User->getOpcode() == ISD::SELECT) {
12863         if (User->getOperand(0) == Inputs[i])
12864           return SDValue();
12865       } else if (User->getOpcode() == ISD::SELECT_CC) {
12866         if (User->getOperand(0) == Inputs[i] ||
12867             User->getOperand(1) == Inputs[i])
12868           return SDValue();
12869       }
12870     }
12871   }
12872 
12873   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12874     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12875                               UE = PromOps[i].getNode()->use_end();
12876          UI != UE; ++UI) {
12877       SDNode *User = *UI;
12878       if (User != N && !Visited.count(User))
12879         return SDValue();
12880 
12881       // Make sure that we're not going to promote the non-output-value
12882       // operand(s) or SELECT or SELECT_CC.
12883       // FIXME: Although we could sometimes handle this, and it does occur in
12884       // practice that one of the condition inputs to the select is also one of
12885       // the outputs, we currently can't deal with this.
12886       if (User->getOpcode() == ISD::SELECT) {
12887         if (User->getOperand(0) == PromOps[i])
12888           return SDValue();
12889       } else if (User->getOpcode() == ISD::SELECT_CC) {
12890         if (User->getOperand(0) == PromOps[i] ||
12891             User->getOperand(1) == PromOps[i])
12892           return SDValue();
12893       }
12894     }
12895   }
12896 
12897   // Replace all inputs with the extension operand.
12898   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12899     // Constants may have users outside the cluster of to-be-promoted nodes,
12900     // and so we need to replace those as we do the promotions.
12901     if (isa<ConstantSDNode>(Inputs[i]))
12902       continue;
12903     else
12904       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12905   }
12906 
12907   std::list<HandleSDNode> PromOpHandles;
12908   for (auto &PromOp : PromOps)
12909     PromOpHandles.emplace_back(PromOp);
12910 
12911   // Replace all operations (these are all the same, but have a different
12912   // (i1) return type). DAG.getNode will validate that the types of
12913   // a binary operator match, so go through the list in reverse so that
12914   // we've likely promoted both operands first. Any intermediate truncations or
12915   // extensions disappear.
12916   while (!PromOpHandles.empty()) {
12917     SDValue PromOp = PromOpHandles.back().getValue();
12918     PromOpHandles.pop_back();
12919 
12920     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12921         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12922         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12923         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12924       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12925           PromOp.getOperand(0).getValueType() != MVT::i1) {
12926         // The operand is not yet ready (see comment below).
12927         PromOpHandles.emplace_front(PromOp);
12928         continue;
12929       }
12930 
12931       SDValue RepValue = PromOp.getOperand(0);
12932       if (isa<ConstantSDNode>(RepValue))
12933         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12934 
12935       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12936       continue;
12937     }
12938 
12939     unsigned C;
12940     switch (PromOp.getOpcode()) {
12941     default:             C = 0; break;
12942     case ISD::SELECT:    C = 1; break;
12943     case ISD::SELECT_CC: C = 2; break;
12944     }
12945 
12946     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12947          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12948         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12949          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12950       // The to-be-promoted operands of this node have not yet been
12951       // promoted (this should be rare because we're going through the
12952       // list backward, but if one of the operands has several users in
12953       // this cluster of to-be-promoted nodes, it is possible).
12954       PromOpHandles.emplace_front(PromOp);
12955       continue;
12956     }
12957 
12958     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12959                                 PromOp.getNode()->op_end());
12960 
12961     // If there are any constant inputs, make sure they're replaced now.
12962     for (unsigned i = 0; i < 2; ++i)
12963       if (isa<ConstantSDNode>(Ops[C+i]))
12964         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12965 
12966     DAG.ReplaceAllUsesOfValueWith(PromOp,
12967       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12968   }
12969 
12970   // Now we're left with the initial truncation itself.
12971   if (N->getOpcode() == ISD::TRUNCATE)
12972     return N->getOperand(0);
12973 
12974   // Otherwise, this is a comparison. The operands to be compared have just
12975   // changed type (to i1), but everything else is the same.
12976   return SDValue(N, 0);
12977 }
12978 
12979 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12980                                                   DAGCombinerInfo &DCI) const {
12981   SelectionDAG &DAG = DCI.DAG;
12982   SDLoc dl(N);
12983 
12984   // If we're tracking CR bits, we need to be careful that we don't have:
12985   //   zext(binary-ops(trunc(x), trunc(y)))
12986   // or
12987   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12988   // such that we're unnecessarily moving things into CR bits that can more
12989   // efficiently stay in GPRs. Note that if we're not certain that the high
12990   // bits are set as required by the final extension, we still may need to do
12991   // some masking to get the proper behavior.
12992 
12993   // This same functionality is important on PPC64 when dealing with
12994   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12995   // the return values of functions. Because it is so similar, it is handled
12996   // here as well.
12997 
12998   if (N->getValueType(0) != MVT::i32 &&
12999       N->getValueType(0) != MVT::i64)
13000     return SDValue();
13001 
13002   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13003         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13004     return SDValue();
13005 
13006   if (N->getOperand(0).getOpcode() != ISD::AND &&
13007       N->getOperand(0).getOpcode() != ISD::OR  &&
13008       N->getOperand(0).getOpcode() != ISD::XOR &&
13009       N->getOperand(0).getOpcode() != ISD::SELECT &&
13010       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13011     return SDValue();
13012 
13013   SmallVector<SDValue, 4> Inputs;
13014   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13015   SmallPtrSet<SDNode *, 16> Visited;
13016 
13017   // Visit all inputs, collect all binary operations (and, or, xor and
13018   // select) that are all fed by truncations.
13019   while (!BinOps.empty()) {
13020     SDValue BinOp = BinOps.back();
13021     BinOps.pop_back();
13022 
13023     if (!Visited.insert(BinOp.getNode()).second)
13024       continue;
13025 
13026     PromOps.push_back(BinOp);
13027 
13028     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13029       // The condition of the select is not promoted.
13030       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13031         continue;
13032       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13033         continue;
13034 
13035       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13036           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13037         Inputs.push_back(BinOp.getOperand(i));
13038       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13039                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13040                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13041                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13042                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13043         BinOps.push_back(BinOp.getOperand(i));
13044       } else {
13045         // We have an input that is not a truncation or another binary
13046         // operation; we'll abort this transformation.
13047         return SDValue();
13048       }
13049     }
13050   }
13051 
13052   // The operands of a select that must be truncated when the select is
13053   // promoted because the operand is actually part of the to-be-promoted set.
13054   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13055 
13056   // Make sure that this is a self-contained cluster of operations (which
13057   // is not quite the same thing as saying that everything has only one
13058   // use).
13059   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13060     if (isa<ConstantSDNode>(Inputs[i]))
13061       continue;
13062 
13063     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13064                               UE = Inputs[i].getNode()->use_end();
13065          UI != UE; ++UI) {
13066       SDNode *User = *UI;
13067       if (User != N && !Visited.count(User))
13068         return SDValue();
13069 
13070       // If we're going to promote the non-output-value operand(s) or SELECT or
13071       // SELECT_CC, record them for truncation.
13072       if (User->getOpcode() == ISD::SELECT) {
13073         if (User->getOperand(0) == Inputs[i])
13074           SelectTruncOp[0].insert(std::make_pair(User,
13075                                     User->getOperand(0).getValueType()));
13076       } else if (User->getOpcode() == ISD::SELECT_CC) {
13077         if (User->getOperand(0) == Inputs[i])
13078           SelectTruncOp[0].insert(std::make_pair(User,
13079                                     User->getOperand(0).getValueType()));
13080         if (User->getOperand(1) == Inputs[i])
13081           SelectTruncOp[1].insert(std::make_pair(User,
13082                                     User->getOperand(1).getValueType()));
13083       }
13084     }
13085   }
13086 
13087   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13088     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13089                               UE = PromOps[i].getNode()->use_end();
13090          UI != UE; ++UI) {
13091       SDNode *User = *UI;
13092       if (User != N && !Visited.count(User))
13093         return SDValue();
13094 
13095       // If we're going to promote the non-output-value operand(s) or SELECT or
13096       // SELECT_CC, record them for truncation.
13097       if (User->getOpcode() == ISD::SELECT) {
13098         if (User->getOperand(0) == PromOps[i])
13099           SelectTruncOp[0].insert(std::make_pair(User,
13100                                     User->getOperand(0).getValueType()));
13101       } else if (User->getOpcode() == ISD::SELECT_CC) {
13102         if (User->getOperand(0) == PromOps[i])
13103           SelectTruncOp[0].insert(std::make_pair(User,
13104                                     User->getOperand(0).getValueType()));
13105         if (User->getOperand(1) == PromOps[i])
13106           SelectTruncOp[1].insert(std::make_pair(User,
13107                                     User->getOperand(1).getValueType()));
13108       }
13109     }
13110   }
13111 
13112   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13113   bool ReallyNeedsExt = false;
13114   if (N->getOpcode() != ISD::ANY_EXTEND) {
13115     // If all of the inputs are not already sign/zero extended, then
13116     // we'll still need to do that at the end.
13117     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13118       if (isa<ConstantSDNode>(Inputs[i]))
13119         continue;
13120 
13121       unsigned OpBits =
13122         Inputs[i].getOperand(0).getValueSizeInBits();
13123       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13124 
13125       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13126            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13127                                   APInt::getHighBitsSet(OpBits,
13128                                                         OpBits-PromBits))) ||
13129           (N->getOpcode() == ISD::SIGN_EXTEND &&
13130            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13131              (OpBits-(PromBits-1)))) {
13132         ReallyNeedsExt = true;
13133         break;
13134       }
13135     }
13136   }
13137 
13138   // Replace all inputs, either with the truncation operand, or a
13139   // truncation or extension to the final output type.
13140   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13141     // Constant inputs need to be replaced with the to-be-promoted nodes that
13142     // use them because they might have users outside of the cluster of
13143     // promoted nodes.
13144     if (isa<ConstantSDNode>(Inputs[i]))
13145       continue;
13146 
13147     SDValue InSrc = Inputs[i].getOperand(0);
13148     if (Inputs[i].getValueType() == N->getValueType(0))
13149       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13150     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13151       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13152         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13153     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13154       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13155         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13156     else
13157       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13158         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13159   }
13160 
13161   std::list<HandleSDNode> PromOpHandles;
13162   for (auto &PromOp : PromOps)
13163     PromOpHandles.emplace_back(PromOp);
13164 
13165   // Replace all operations (these are all the same, but have a different
13166   // (promoted) return type). DAG.getNode will validate that the types of
13167   // a binary operator match, so go through the list in reverse so that
13168   // we've likely promoted both operands first.
13169   while (!PromOpHandles.empty()) {
13170     SDValue PromOp = PromOpHandles.back().getValue();
13171     PromOpHandles.pop_back();
13172 
13173     unsigned C;
13174     switch (PromOp.getOpcode()) {
13175     default:             C = 0; break;
13176     case ISD::SELECT:    C = 1; break;
13177     case ISD::SELECT_CC: C = 2; break;
13178     }
13179 
13180     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13181          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13182         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13183          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13184       // The to-be-promoted operands of this node have not yet been
13185       // promoted (this should be rare because we're going through the
13186       // list backward, but if one of the operands has several users in
13187       // this cluster of to-be-promoted nodes, it is possible).
13188       PromOpHandles.emplace_front(PromOp);
13189       continue;
13190     }
13191 
13192     // For SELECT and SELECT_CC nodes, we do a similar check for any
13193     // to-be-promoted comparison inputs.
13194     if (PromOp.getOpcode() == ISD::SELECT ||
13195         PromOp.getOpcode() == ISD::SELECT_CC) {
13196       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13197            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13198           (SelectTruncOp[1].count(PromOp.getNode()) &&
13199            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13200         PromOpHandles.emplace_front(PromOp);
13201         continue;
13202       }
13203     }
13204 
13205     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13206                                 PromOp.getNode()->op_end());
13207 
13208     // If this node has constant inputs, then they'll need to be promoted here.
13209     for (unsigned i = 0; i < 2; ++i) {
13210       if (!isa<ConstantSDNode>(Ops[C+i]))
13211         continue;
13212       if (Ops[C+i].getValueType() == N->getValueType(0))
13213         continue;
13214 
13215       if (N->getOpcode() == ISD::SIGN_EXTEND)
13216         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13217       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13218         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13219       else
13220         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13221     }
13222 
13223     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13224     // truncate them again to the original value type.
13225     if (PromOp.getOpcode() == ISD::SELECT ||
13226         PromOp.getOpcode() == ISD::SELECT_CC) {
13227       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13228       if (SI0 != SelectTruncOp[0].end())
13229         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13230       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13231       if (SI1 != SelectTruncOp[1].end())
13232         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13233     }
13234 
13235     DAG.ReplaceAllUsesOfValueWith(PromOp,
13236       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13237   }
13238 
13239   // Now we're left with the initial extension itself.
13240   if (!ReallyNeedsExt)
13241     return N->getOperand(0);
13242 
13243   // To zero extend, just mask off everything except for the first bit (in the
13244   // i1 case).
13245   if (N->getOpcode() == ISD::ZERO_EXTEND)
13246     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13247                        DAG.getConstant(APInt::getLowBitsSet(
13248                                          N->getValueSizeInBits(0), PromBits),
13249                                        dl, N->getValueType(0)));
13250 
13251   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13252          "Invalid extension type");
13253   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13254   SDValue ShiftCst =
13255       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13256   return DAG.getNode(
13257       ISD::SRA, dl, N->getValueType(0),
13258       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13259       ShiftCst);
13260 }
13261 
13262 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13263                                         DAGCombinerInfo &DCI) const {
13264   assert(N->getOpcode() == ISD::SETCC &&
13265          "Should be called with a SETCC node");
13266 
13267   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13268   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13269     SDValue LHS = N->getOperand(0);
13270     SDValue RHS = N->getOperand(1);
13271 
13272     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13273     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13274         LHS.hasOneUse())
13275       std::swap(LHS, RHS);
13276 
13277     // x == 0-y --> x+y == 0
13278     // x != 0-y --> x+y != 0
13279     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13280         RHS.hasOneUse()) {
13281       SDLoc DL(N);
13282       SelectionDAG &DAG = DCI.DAG;
13283       EVT VT = N->getValueType(0);
13284       EVT OpVT = LHS.getValueType();
13285       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13286       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13287     }
13288   }
13289 
13290   return DAGCombineTruncBoolExt(N, DCI);
13291 }
13292 
13293 // Is this an extending load from an f32 to an f64?
13294 static bool isFPExtLoad(SDValue Op) {
13295   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13296     return LD->getExtensionType() == ISD::EXTLOAD &&
13297       Op.getValueType() == MVT::f64;
13298   return false;
13299 }
13300 
13301 /// Reduces the number of fp-to-int conversion when building a vector.
13302 ///
13303 /// If this vector is built out of floating to integer conversions,
13304 /// transform it to a vector built out of floating point values followed by a
13305 /// single floating to integer conversion of the vector.
13306 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13307 /// becomes (fptosi (build_vector ($A, $B, ...)))
13308 SDValue PPCTargetLowering::
13309 combineElementTruncationToVectorTruncation(SDNode *N,
13310                                            DAGCombinerInfo &DCI) const {
13311   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13312          "Should be called with a BUILD_VECTOR node");
13313 
13314   SelectionDAG &DAG = DCI.DAG;
13315   SDLoc dl(N);
13316 
13317   SDValue FirstInput = N->getOperand(0);
13318   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13319          "The input operand must be an fp-to-int conversion.");
13320 
13321   // This combine happens after legalization so the fp_to_[su]i nodes are
13322   // already converted to PPCSISD nodes.
13323   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13324   if (FirstConversion == PPCISD::FCTIDZ ||
13325       FirstConversion == PPCISD::FCTIDUZ ||
13326       FirstConversion == PPCISD::FCTIWZ ||
13327       FirstConversion == PPCISD::FCTIWUZ) {
13328     bool IsSplat = true;
13329     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13330       FirstConversion == PPCISD::FCTIWUZ;
13331     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13332     SmallVector<SDValue, 4> Ops;
13333     EVT TargetVT = N->getValueType(0);
13334     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13335       SDValue NextOp = N->getOperand(i);
13336       if (NextOp.getOpcode() != PPCISD::MFVSR)
13337         return SDValue();
13338       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13339       if (NextConversion != FirstConversion)
13340         return SDValue();
13341       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13342       // This is not valid if the input was originally double precision. It is
13343       // also not profitable to do unless this is an extending load in which
13344       // case doing this combine will allow us to combine consecutive loads.
13345       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13346         return SDValue();
13347       if (N->getOperand(i) != FirstInput)
13348         IsSplat = false;
13349     }
13350 
13351     // If this is a splat, we leave it as-is since there will be only a single
13352     // fp-to-int conversion followed by a splat of the integer. This is better
13353     // for 32-bit and smaller ints and neutral for 64-bit ints.
13354     if (IsSplat)
13355       return SDValue();
13356 
13357     // Now that we know we have the right type of node, get its operands
13358     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13359       SDValue In = N->getOperand(i).getOperand(0);
13360       if (Is32Bit) {
13361         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13362         // here, we know that all inputs are extending loads so this is safe).
13363         if (In.isUndef())
13364           Ops.push_back(DAG.getUNDEF(SrcVT));
13365         else {
13366           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13367                                       MVT::f32, In.getOperand(0),
13368                                       DAG.getIntPtrConstant(1, dl));
13369           Ops.push_back(Trunc);
13370         }
13371       } else
13372         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13373     }
13374 
13375     unsigned Opcode;
13376     if (FirstConversion == PPCISD::FCTIDZ ||
13377         FirstConversion == PPCISD::FCTIWZ)
13378       Opcode = ISD::FP_TO_SINT;
13379     else
13380       Opcode = ISD::FP_TO_UINT;
13381 
13382     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13383     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13384     return DAG.getNode(Opcode, dl, TargetVT, BV);
13385   }
13386   return SDValue();
13387 }
13388 
13389 /// Reduce the number of loads when building a vector.
13390 ///
13391 /// Building a vector out of multiple loads can be converted to a load
13392 /// of the vector type if the loads are consecutive. If the loads are
13393 /// consecutive but in descending order, a shuffle is added at the end
13394 /// to reorder the vector.
13395 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13396   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13397          "Should be called with a BUILD_VECTOR node");
13398 
13399   SDLoc dl(N);
13400 
13401   // Return early for non byte-sized type, as they can't be consecutive.
13402   if (!N->getValueType(0).getVectorElementType().isByteSized())
13403     return SDValue();
13404 
13405   bool InputsAreConsecutiveLoads = true;
13406   bool InputsAreReverseConsecutive = true;
13407   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13408   SDValue FirstInput = N->getOperand(0);
13409   bool IsRoundOfExtLoad = false;
13410 
13411   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13412       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13413     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13414     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13415   }
13416   // Not a build vector of (possibly fp_rounded) loads.
13417   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13418       N->getNumOperands() == 1)
13419     return SDValue();
13420 
13421   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13422     // If any inputs are fp_round(extload), they all must be.
13423     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13424       return SDValue();
13425 
13426     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13427       N->getOperand(i);
13428     if (NextInput.getOpcode() != ISD::LOAD)
13429       return SDValue();
13430 
13431     SDValue PreviousInput =
13432       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13433     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13434     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13435 
13436     // If any inputs are fp_round(extload), they all must be.
13437     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13438       return SDValue();
13439 
13440     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13441       InputsAreConsecutiveLoads = false;
13442     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13443       InputsAreReverseConsecutive = false;
13444 
13445     // Exit early if the loads are neither consecutive nor reverse consecutive.
13446     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13447       return SDValue();
13448   }
13449 
13450   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13451          "The loads cannot be both consecutive and reverse consecutive.");
13452 
13453   SDValue FirstLoadOp =
13454     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13455   SDValue LastLoadOp =
13456     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13457                        N->getOperand(N->getNumOperands()-1);
13458 
13459   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13460   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13461   if (InputsAreConsecutiveLoads) {
13462     assert(LD1 && "Input needs to be a LoadSDNode.");
13463     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13464                        LD1->getBasePtr(), LD1->getPointerInfo(),
13465                        LD1->getAlignment());
13466   }
13467   if (InputsAreReverseConsecutive) {
13468     assert(LDL && "Input needs to be a LoadSDNode.");
13469     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13470                                LDL->getBasePtr(), LDL->getPointerInfo(),
13471                                LDL->getAlignment());
13472     SmallVector<int, 16> Ops;
13473     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13474       Ops.push_back(i);
13475 
13476     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13477                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13478   }
13479   return SDValue();
13480 }
13481 
13482 // This function adds the required vector_shuffle needed to get
13483 // the elements of the vector extract in the correct position
13484 // as specified by the CorrectElems encoding.
13485 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13486                                       SDValue Input, uint64_t Elems,
13487                                       uint64_t CorrectElems) {
13488   SDLoc dl(N);
13489 
13490   unsigned NumElems = Input.getValueType().getVectorNumElements();
13491   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13492 
13493   // Knowing the element indices being extracted from the original
13494   // vector and the order in which they're being inserted, just put
13495   // them at element indices required for the instruction.
13496   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13497     if (DAG.getDataLayout().isLittleEndian())
13498       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13499     else
13500       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13501     CorrectElems = CorrectElems >> 8;
13502     Elems = Elems >> 8;
13503   }
13504 
13505   SDValue Shuffle =
13506       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13507                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13508 
13509   EVT VT = N->getValueType(0);
13510   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13511 
13512   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13513                                Input.getValueType().getVectorElementType(),
13514                                VT.getVectorNumElements());
13515   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13516                      DAG.getValueType(ExtVT));
13517 }
13518 
13519 // Look for build vector patterns where input operands come from sign
13520 // extended vector_extract elements of specific indices. If the correct indices
13521 // aren't used, add a vector shuffle to fix up the indices and create
13522 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13523 // during instruction selection.
13524 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13525   // This array encodes the indices that the vector sign extend instructions
13526   // extract from when extending from one type to another for both BE and LE.
13527   // The right nibble of each byte corresponds to the LE incides.
13528   // and the left nibble of each byte corresponds to the BE incides.
13529   // For example: 0x3074B8FC  byte->word
13530   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13531   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13532   // For example: 0x000070F8  byte->double word
13533   // For LE: the allowed indices are: 0x0,0x8
13534   // For BE: the allowed indices are: 0x7,0xF
13535   uint64_t TargetElems[] = {
13536       0x3074B8FC, // b->w
13537       0x000070F8, // b->d
13538       0x10325476, // h->w
13539       0x00003074, // h->d
13540       0x00001032, // w->d
13541   };
13542 
13543   uint64_t Elems = 0;
13544   int Index;
13545   SDValue Input;
13546 
13547   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13548     if (!Op)
13549       return false;
13550     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13551         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13552       return false;
13553 
13554     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13555     // of the right width.
13556     SDValue Extract = Op.getOperand(0);
13557     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13558       Extract = Extract.getOperand(0);
13559     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13560       return false;
13561 
13562     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13563     if (!ExtOp)
13564       return false;
13565 
13566     Index = ExtOp->getZExtValue();
13567     if (Input && Input != Extract.getOperand(0))
13568       return false;
13569 
13570     if (!Input)
13571       Input = Extract.getOperand(0);
13572 
13573     Elems = Elems << 8;
13574     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13575     Elems |= Index;
13576 
13577     return true;
13578   };
13579 
13580   // If the build vector operands aren't sign extended vector extracts,
13581   // of the same input vector, then return.
13582   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13583     if (!isSExtOfVecExtract(N->getOperand(i))) {
13584       return SDValue();
13585     }
13586   }
13587 
13588   // If the vector extract indicies are not correct, add the appropriate
13589   // vector_shuffle.
13590   int TgtElemArrayIdx;
13591   int InputSize = Input.getValueType().getScalarSizeInBits();
13592   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13593   if (InputSize + OutputSize == 40)
13594     TgtElemArrayIdx = 0;
13595   else if (InputSize + OutputSize == 72)
13596     TgtElemArrayIdx = 1;
13597   else if (InputSize + OutputSize == 48)
13598     TgtElemArrayIdx = 2;
13599   else if (InputSize + OutputSize == 80)
13600     TgtElemArrayIdx = 3;
13601   else if (InputSize + OutputSize == 96)
13602     TgtElemArrayIdx = 4;
13603   else
13604     return SDValue();
13605 
13606   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13607   CorrectElems = DAG.getDataLayout().isLittleEndian()
13608                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13609                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13610   if (Elems != CorrectElems) {
13611     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13612   }
13613 
13614   // Regular lowering will catch cases where a shuffle is not needed.
13615   return SDValue();
13616 }
13617 
13618 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13619                                                  DAGCombinerInfo &DCI) const {
13620   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13621          "Should be called with a BUILD_VECTOR node");
13622 
13623   SelectionDAG &DAG = DCI.DAG;
13624   SDLoc dl(N);
13625 
13626   if (!Subtarget.hasVSX())
13627     return SDValue();
13628 
13629   // The target independent DAG combiner will leave a build_vector of
13630   // float-to-int conversions intact. We can generate MUCH better code for
13631   // a float-to-int conversion of a vector of floats.
13632   SDValue FirstInput = N->getOperand(0);
13633   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13634     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13635     if (Reduced)
13636       return Reduced;
13637   }
13638 
13639   // If we're building a vector out of consecutive loads, just load that
13640   // vector type.
13641   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13642   if (Reduced)
13643     return Reduced;
13644 
13645   // If we're building a vector out of extended elements from another vector
13646   // we have P9 vector integer extend instructions. The code assumes legal
13647   // input types (i.e. it can't handle things like v4i16) so do not run before
13648   // legalization.
13649   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13650     Reduced = combineBVOfVecSExt(N, DAG);
13651     if (Reduced)
13652       return Reduced;
13653   }
13654 
13655 
13656   if (N->getValueType(0) != MVT::v2f64)
13657     return SDValue();
13658 
13659   // Looking for:
13660   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13661   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13662       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13663     return SDValue();
13664   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13665       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13666     return SDValue();
13667   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13668     return SDValue();
13669 
13670   SDValue Ext1 = FirstInput.getOperand(0);
13671   SDValue Ext2 = N->getOperand(1).getOperand(0);
13672   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13673      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13674     return SDValue();
13675 
13676   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13677   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13678   if (!Ext1Op || !Ext2Op)
13679     return SDValue();
13680   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13681       Ext1.getOperand(0) != Ext2.getOperand(0))
13682     return SDValue();
13683 
13684   int FirstElem = Ext1Op->getZExtValue();
13685   int SecondElem = Ext2Op->getZExtValue();
13686   int SubvecIdx;
13687   if (FirstElem == 0 && SecondElem == 1)
13688     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13689   else if (FirstElem == 2 && SecondElem == 3)
13690     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13691   else
13692     return SDValue();
13693 
13694   SDValue SrcVec = Ext1.getOperand(0);
13695   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13696     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13697   return DAG.getNode(NodeType, dl, MVT::v2f64,
13698                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13699 }
13700 
13701 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13702                                               DAGCombinerInfo &DCI) const {
13703   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13704           N->getOpcode() == ISD::UINT_TO_FP) &&
13705          "Need an int -> FP conversion node here");
13706 
13707   if (useSoftFloat() || !Subtarget.has64BitSupport())
13708     return SDValue();
13709 
13710   SelectionDAG &DAG = DCI.DAG;
13711   SDLoc dl(N);
13712   SDValue Op(N, 0);
13713 
13714   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13715   // from the hardware.
13716   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13717     return SDValue();
13718   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13719       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13720     return SDValue();
13721 
13722   SDValue FirstOperand(Op.getOperand(0));
13723   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13724     (FirstOperand.getValueType() == MVT::i8 ||
13725      FirstOperand.getValueType() == MVT::i16);
13726   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13727     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13728     bool DstDouble = Op.getValueType() == MVT::f64;
13729     unsigned ConvOp = Signed ?
13730       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13731       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13732     SDValue WidthConst =
13733       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13734                             dl, false);
13735     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13736     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13737     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13738                                          DAG.getVTList(MVT::f64, MVT::Other),
13739                                          Ops, MVT::i8, LDN->getMemOperand());
13740 
13741     // For signed conversion, we need to sign-extend the value in the VSR
13742     if (Signed) {
13743       SDValue ExtOps[] = { Ld, WidthConst };
13744       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13745       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13746     } else
13747       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13748   }
13749 
13750 
13751   // For i32 intermediate values, unfortunately, the conversion functions
13752   // leave the upper 32 bits of the value are undefined. Within the set of
13753   // scalar instructions, we have no method for zero- or sign-extending the
13754   // value. Thus, we cannot handle i32 intermediate values here.
13755   if (Op.getOperand(0).getValueType() == MVT::i32)
13756     return SDValue();
13757 
13758   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13759          "UINT_TO_FP is supported only with FPCVT");
13760 
13761   // If we have FCFIDS, then use it when converting to single-precision.
13762   // Otherwise, convert to double-precision and then round.
13763   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13764                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13765                                                             : PPCISD::FCFIDS)
13766                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13767                                                             : PPCISD::FCFID);
13768   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13769                   ? MVT::f32
13770                   : MVT::f64;
13771 
13772   // If we're converting from a float, to an int, and back to a float again,
13773   // then we don't need the store/load pair at all.
13774   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13775        Subtarget.hasFPCVT()) ||
13776       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13777     SDValue Src = Op.getOperand(0).getOperand(0);
13778     if (Src.getValueType() == MVT::f32) {
13779       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13780       DCI.AddToWorklist(Src.getNode());
13781     } else if (Src.getValueType() != MVT::f64) {
13782       // Make sure that we don't pick up a ppc_fp128 source value.
13783       return SDValue();
13784     }
13785 
13786     unsigned FCTOp =
13787       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13788                                                         PPCISD::FCTIDUZ;
13789 
13790     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13791     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13792 
13793     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13794       FP = DAG.getNode(ISD::FP_ROUND, dl,
13795                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13796       DCI.AddToWorklist(FP.getNode());
13797     }
13798 
13799     return FP;
13800   }
13801 
13802   return SDValue();
13803 }
13804 
13805 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13806 // builtins) into loads with swaps.
13807 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13808                                               DAGCombinerInfo &DCI) const {
13809   SelectionDAG &DAG = DCI.DAG;
13810   SDLoc dl(N);
13811   SDValue Chain;
13812   SDValue Base;
13813   MachineMemOperand *MMO;
13814 
13815   switch (N->getOpcode()) {
13816   default:
13817     llvm_unreachable("Unexpected opcode for little endian VSX load");
13818   case ISD::LOAD: {
13819     LoadSDNode *LD = cast<LoadSDNode>(N);
13820     Chain = LD->getChain();
13821     Base = LD->getBasePtr();
13822     MMO = LD->getMemOperand();
13823     // If the MMO suggests this isn't a load of a full vector, leave
13824     // things alone.  For a built-in, we have to make the change for
13825     // correctness, so if there is a size problem that will be a bug.
13826     if (MMO->getSize() < 16)
13827       return SDValue();
13828     break;
13829   }
13830   case ISD::INTRINSIC_W_CHAIN: {
13831     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13832     Chain = Intrin->getChain();
13833     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13834     // us what we want. Get operand 2 instead.
13835     Base = Intrin->getOperand(2);
13836     MMO = Intrin->getMemOperand();
13837     break;
13838   }
13839   }
13840 
13841   MVT VecTy = N->getValueType(0).getSimpleVT();
13842 
13843   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13844   // aligned and the type is a vector with elements up to 4 bytes
13845   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13846       VecTy.getScalarSizeInBits() <= 32) {
13847     return SDValue();
13848   }
13849 
13850   SDValue LoadOps[] = { Chain, Base };
13851   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13852                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13853                                          LoadOps, MVT::v2f64, MMO);
13854 
13855   DCI.AddToWorklist(Load.getNode());
13856   Chain = Load.getValue(1);
13857   SDValue Swap = DAG.getNode(
13858       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13859   DCI.AddToWorklist(Swap.getNode());
13860 
13861   // Add a bitcast if the resulting load type doesn't match v2f64.
13862   if (VecTy != MVT::v2f64) {
13863     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13864     DCI.AddToWorklist(N.getNode());
13865     // Package {bitcast value, swap's chain} to match Load's shape.
13866     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13867                        N, Swap.getValue(1));
13868   }
13869 
13870   return Swap;
13871 }
13872 
13873 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13874 // builtins) into stores with swaps.
13875 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13876                                                DAGCombinerInfo &DCI) const {
13877   SelectionDAG &DAG = DCI.DAG;
13878   SDLoc dl(N);
13879   SDValue Chain;
13880   SDValue Base;
13881   unsigned SrcOpnd;
13882   MachineMemOperand *MMO;
13883 
13884   switch (N->getOpcode()) {
13885   default:
13886     llvm_unreachable("Unexpected opcode for little endian VSX store");
13887   case ISD::STORE: {
13888     StoreSDNode *ST = cast<StoreSDNode>(N);
13889     Chain = ST->getChain();
13890     Base = ST->getBasePtr();
13891     MMO = ST->getMemOperand();
13892     SrcOpnd = 1;
13893     // If the MMO suggests this isn't a store of a full vector, leave
13894     // things alone.  For a built-in, we have to make the change for
13895     // correctness, so if there is a size problem that will be a bug.
13896     if (MMO->getSize() < 16)
13897       return SDValue();
13898     break;
13899   }
13900   case ISD::INTRINSIC_VOID: {
13901     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13902     Chain = Intrin->getChain();
13903     // Intrin->getBasePtr() oddly does not get what we want.
13904     Base = Intrin->getOperand(3);
13905     MMO = Intrin->getMemOperand();
13906     SrcOpnd = 2;
13907     break;
13908   }
13909   }
13910 
13911   SDValue Src = N->getOperand(SrcOpnd);
13912   MVT VecTy = Src.getValueType().getSimpleVT();
13913 
13914   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13915   // aligned and the type is a vector with elements up to 4 bytes
13916   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13917       VecTy.getScalarSizeInBits() <= 32) {
13918     return SDValue();
13919   }
13920 
13921   // All stores are done as v2f64 and possible bit cast.
13922   if (VecTy != MVT::v2f64) {
13923     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13924     DCI.AddToWorklist(Src.getNode());
13925   }
13926 
13927   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13928                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13929   DCI.AddToWorklist(Swap.getNode());
13930   Chain = Swap.getValue(1);
13931   SDValue StoreOps[] = { Chain, Swap, Base };
13932   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13933                                           DAG.getVTList(MVT::Other),
13934                                           StoreOps, VecTy, MMO);
13935   DCI.AddToWorklist(Store.getNode());
13936   return Store;
13937 }
13938 
13939 // Handle DAG combine for STORE (FP_TO_INT F).
13940 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13941                                                DAGCombinerInfo &DCI) const {
13942 
13943   SelectionDAG &DAG = DCI.DAG;
13944   SDLoc dl(N);
13945   unsigned Opcode = N->getOperand(1).getOpcode();
13946 
13947   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13948          && "Not a FP_TO_INT Instruction!");
13949 
13950   SDValue Val = N->getOperand(1).getOperand(0);
13951   EVT Op1VT = N->getOperand(1).getValueType();
13952   EVT ResVT = Val.getValueType();
13953 
13954   // Floating point types smaller than 32 bits are not legal on Power.
13955   if (ResVT.getScalarSizeInBits() < 32)
13956     return SDValue();
13957 
13958   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13959   bool ValidTypeForStoreFltAsInt =
13960         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13961          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13962 
13963   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13964       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13965     return SDValue();
13966 
13967   // Extend f32 values to f64
13968   if (ResVT.getScalarSizeInBits() == 32) {
13969     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13970     DCI.AddToWorklist(Val.getNode());
13971   }
13972 
13973   // Set signed or unsigned conversion opcode.
13974   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13975                           PPCISD::FP_TO_SINT_IN_VSR :
13976                           PPCISD::FP_TO_UINT_IN_VSR;
13977 
13978   Val = DAG.getNode(ConvOpcode,
13979                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13980   DCI.AddToWorklist(Val.getNode());
13981 
13982   // Set number of bytes being converted.
13983   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13984   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13985                     DAG.getIntPtrConstant(ByteSize, dl, false),
13986                     DAG.getValueType(Op1VT) };
13987 
13988   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13989           DAG.getVTList(MVT::Other), Ops,
13990           cast<StoreSDNode>(N)->getMemoryVT(),
13991           cast<StoreSDNode>(N)->getMemOperand());
13992 
13993   DCI.AddToWorklist(Val.getNode());
13994   return Val;
13995 }
13996 
13997 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
13998   // Check that the source of the element keeps flipping
13999   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14000   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14001   for (int i = 1, e = Mask.size(); i < e; i++) {
14002     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14003       return false;
14004     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14005       return false;
14006     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14007   }
14008   return true;
14009 }
14010 
14011 static bool isSplatBV(SDValue Op) {
14012   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14013     return false;
14014   SDValue FirstOp;
14015 
14016   // Find first non-undef input.
14017   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14018     FirstOp = Op.getOperand(i);
14019     if (!FirstOp.isUndef())
14020       break;
14021   }
14022 
14023   // All inputs are undef or the same as the first non-undef input.
14024   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14025     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14026       return false;
14027   return true;
14028 }
14029 
14030 static SDValue isScalarToVec(SDValue Op) {
14031   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14032     return Op;
14033   if (Op.getOpcode() != ISD::BITCAST)
14034     return SDValue();
14035   Op = Op.getOperand(0);
14036   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14037     return Op;
14038   return SDValue();
14039 }
14040 
14041 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14042                                             int LHSMaxIdx, int RHSMinIdx,
14043                                             int RHSMaxIdx, int HalfVec) {
14044   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14045     int Idx = ShuffV[i];
14046     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14047       ShuffV[i] += HalfVec;
14048   }
14049   return;
14050 }
14051 
14052 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14053 // the original is:
14054 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14055 // In such a case, just change the shuffle mask to extract the element
14056 // from the permuted index.
14057 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14058   SDLoc dl(OrigSToV);
14059   EVT VT = OrigSToV.getValueType();
14060   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14061          "Expecting a SCALAR_TO_VECTOR here");
14062   SDValue Input = OrigSToV.getOperand(0);
14063 
14064   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14065     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14066     SDValue OrigVector = Input.getOperand(0);
14067 
14068     // Can't handle non-const element indices or different vector types
14069     // for the input to the extract and the output of the scalar_to_vector.
14070     if (Idx && VT == OrigVector.getValueType()) {
14071       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14072       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14073       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14074     }
14075   }
14076   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14077                      OrigSToV.getOperand(0));
14078 }
14079 
14080 // On little endian subtargets, combine shuffles such as:
14081 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14082 // into:
14083 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14084 // because the latter can be matched to a single instruction merge.
14085 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14086 // to put the value into element zero. Adjust the shuffle mask so that the
14087 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14088 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14089                                                 SelectionDAG &DAG) const {
14090   SDValue LHS = SVN->getOperand(0);
14091   SDValue RHS = SVN->getOperand(1);
14092   auto Mask = SVN->getMask();
14093   int NumElts = LHS.getValueType().getVectorNumElements();
14094   SDValue Res(SVN, 0);
14095   SDLoc dl(SVN);
14096 
14097   // None of these combines are useful on big endian systems since the ISA
14098   // already has a big endian bias.
14099   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14100     return Res;
14101 
14102   // If this is not a shuffle of a shuffle and the first element comes from
14103   // the second vector, canonicalize to the commuted form. This will make it
14104   // more likely to match one of the single instruction patterns.
14105   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14106       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14107     std::swap(LHS, RHS);
14108     Res = DAG.getCommutedVectorShuffle(*SVN);
14109     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14110   }
14111 
14112   // Adjust the shuffle mask if either input vector comes from a
14113   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14114   // form (to prevent the need for a swap).
14115   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14116   SDValue SToVLHS = isScalarToVec(LHS);
14117   SDValue SToVRHS = isScalarToVec(RHS);
14118   if (SToVLHS || SToVRHS) {
14119     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14120                             : SToVRHS.getValueType().getVectorNumElements();
14121     int NumEltsOut = ShuffV.size();
14122 
14123     // Initially assume that neither input is permuted. These will be adjusted
14124     // accordingly if either input is.
14125     int LHSMaxIdx = -1;
14126     int RHSMinIdx = -1;
14127     int RHSMaxIdx = -1;
14128     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14129 
14130     // Get the permuted scalar to vector nodes for the source(s) that come from
14131     // ISD::SCALAR_TO_VECTOR.
14132     if (SToVLHS) {
14133       // Set up the values for the shuffle vector fixup.
14134       LHSMaxIdx = NumEltsOut / NumEltsIn;
14135       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14136       if (SToVLHS.getValueType() != LHS.getValueType())
14137         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14138       LHS = SToVLHS;
14139     }
14140     if (SToVRHS) {
14141       RHSMinIdx = NumEltsOut;
14142       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14143       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14144       if (SToVRHS.getValueType() != RHS.getValueType())
14145         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14146       RHS = SToVRHS;
14147     }
14148 
14149     // Fix up the shuffle mask to reflect where the desired element actually is.
14150     // The minimum and maximum indices that correspond to element zero for both
14151     // the LHS and RHS are computed and will control which shuffle mask entries
14152     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14153     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14154     // HalfVec to refer to the corresponding element in the permuted vector.
14155     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14156                                     HalfVec);
14157     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14158 
14159     // We may have simplified away the shuffle. We won't be able to do anything
14160     // further with it here.
14161     if (!isa<ShuffleVectorSDNode>(Res))
14162       return Res;
14163     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14164   }
14165 
14166   // The common case after we commuted the shuffle is that the RHS is a splat
14167   // and we have elements coming in from the splat at indices that are not
14168   // conducive to using a merge.
14169   // Example:
14170   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14171   if (!isSplatBV(RHS))
14172     return Res;
14173 
14174   // We are looking for a mask such that all even elements are from
14175   // one vector and all odd elements from the other.
14176   if (!isAlternatingShuffMask(Mask, NumElts))
14177     return Res;
14178 
14179   // Adjust the mask so we are pulling in the same index from the splat
14180   // as the index from the interesting vector in consecutive elements.
14181   // Example (even elements from first vector):
14182   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14183   if (Mask[0] < NumElts)
14184     for (int i = 1, e = Mask.size(); i < e; i += 2)
14185       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14186   // Example (odd elements from first vector):
14187   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14188   else
14189     for (int i = 0, e = Mask.size(); i < e; i += 2)
14190       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14191 
14192   // If the RHS has undefs, we need to remove them since we may have created
14193   // a shuffle that adds those instead of the splat value.
14194   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14195   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14196 
14197   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14198   return Res;
14199 }
14200 
14201 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14202                                                 LSBaseSDNode *LSBase,
14203                                                 DAGCombinerInfo &DCI) const {
14204   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14205         "Not a reverse memop pattern!");
14206 
14207   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14208     auto Mask = SVN->getMask();
14209     int i = 0;
14210     auto I = Mask.rbegin();
14211     auto E = Mask.rend();
14212 
14213     for (; I != E; ++I) {
14214       if (*I != i)
14215         return false;
14216       i++;
14217     }
14218     return true;
14219   };
14220 
14221   SelectionDAG &DAG = DCI.DAG;
14222   EVT VT = SVN->getValueType(0);
14223 
14224   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14225     return SDValue();
14226 
14227   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14228   // See comment in PPCVSXSwapRemoval.cpp.
14229   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14230   if (!Subtarget.hasP9Vector())
14231     return SDValue();
14232 
14233   if(!IsElementReverse(SVN))
14234     return SDValue();
14235 
14236   if (LSBase->getOpcode() == ISD::LOAD) {
14237     SDLoc dl(SVN);
14238     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14239     return DAG.getMemIntrinsicNode(
14240         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14241         LSBase->getMemoryVT(), LSBase->getMemOperand());
14242   }
14243 
14244   if (LSBase->getOpcode() == ISD::STORE) {
14245     SDLoc dl(LSBase);
14246     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14247                           LSBase->getBasePtr()};
14248     return DAG.getMemIntrinsicNode(
14249         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14250         LSBase->getMemoryVT(), LSBase->getMemOperand());
14251   }
14252 
14253   llvm_unreachable("Expected a load or store node here");
14254 }
14255 
14256 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14257                                              DAGCombinerInfo &DCI) const {
14258   SelectionDAG &DAG = DCI.DAG;
14259   SDLoc dl(N);
14260   switch (N->getOpcode()) {
14261   default: break;
14262   case ISD::ADD:
14263     return combineADD(N, DCI);
14264   case ISD::SHL:
14265     return combineSHL(N, DCI);
14266   case ISD::SRA:
14267     return combineSRA(N, DCI);
14268   case ISD::SRL:
14269     return combineSRL(N, DCI);
14270   case ISD::MUL:
14271     return combineMUL(N, DCI);
14272   case ISD::FMA:
14273   case PPCISD::FNMSUB:
14274     return combineFMALike(N, DCI);
14275   case PPCISD::SHL:
14276     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14277         return N->getOperand(0);
14278     break;
14279   case PPCISD::SRL:
14280     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14281         return N->getOperand(0);
14282     break;
14283   case PPCISD::SRA:
14284     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14285       if (C->isNullValue() ||   //  0 >>s V -> 0.
14286           C->isAllOnesValue())    // -1 >>s V -> -1.
14287         return N->getOperand(0);
14288     }
14289     break;
14290   case ISD::SIGN_EXTEND:
14291   case ISD::ZERO_EXTEND:
14292   case ISD::ANY_EXTEND:
14293     return DAGCombineExtBoolTrunc(N, DCI);
14294   case ISD::TRUNCATE:
14295     return combineTRUNCATE(N, DCI);
14296   case ISD::SETCC:
14297     if (SDValue CSCC = combineSetCC(N, DCI))
14298       return CSCC;
14299     LLVM_FALLTHROUGH;
14300   case ISD::SELECT_CC:
14301     return DAGCombineTruncBoolExt(N, DCI);
14302   case ISD::SINT_TO_FP:
14303   case ISD::UINT_TO_FP:
14304     return combineFPToIntToFP(N, DCI);
14305   case ISD::VECTOR_SHUFFLE:
14306     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14307       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14308       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14309     }
14310     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14311   case ISD::STORE: {
14312 
14313     EVT Op1VT = N->getOperand(1).getValueType();
14314     unsigned Opcode = N->getOperand(1).getOpcode();
14315 
14316     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14317       SDValue Val= combineStoreFPToInt(N, DCI);
14318       if (Val)
14319         return Val;
14320     }
14321 
14322     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14323       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14324       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14325       if (Val)
14326         return Val;
14327     }
14328 
14329     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14330     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14331         N->getOperand(1).getNode()->hasOneUse() &&
14332         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14333          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14334 
14335       // STBRX can only handle simple types and it makes no sense to store less
14336       // two bytes in byte-reversed order.
14337       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14338       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14339         break;
14340 
14341       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14342       // Do an any-extend to 32-bits if this is a half-word input.
14343       if (BSwapOp.getValueType() == MVT::i16)
14344         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14345 
14346       // If the type of BSWAP operand is wider than stored memory width
14347       // it need to be shifted to the right side before STBRX.
14348       if (Op1VT.bitsGT(mVT)) {
14349         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14350         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14351                               DAG.getConstant(Shift, dl, MVT::i32));
14352         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14353         if (Op1VT == MVT::i64)
14354           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14355       }
14356 
14357       SDValue Ops[] = {
14358         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14359       };
14360       return
14361         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14362                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14363                                 cast<StoreSDNode>(N)->getMemOperand());
14364     }
14365 
14366     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14367     // So it can increase the chance of CSE constant construction.
14368     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14369         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14370       // Need to sign-extended to 64-bits to handle negative values.
14371       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14372       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14373                                     MemVT.getSizeInBits());
14374       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14375 
14376       // DAG.getTruncStore() can't be used here because it doesn't accept
14377       // the general (base + offset) addressing mode.
14378       // So we use UpdateNodeOperands and setTruncatingStore instead.
14379       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14380                              N->getOperand(3));
14381       cast<StoreSDNode>(N)->setTruncatingStore(true);
14382       return SDValue(N, 0);
14383     }
14384 
14385     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14386     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14387     if (Op1VT.isSimple()) {
14388       MVT StoreVT = Op1VT.getSimpleVT();
14389       if (Subtarget.needsSwapsForVSXMemOps() &&
14390           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14391            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14392         return expandVSXStoreForLE(N, DCI);
14393     }
14394     break;
14395   }
14396   case ISD::LOAD: {
14397     LoadSDNode *LD = cast<LoadSDNode>(N);
14398     EVT VT = LD->getValueType(0);
14399 
14400     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14401     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14402     if (VT.isSimple()) {
14403       MVT LoadVT = VT.getSimpleVT();
14404       if (Subtarget.needsSwapsForVSXMemOps() &&
14405           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14406            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14407         return expandVSXLoadForLE(N, DCI);
14408     }
14409 
14410     // We sometimes end up with a 64-bit integer load, from which we extract
14411     // two single-precision floating-point numbers. This happens with
14412     // std::complex<float>, and other similar structures, because of the way we
14413     // canonicalize structure copies. However, if we lack direct moves,
14414     // then the final bitcasts from the extracted integer values to the
14415     // floating-point numbers turn into store/load pairs. Even with direct moves,
14416     // just loading the two floating-point numbers is likely better.
14417     auto ReplaceTwoFloatLoad = [&]() {
14418       if (VT != MVT::i64)
14419         return false;
14420 
14421       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14422           LD->isVolatile())
14423         return false;
14424 
14425       //  We're looking for a sequence like this:
14426       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14427       //      t16: i64 = srl t13, Constant:i32<32>
14428       //    t17: i32 = truncate t16
14429       //  t18: f32 = bitcast t17
14430       //    t19: i32 = truncate t13
14431       //  t20: f32 = bitcast t19
14432 
14433       if (!LD->hasNUsesOfValue(2, 0))
14434         return false;
14435 
14436       auto UI = LD->use_begin();
14437       while (UI.getUse().getResNo() != 0) ++UI;
14438       SDNode *Trunc = *UI++;
14439       while (UI.getUse().getResNo() != 0) ++UI;
14440       SDNode *RightShift = *UI;
14441       if (Trunc->getOpcode() != ISD::TRUNCATE)
14442         std::swap(Trunc, RightShift);
14443 
14444       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14445           Trunc->getValueType(0) != MVT::i32 ||
14446           !Trunc->hasOneUse())
14447         return false;
14448       if (RightShift->getOpcode() != ISD::SRL ||
14449           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14450           RightShift->getConstantOperandVal(1) != 32 ||
14451           !RightShift->hasOneUse())
14452         return false;
14453 
14454       SDNode *Trunc2 = *RightShift->use_begin();
14455       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14456           Trunc2->getValueType(0) != MVT::i32 ||
14457           !Trunc2->hasOneUse())
14458         return false;
14459 
14460       SDNode *Bitcast = *Trunc->use_begin();
14461       SDNode *Bitcast2 = *Trunc2->use_begin();
14462 
14463       if (Bitcast->getOpcode() != ISD::BITCAST ||
14464           Bitcast->getValueType(0) != MVT::f32)
14465         return false;
14466       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14467           Bitcast2->getValueType(0) != MVT::f32)
14468         return false;
14469 
14470       if (Subtarget.isLittleEndian())
14471         std::swap(Bitcast, Bitcast2);
14472 
14473       // Bitcast has the second float (in memory-layout order) and Bitcast2
14474       // has the first one.
14475 
14476       SDValue BasePtr = LD->getBasePtr();
14477       if (LD->isIndexed()) {
14478         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14479                "Non-pre-inc AM on PPC?");
14480         BasePtr =
14481           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14482                       LD->getOffset());
14483       }
14484 
14485       auto MMOFlags =
14486           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14487       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14488                                       LD->getPointerInfo(), LD->getAlignment(),
14489                                       MMOFlags, LD->getAAInfo());
14490       SDValue AddPtr =
14491         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14492                     BasePtr, DAG.getIntPtrConstant(4, dl));
14493       SDValue FloatLoad2 = DAG.getLoad(
14494           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14495           LD->getPointerInfo().getWithOffset(4),
14496           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14497 
14498       if (LD->isIndexed()) {
14499         // Note that DAGCombine should re-form any pre-increment load(s) from
14500         // what is produced here if that makes sense.
14501         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14502       }
14503 
14504       DCI.CombineTo(Bitcast2, FloatLoad);
14505       DCI.CombineTo(Bitcast, FloatLoad2);
14506 
14507       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14508                                     SDValue(FloatLoad2.getNode(), 1));
14509       return true;
14510     };
14511 
14512     if (ReplaceTwoFloatLoad())
14513       return SDValue(N, 0);
14514 
14515     EVT MemVT = LD->getMemoryVT();
14516     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14517     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14518     if (LD->isUnindexed() && VT.isVector() &&
14519         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14520           // P8 and later hardware should just use LOAD.
14521           !Subtarget.hasP8Vector() &&
14522           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14523            VT == MVT::v4f32))) &&
14524         LD->getAlign() < ABIAlignment) {
14525       // This is a type-legal unaligned Altivec load.
14526       SDValue Chain = LD->getChain();
14527       SDValue Ptr = LD->getBasePtr();
14528       bool isLittleEndian = Subtarget.isLittleEndian();
14529 
14530       // This implements the loading of unaligned vectors as described in
14531       // the venerable Apple Velocity Engine overview. Specifically:
14532       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14533       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14534       //
14535       // The general idea is to expand a sequence of one or more unaligned
14536       // loads into an alignment-based permutation-control instruction (lvsl
14537       // or lvsr), a series of regular vector loads (which always truncate
14538       // their input address to an aligned address), and a series of
14539       // permutations.  The results of these permutations are the requested
14540       // loaded values.  The trick is that the last "extra" load is not taken
14541       // from the address you might suspect (sizeof(vector) bytes after the
14542       // last requested load), but rather sizeof(vector) - 1 bytes after the
14543       // last requested vector. The point of this is to avoid a page fault if
14544       // the base address happened to be aligned. This works because if the
14545       // base address is aligned, then adding less than a full vector length
14546       // will cause the last vector in the sequence to be (re)loaded.
14547       // Otherwise, the next vector will be fetched as you might suspect was
14548       // necessary.
14549 
14550       // We might be able to reuse the permutation generation from
14551       // a different base address offset from this one by an aligned amount.
14552       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14553       // optimization later.
14554       Intrinsic::ID Intr, IntrLD, IntrPerm;
14555       MVT PermCntlTy, PermTy, LDTy;
14556       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14557                             : Intrinsic::ppc_altivec_lvsl;
14558       IntrLD = Intrinsic::ppc_altivec_lvx;
14559       IntrPerm = Intrinsic::ppc_altivec_vperm;
14560       PermCntlTy = MVT::v16i8;
14561       PermTy = MVT::v4i32;
14562       LDTy = MVT::v4i32;
14563 
14564       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14565 
14566       // Create the new MMO for the new base load. It is like the original MMO,
14567       // but represents an area in memory almost twice the vector size centered
14568       // on the original address. If the address is unaligned, we might start
14569       // reading up to (sizeof(vector)-1) bytes below the address of the
14570       // original unaligned load.
14571       MachineFunction &MF = DAG.getMachineFunction();
14572       MachineMemOperand *BaseMMO =
14573         MF.getMachineMemOperand(LD->getMemOperand(),
14574                                 -(long)MemVT.getStoreSize()+1,
14575                                 2*MemVT.getStoreSize()-1);
14576 
14577       // Create the new base load.
14578       SDValue LDXIntID =
14579           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14580       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14581       SDValue BaseLoad =
14582         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14583                                 DAG.getVTList(PermTy, MVT::Other),
14584                                 BaseLoadOps, LDTy, BaseMMO);
14585 
14586       // Note that the value of IncOffset (which is provided to the next
14587       // load's pointer info offset value, and thus used to calculate the
14588       // alignment), and the value of IncValue (which is actually used to
14589       // increment the pointer value) are different! This is because we
14590       // require the next load to appear to be aligned, even though it
14591       // is actually offset from the base pointer by a lesser amount.
14592       int IncOffset = VT.getSizeInBits() / 8;
14593       int IncValue = IncOffset;
14594 
14595       // Walk (both up and down) the chain looking for another load at the real
14596       // (aligned) offset (the alignment of the other load does not matter in
14597       // this case). If found, then do not use the offset reduction trick, as
14598       // that will prevent the loads from being later combined (as they would
14599       // otherwise be duplicates).
14600       if (!findConsecutiveLoad(LD, DAG))
14601         --IncValue;
14602 
14603       SDValue Increment =
14604           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14605       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14606 
14607       MachineMemOperand *ExtraMMO =
14608         MF.getMachineMemOperand(LD->getMemOperand(),
14609                                 1, 2*MemVT.getStoreSize()-1);
14610       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14611       SDValue ExtraLoad =
14612         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14613                                 DAG.getVTList(PermTy, MVT::Other),
14614                                 ExtraLoadOps, LDTy, ExtraMMO);
14615 
14616       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14617         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14618 
14619       // Because vperm has a big-endian bias, we must reverse the order
14620       // of the input vectors and complement the permute control vector
14621       // when generating little endian code.  We have already handled the
14622       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14623       // and ExtraLoad here.
14624       SDValue Perm;
14625       if (isLittleEndian)
14626         Perm = BuildIntrinsicOp(IntrPerm,
14627                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14628       else
14629         Perm = BuildIntrinsicOp(IntrPerm,
14630                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14631 
14632       if (VT != PermTy)
14633         Perm = Subtarget.hasAltivec()
14634                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14635                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14636                                  DAG.getTargetConstant(1, dl, MVT::i64));
14637                                // second argument is 1 because this rounding
14638                                // is always exact.
14639 
14640       // The output of the permutation is our loaded result, the TokenFactor is
14641       // our new chain.
14642       DCI.CombineTo(N, Perm, TF);
14643       return SDValue(N, 0);
14644     }
14645     }
14646     break;
14647     case ISD::INTRINSIC_WO_CHAIN: {
14648       bool isLittleEndian = Subtarget.isLittleEndian();
14649       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14650       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14651                                            : Intrinsic::ppc_altivec_lvsl);
14652       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14653         SDValue Add = N->getOperand(1);
14654 
14655         int Bits = 4 /* 16 byte alignment */;
14656 
14657         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14658                                   APInt::getAllOnesValue(Bits /* alignment */)
14659                                       .zext(Add.getScalarValueSizeInBits()))) {
14660           SDNode *BasePtr = Add->getOperand(0).getNode();
14661           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14662                                     UE = BasePtr->use_end();
14663                UI != UE; ++UI) {
14664             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14665                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14666                     IID) {
14667               // We've found another LVSL/LVSR, and this address is an aligned
14668               // multiple of that one. The results will be the same, so use the
14669               // one we've just found instead.
14670 
14671               return SDValue(*UI, 0);
14672             }
14673           }
14674         }
14675 
14676         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14677           SDNode *BasePtr = Add->getOperand(0).getNode();
14678           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14679                UE = BasePtr->use_end(); UI != UE; ++UI) {
14680             if (UI->getOpcode() == ISD::ADD &&
14681                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14682                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14683                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14684                 (1ULL << Bits) == 0) {
14685               SDNode *OtherAdd = *UI;
14686               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14687                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14688                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14689                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14690                   return SDValue(*VI, 0);
14691                 }
14692               }
14693             }
14694           }
14695         }
14696       }
14697 
14698       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14699       // Expose the vabsduw/h/b opportunity for down stream
14700       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14701           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14702            IID == Intrinsic::ppc_altivec_vmaxsh ||
14703            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14704         SDValue V1 = N->getOperand(1);
14705         SDValue V2 = N->getOperand(2);
14706         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14707              V1.getSimpleValueType() == MVT::v8i16 ||
14708              V1.getSimpleValueType() == MVT::v16i8) &&
14709             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14710           // (0-a, a)
14711           if (V1.getOpcode() == ISD::SUB &&
14712               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14713               V1.getOperand(1) == V2) {
14714             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14715           }
14716           // (a, 0-a)
14717           if (V2.getOpcode() == ISD::SUB &&
14718               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14719               V2.getOperand(1) == V1) {
14720             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14721           }
14722           // (x-y, y-x)
14723           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14724               V1.getOperand(0) == V2.getOperand(1) &&
14725               V1.getOperand(1) == V2.getOperand(0)) {
14726             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14727           }
14728         }
14729       }
14730     }
14731 
14732     break;
14733   case ISD::INTRINSIC_W_CHAIN:
14734     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14735     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14736     if (Subtarget.needsSwapsForVSXMemOps()) {
14737       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14738       default:
14739         break;
14740       case Intrinsic::ppc_vsx_lxvw4x:
14741       case Intrinsic::ppc_vsx_lxvd2x:
14742         return expandVSXLoadForLE(N, DCI);
14743       }
14744     }
14745     break;
14746   case ISD::INTRINSIC_VOID:
14747     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14748     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14749     if (Subtarget.needsSwapsForVSXMemOps()) {
14750       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14751       default:
14752         break;
14753       case Intrinsic::ppc_vsx_stxvw4x:
14754       case Intrinsic::ppc_vsx_stxvd2x:
14755         return expandVSXStoreForLE(N, DCI);
14756       }
14757     }
14758     break;
14759   case ISD::BSWAP:
14760     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14761     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14762         N->getOperand(0).hasOneUse() &&
14763         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14764          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14765           N->getValueType(0) == MVT::i64))) {
14766       SDValue Load = N->getOperand(0);
14767       LoadSDNode *LD = cast<LoadSDNode>(Load);
14768       // Create the byte-swapping load.
14769       SDValue Ops[] = {
14770         LD->getChain(),    // Chain
14771         LD->getBasePtr(),  // Ptr
14772         DAG.getValueType(N->getValueType(0)) // VT
14773       };
14774       SDValue BSLoad =
14775         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14776                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14777                                               MVT::i64 : MVT::i32, MVT::Other),
14778                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14779 
14780       // If this is an i16 load, insert the truncate.
14781       SDValue ResVal = BSLoad;
14782       if (N->getValueType(0) == MVT::i16)
14783         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14784 
14785       // First, combine the bswap away.  This makes the value produced by the
14786       // load dead.
14787       DCI.CombineTo(N, ResVal);
14788 
14789       // Next, combine the load away, we give it a bogus result value but a real
14790       // chain result.  The result value is dead because the bswap is dead.
14791       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14792 
14793       // Return N so it doesn't get rechecked!
14794       return SDValue(N, 0);
14795     }
14796     break;
14797   case PPCISD::VCMP:
14798     // If a VCMPo node already exists with exactly the same operands as this
14799     // node, use its result instead of this node (VCMPo computes both a CR6 and
14800     // a normal output).
14801     //
14802     if (!N->getOperand(0).hasOneUse() &&
14803         !N->getOperand(1).hasOneUse() &&
14804         !N->getOperand(2).hasOneUse()) {
14805 
14806       // Scan all of the users of the LHS, looking for VCMPo's that match.
14807       SDNode *VCMPoNode = nullptr;
14808 
14809       SDNode *LHSN = N->getOperand(0).getNode();
14810       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14811            UI != E; ++UI)
14812         if (UI->getOpcode() == PPCISD::VCMPo &&
14813             UI->getOperand(1) == N->getOperand(1) &&
14814             UI->getOperand(2) == N->getOperand(2) &&
14815             UI->getOperand(0) == N->getOperand(0)) {
14816           VCMPoNode = *UI;
14817           break;
14818         }
14819 
14820       // If there is no VCMPo node, or if the flag value has a single use, don't
14821       // transform this.
14822       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14823         break;
14824 
14825       // Look at the (necessarily single) use of the flag value.  If it has a
14826       // chain, this transformation is more complex.  Note that multiple things
14827       // could use the value result, which we should ignore.
14828       SDNode *FlagUser = nullptr;
14829       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14830            FlagUser == nullptr; ++UI) {
14831         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14832         SDNode *User = *UI;
14833         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14834           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14835             FlagUser = User;
14836             break;
14837           }
14838         }
14839       }
14840 
14841       // If the user is a MFOCRF instruction, we know this is safe.
14842       // Otherwise we give up for right now.
14843       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14844         return SDValue(VCMPoNode, 0);
14845     }
14846     break;
14847   case ISD::BRCOND: {
14848     SDValue Cond = N->getOperand(1);
14849     SDValue Target = N->getOperand(2);
14850 
14851     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14852         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14853           Intrinsic::loop_decrement) {
14854 
14855       // We now need to make the intrinsic dead (it cannot be instruction
14856       // selected).
14857       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14858       assert(Cond.getNode()->hasOneUse() &&
14859              "Counter decrement has more than one use");
14860 
14861       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14862                          N->getOperand(0), Target);
14863     }
14864   }
14865   break;
14866   case ISD::BR_CC: {
14867     // If this is a branch on an altivec predicate comparison, lower this so
14868     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14869     // lowering is done pre-legalize, because the legalizer lowers the predicate
14870     // compare down to code that is difficult to reassemble.
14871     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14872     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14873 
14874     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14875     // value. If so, pass-through the AND to get to the intrinsic.
14876     if (LHS.getOpcode() == ISD::AND &&
14877         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14878         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14879           Intrinsic::loop_decrement &&
14880         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14881         !isNullConstant(LHS.getOperand(1)))
14882       LHS = LHS.getOperand(0);
14883 
14884     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14885         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14886           Intrinsic::loop_decrement &&
14887         isa<ConstantSDNode>(RHS)) {
14888       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14889              "Counter decrement comparison is not EQ or NE");
14890 
14891       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14892       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14893                     (CC == ISD::SETNE && !Val);
14894 
14895       // We now need to make the intrinsic dead (it cannot be instruction
14896       // selected).
14897       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14898       assert(LHS.getNode()->hasOneUse() &&
14899              "Counter decrement has more than one use");
14900 
14901       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14902                          N->getOperand(0), N->getOperand(4));
14903     }
14904 
14905     int CompareOpc;
14906     bool isDot;
14907 
14908     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14909         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14910         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14911       assert(isDot && "Can't compare against a vector result!");
14912 
14913       // If this is a comparison against something other than 0/1, then we know
14914       // that the condition is never/always true.
14915       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14916       if (Val != 0 && Val != 1) {
14917         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14918           return N->getOperand(0);
14919         // Always !=, turn it into an unconditional branch.
14920         return DAG.getNode(ISD::BR, dl, MVT::Other,
14921                            N->getOperand(0), N->getOperand(4));
14922       }
14923 
14924       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14925 
14926       // Create the PPCISD altivec 'dot' comparison node.
14927       SDValue Ops[] = {
14928         LHS.getOperand(2),  // LHS of compare
14929         LHS.getOperand(3),  // RHS of compare
14930         DAG.getConstant(CompareOpc, dl, MVT::i32)
14931       };
14932       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14933       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14934 
14935       // Unpack the result based on how the target uses it.
14936       PPC::Predicate CompOpc;
14937       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14938       default:  // Can't happen, don't crash on invalid number though.
14939       case 0:   // Branch on the value of the EQ bit of CR6.
14940         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14941         break;
14942       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14943         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14944         break;
14945       case 2:   // Branch on the value of the LT bit of CR6.
14946         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14947         break;
14948       case 3:   // Branch on the inverted value of the LT bit of CR6.
14949         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14950         break;
14951       }
14952 
14953       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14954                          DAG.getConstant(CompOpc, dl, MVT::i32),
14955                          DAG.getRegister(PPC::CR6, MVT::i32),
14956                          N->getOperand(4), CompNode.getValue(1));
14957     }
14958     break;
14959   }
14960   case ISD::BUILD_VECTOR:
14961     return DAGCombineBuildVector(N, DCI);
14962   case ISD::ABS:
14963     return combineABS(N, DCI);
14964   case ISD::VSELECT:
14965     return combineVSelect(N, DCI);
14966   }
14967 
14968   return SDValue();
14969 }
14970 
14971 SDValue
14972 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14973                                  SelectionDAG &DAG,
14974                                  SmallVectorImpl<SDNode *> &Created) const {
14975   // fold (sdiv X, pow2)
14976   EVT VT = N->getValueType(0);
14977   if (VT == MVT::i64 && !Subtarget.isPPC64())
14978     return SDValue();
14979   if ((VT != MVT::i32 && VT != MVT::i64) ||
14980       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14981     return SDValue();
14982 
14983   SDLoc DL(N);
14984   SDValue N0 = N->getOperand(0);
14985 
14986   bool IsNegPow2 = (-Divisor).isPowerOf2();
14987   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14988   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14989 
14990   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14991   Created.push_back(Op.getNode());
14992 
14993   if (IsNegPow2) {
14994     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14995     Created.push_back(Op.getNode());
14996   }
14997 
14998   return Op;
14999 }
15000 
15001 //===----------------------------------------------------------------------===//
15002 // Inline Assembly Support
15003 //===----------------------------------------------------------------------===//
15004 
15005 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15006                                                       KnownBits &Known,
15007                                                       const APInt &DemandedElts,
15008                                                       const SelectionDAG &DAG,
15009                                                       unsigned Depth) const {
15010   Known.resetAll();
15011   switch (Op.getOpcode()) {
15012   default: break;
15013   case PPCISD::LBRX: {
15014     // lhbrx is known to have the top bits cleared out.
15015     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15016       Known.Zero = 0xFFFF0000;
15017     break;
15018   }
15019   case ISD::INTRINSIC_WO_CHAIN: {
15020     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15021     default: break;
15022     case Intrinsic::ppc_altivec_vcmpbfp_p:
15023     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15024     case Intrinsic::ppc_altivec_vcmpequb_p:
15025     case Intrinsic::ppc_altivec_vcmpequh_p:
15026     case Intrinsic::ppc_altivec_vcmpequw_p:
15027     case Intrinsic::ppc_altivec_vcmpequd_p:
15028     case Intrinsic::ppc_altivec_vcmpgefp_p:
15029     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15030     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15031     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15032     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15033     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15034     case Intrinsic::ppc_altivec_vcmpgtub_p:
15035     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15036     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15037     case Intrinsic::ppc_altivec_vcmpgtud_p:
15038       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15039       break;
15040     }
15041   }
15042   }
15043 }
15044 
15045 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15046   switch (Subtarget.getCPUDirective()) {
15047   default: break;
15048   case PPC::DIR_970:
15049   case PPC::DIR_PWR4:
15050   case PPC::DIR_PWR5:
15051   case PPC::DIR_PWR5X:
15052   case PPC::DIR_PWR6:
15053   case PPC::DIR_PWR6X:
15054   case PPC::DIR_PWR7:
15055   case PPC::DIR_PWR8:
15056   case PPC::DIR_PWR9:
15057   case PPC::DIR_PWR10:
15058   case PPC::DIR_PWR_FUTURE: {
15059     if (!ML)
15060       break;
15061 
15062     if (!DisableInnermostLoopAlign32) {
15063       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15064       // so that we can decrease cache misses and branch-prediction misses.
15065       // Actual alignment of the loop will depend on the hotness check and other
15066       // logic in alignBlocks.
15067       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15068         return Align(32);
15069     }
15070 
15071     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15072 
15073     // For small loops (between 5 and 8 instructions), align to a 32-byte
15074     // boundary so that the entire loop fits in one instruction-cache line.
15075     uint64_t LoopSize = 0;
15076     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15077       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15078         LoopSize += TII->getInstSizeInBytes(*J);
15079         if (LoopSize > 32)
15080           break;
15081       }
15082 
15083     if (LoopSize > 16 && LoopSize <= 32)
15084       return Align(32);
15085 
15086     break;
15087   }
15088   }
15089 
15090   return TargetLowering::getPrefLoopAlignment(ML);
15091 }
15092 
15093 /// getConstraintType - Given a constraint, return the type of
15094 /// constraint it is for this target.
15095 PPCTargetLowering::ConstraintType
15096 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15097   if (Constraint.size() == 1) {
15098     switch (Constraint[0]) {
15099     default: break;
15100     case 'b':
15101     case 'r':
15102     case 'f':
15103     case 'd':
15104     case 'v':
15105     case 'y':
15106       return C_RegisterClass;
15107     case 'Z':
15108       // FIXME: While Z does indicate a memory constraint, it specifically
15109       // indicates an r+r address (used in conjunction with the 'y' modifier
15110       // in the replacement string). Currently, we're forcing the base
15111       // register to be r0 in the asm printer (which is interpreted as zero)
15112       // and forming the complete address in the second register. This is
15113       // suboptimal.
15114       return C_Memory;
15115     }
15116   } else if (Constraint == "wc") { // individual CR bits.
15117     return C_RegisterClass;
15118   } else if (Constraint == "wa" || Constraint == "wd" ||
15119              Constraint == "wf" || Constraint == "ws" ||
15120              Constraint == "wi" || Constraint == "ww") {
15121     return C_RegisterClass; // VSX registers.
15122   }
15123   return TargetLowering::getConstraintType(Constraint);
15124 }
15125 
15126 /// Examine constraint type and operand type and determine a weight value.
15127 /// This object must already have been set up with the operand type
15128 /// and the current alternative constraint selected.
15129 TargetLowering::ConstraintWeight
15130 PPCTargetLowering::getSingleConstraintMatchWeight(
15131     AsmOperandInfo &info, const char *constraint) const {
15132   ConstraintWeight weight = CW_Invalid;
15133   Value *CallOperandVal = info.CallOperandVal;
15134     // If we don't have a value, we can't do a match,
15135     // but allow it at the lowest weight.
15136   if (!CallOperandVal)
15137     return CW_Default;
15138   Type *type = CallOperandVal->getType();
15139 
15140   // Look at the constraint type.
15141   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15142     return CW_Register; // an individual CR bit.
15143   else if ((StringRef(constraint) == "wa" ||
15144             StringRef(constraint) == "wd" ||
15145             StringRef(constraint) == "wf") &&
15146            type->isVectorTy())
15147     return CW_Register;
15148   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15149     return CW_Register; // just hold 64-bit integers data.
15150   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15151     return CW_Register;
15152   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15153     return CW_Register;
15154 
15155   switch (*constraint) {
15156   default:
15157     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15158     break;
15159   case 'b':
15160     if (type->isIntegerTy())
15161       weight = CW_Register;
15162     break;
15163   case 'f':
15164     if (type->isFloatTy())
15165       weight = CW_Register;
15166     break;
15167   case 'd':
15168     if (type->isDoubleTy())
15169       weight = CW_Register;
15170     break;
15171   case 'v':
15172     if (type->isVectorTy())
15173       weight = CW_Register;
15174     break;
15175   case 'y':
15176     weight = CW_Register;
15177     break;
15178   case 'Z':
15179     weight = CW_Memory;
15180     break;
15181   }
15182   return weight;
15183 }
15184 
15185 std::pair<unsigned, const TargetRegisterClass *>
15186 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15187                                                 StringRef Constraint,
15188                                                 MVT VT) const {
15189   if (Constraint.size() == 1) {
15190     // GCC RS6000 Constraint Letters
15191     switch (Constraint[0]) {
15192     case 'b':   // R1-R31
15193       if (VT == MVT::i64 && Subtarget.isPPC64())
15194         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15195       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15196     case 'r':   // R0-R31
15197       if (VT == MVT::i64 && Subtarget.isPPC64())
15198         return std::make_pair(0U, &PPC::G8RCRegClass);
15199       return std::make_pair(0U, &PPC::GPRCRegClass);
15200     // 'd' and 'f' constraints are both defined to be "the floating point
15201     // registers", where one is for 32-bit and the other for 64-bit. We don't
15202     // really care overly much here so just give them all the same reg classes.
15203     case 'd':
15204     case 'f':
15205       if (Subtarget.hasSPE()) {
15206         if (VT == MVT::f32 || VT == MVT::i32)
15207           return std::make_pair(0U, &PPC::GPRCRegClass);
15208         if (VT == MVT::f64 || VT == MVT::i64)
15209           return std::make_pair(0U, &PPC::SPERCRegClass);
15210       } else {
15211         if (VT == MVT::f32 || VT == MVT::i32)
15212           return std::make_pair(0U, &PPC::F4RCRegClass);
15213         if (VT == MVT::f64 || VT == MVT::i64)
15214           return std::make_pair(0U, &PPC::F8RCRegClass);
15215       }
15216       break;
15217     case 'v':
15218       if (Subtarget.hasAltivec())
15219         return std::make_pair(0U, &PPC::VRRCRegClass);
15220       break;
15221     case 'y':   // crrc
15222       return std::make_pair(0U, &PPC::CRRCRegClass);
15223     }
15224   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15225     // An individual CR bit.
15226     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15227   } else if ((Constraint == "wa" || Constraint == "wd" ||
15228              Constraint == "wf" || Constraint == "wi") &&
15229              Subtarget.hasVSX()) {
15230     return std::make_pair(0U, &PPC::VSRCRegClass);
15231   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15232     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15233       return std::make_pair(0U, &PPC::VSSRCRegClass);
15234     else
15235       return std::make_pair(0U, &PPC::VSFRCRegClass);
15236   }
15237 
15238   // If we name a VSX register, we can't defer to the base class because it
15239   // will not recognize the correct register (their names will be VSL{0-31}
15240   // and V{0-31} so they won't match). So we match them here.
15241   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15242     int VSNum = atoi(Constraint.data() + 3);
15243     assert(VSNum >= 0 && VSNum <= 63 &&
15244            "Attempted to access a vsr out of range");
15245     if (VSNum < 32)
15246       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15247     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15248   }
15249   std::pair<unsigned, const TargetRegisterClass *> R =
15250       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15251 
15252   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15253   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15254   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15255   // register.
15256   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15257   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15258   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15259       PPC::GPRCRegClass.contains(R.first))
15260     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15261                             PPC::sub_32, &PPC::G8RCRegClass),
15262                           &PPC::G8RCRegClass);
15263 
15264   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15265   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15266     R.first = PPC::CR0;
15267     R.second = &PPC::CRRCRegClass;
15268   }
15269 
15270   return R;
15271 }
15272 
15273 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15274 /// vector.  If it is invalid, don't add anything to Ops.
15275 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15276                                                      std::string &Constraint,
15277                                                      std::vector<SDValue>&Ops,
15278                                                      SelectionDAG &DAG) const {
15279   SDValue Result;
15280 
15281   // Only support length 1 constraints.
15282   if (Constraint.length() > 1) return;
15283 
15284   char Letter = Constraint[0];
15285   switch (Letter) {
15286   default: break;
15287   case 'I':
15288   case 'J':
15289   case 'K':
15290   case 'L':
15291   case 'M':
15292   case 'N':
15293   case 'O':
15294   case 'P': {
15295     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15296     if (!CST) return; // Must be an immediate to match.
15297     SDLoc dl(Op);
15298     int64_t Value = CST->getSExtValue();
15299     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15300                          // numbers are printed as such.
15301     switch (Letter) {
15302     default: llvm_unreachable("Unknown constraint letter!");
15303     case 'I':  // "I" is a signed 16-bit constant.
15304       if (isInt<16>(Value))
15305         Result = DAG.getTargetConstant(Value, dl, TCVT);
15306       break;
15307     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15308       if (isShiftedUInt<16, 16>(Value))
15309         Result = DAG.getTargetConstant(Value, dl, TCVT);
15310       break;
15311     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15312       if (isShiftedInt<16, 16>(Value))
15313         Result = DAG.getTargetConstant(Value, dl, TCVT);
15314       break;
15315     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15316       if (isUInt<16>(Value))
15317         Result = DAG.getTargetConstant(Value, dl, TCVT);
15318       break;
15319     case 'M':  // "M" is a constant that is greater than 31.
15320       if (Value > 31)
15321         Result = DAG.getTargetConstant(Value, dl, TCVT);
15322       break;
15323     case 'N':  // "N" is a positive constant that is an exact power of two.
15324       if (Value > 0 && isPowerOf2_64(Value))
15325         Result = DAG.getTargetConstant(Value, dl, TCVT);
15326       break;
15327     case 'O':  // "O" is the constant zero.
15328       if (Value == 0)
15329         Result = DAG.getTargetConstant(Value, dl, TCVT);
15330       break;
15331     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15332       if (isInt<16>(-Value))
15333         Result = DAG.getTargetConstant(Value, dl, TCVT);
15334       break;
15335     }
15336     break;
15337   }
15338   }
15339 
15340   if (Result.getNode()) {
15341     Ops.push_back(Result);
15342     return;
15343   }
15344 
15345   // Handle standard constraint letters.
15346   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15347 }
15348 
15349 // isLegalAddressingMode - Return true if the addressing mode represented
15350 // by AM is legal for this target, for a load/store of the specified type.
15351 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15352                                               const AddrMode &AM, Type *Ty,
15353                                               unsigned AS,
15354                                               Instruction *I) const {
15355   // Vector type r+i form is supported since power9 as DQ form. We don't check
15356   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15357   // imm form is preferred and the offset can be adjusted to use imm form later
15358   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15359   // max offset to check legal addressing mode, we should be a little aggressive
15360   // to contain other offsets for that LSRUse.
15361   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15362     return false;
15363 
15364   // PPC allows a sign-extended 16-bit immediate field.
15365   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15366     return false;
15367 
15368   // No global is ever allowed as a base.
15369   if (AM.BaseGV)
15370     return false;
15371 
15372   // PPC only support r+r,
15373   switch (AM.Scale) {
15374   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15375     break;
15376   case 1:
15377     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15378       return false;
15379     // Otherwise we have r+r or r+i.
15380     break;
15381   case 2:
15382     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15383       return false;
15384     // Allow 2*r as r+r.
15385     break;
15386   default:
15387     // No other scales are supported.
15388     return false;
15389   }
15390 
15391   return true;
15392 }
15393 
15394 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15395                                            SelectionDAG &DAG) const {
15396   MachineFunction &MF = DAG.getMachineFunction();
15397   MachineFrameInfo &MFI = MF.getFrameInfo();
15398   MFI.setReturnAddressIsTaken(true);
15399 
15400   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15401     return SDValue();
15402 
15403   SDLoc dl(Op);
15404   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15405 
15406   // Make sure the function does not optimize away the store of the RA to
15407   // the stack.
15408   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15409   FuncInfo->setLRStoreRequired();
15410   bool isPPC64 = Subtarget.isPPC64();
15411   auto PtrVT = getPointerTy(MF.getDataLayout());
15412 
15413   if (Depth > 0) {
15414     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15415     SDValue Offset =
15416         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15417                         isPPC64 ? MVT::i64 : MVT::i32);
15418     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15419                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15420                        MachinePointerInfo());
15421   }
15422 
15423   // Just load the return address off the stack.
15424   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15425   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15426                      MachinePointerInfo());
15427 }
15428 
15429 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15430                                           SelectionDAG &DAG) const {
15431   SDLoc dl(Op);
15432   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15433 
15434   MachineFunction &MF = DAG.getMachineFunction();
15435   MachineFrameInfo &MFI = MF.getFrameInfo();
15436   MFI.setFrameAddressIsTaken(true);
15437 
15438   EVT PtrVT = getPointerTy(MF.getDataLayout());
15439   bool isPPC64 = PtrVT == MVT::i64;
15440 
15441   // Naked functions never have a frame pointer, and so we use r1. For all
15442   // other functions, this decision must be delayed until during PEI.
15443   unsigned FrameReg;
15444   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15445     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15446   else
15447     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15448 
15449   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15450                                          PtrVT);
15451   while (Depth--)
15452     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15453                             FrameAddr, MachinePointerInfo());
15454   return FrameAddr;
15455 }
15456 
15457 // FIXME? Maybe this could be a TableGen attribute on some registers and
15458 // this table could be generated automatically from RegInfo.
15459 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15460                                               const MachineFunction &MF) const {
15461   bool isPPC64 = Subtarget.isPPC64();
15462 
15463   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15464   if (!is64Bit && VT != LLT::scalar(32))
15465     report_fatal_error("Invalid register global variable type");
15466 
15467   Register Reg = StringSwitch<Register>(RegName)
15468                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15469                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15470                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15471                      .Default(Register());
15472 
15473   if (Reg)
15474     return Reg;
15475   report_fatal_error("Invalid register name global variable");
15476 }
15477 
15478 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15479   // 32-bit SVR4 ABI access everything as got-indirect.
15480   if (Subtarget.is32BitELFABI())
15481     return true;
15482 
15483   // AIX accesses everything indirectly through the TOC, which is similar to
15484   // the GOT.
15485   if (Subtarget.isAIXABI())
15486     return true;
15487 
15488   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15489   // If it is small or large code model, module locals are accessed
15490   // indirectly by loading their address from .toc/.got.
15491   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15492     return true;
15493 
15494   // JumpTable and BlockAddress are accessed as got-indirect.
15495   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15496     return true;
15497 
15498   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15499     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15500 
15501   return false;
15502 }
15503 
15504 bool
15505 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15506   // The PowerPC target isn't yet aware of offsets.
15507   return false;
15508 }
15509 
15510 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15511                                            const CallInst &I,
15512                                            MachineFunction &MF,
15513                                            unsigned Intrinsic) const {
15514   switch (Intrinsic) {
15515   case Intrinsic::ppc_altivec_lvx:
15516   case Intrinsic::ppc_altivec_lvxl:
15517   case Intrinsic::ppc_altivec_lvebx:
15518   case Intrinsic::ppc_altivec_lvehx:
15519   case Intrinsic::ppc_altivec_lvewx:
15520   case Intrinsic::ppc_vsx_lxvd2x:
15521   case Intrinsic::ppc_vsx_lxvw4x: {
15522     EVT VT;
15523     switch (Intrinsic) {
15524     case Intrinsic::ppc_altivec_lvebx:
15525       VT = MVT::i8;
15526       break;
15527     case Intrinsic::ppc_altivec_lvehx:
15528       VT = MVT::i16;
15529       break;
15530     case Intrinsic::ppc_altivec_lvewx:
15531       VT = MVT::i32;
15532       break;
15533     case Intrinsic::ppc_vsx_lxvd2x:
15534       VT = MVT::v2f64;
15535       break;
15536     default:
15537       VT = MVT::v4i32;
15538       break;
15539     }
15540 
15541     Info.opc = ISD::INTRINSIC_W_CHAIN;
15542     Info.memVT = VT;
15543     Info.ptrVal = I.getArgOperand(0);
15544     Info.offset = -VT.getStoreSize()+1;
15545     Info.size = 2*VT.getStoreSize()-1;
15546     Info.align = Align(1);
15547     Info.flags = MachineMemOperand::MOLoad;
15548     return true;
15549   }
15550   case Intrinsic::ppc_altivec_stvx:
15551   case Intrinsic::ppc_altivec_stvxl:
15552   case Intrinsic::ppc_altivec_stvebx:
15553   case Intrinsic::ppc_altivec_stvehx:
15554   case Intrinsic::ppc_altivec_stvewx:
15555   case Intrinsic::ppc_vsx_stxvd2x:
15556   case Intrinsic::ppc_vsx_stxvw4x: {
15557     EVT VT;
15558     switch (Intrinsic) {
15559     case Intrinsic::ppc_altivec_stvebx:
15560       VT = MVT::i8;
15561       break;
15562     case Intrinsic::ppc_altivec_stvehx:
15563       VT = MVT::i16;
15564       break;
15565     case Intrinsic::ppc_altivec_stvewx:
15566       VT = MVT::i32;
15567       break;
15568     case Intrinsic::ppc_vsx_stxvd2x:
15569       VT = MVT::v2f64;
15570       break;
15571     default:
15572       VT = MVT::v4i32;
15573       break;
15574     }
15575 
15576     Info.opc = ISD::INTRINSIC_VOID;
15577     Info.memVT = VT;
15578     Info.ptrVal = I.getArgOperand(1);
15579     Info.offset = -VT.getStoreSize()+1;
15580     Info.size = 2*VT.getStoreSize()-1;
15581     Info.align = Align(1);
15582     Info.flags = MachineMemOperand::MOStore;
15583     return true;
15584   }
15585   default:
15586     break;
15587   }
15588 
15589   return false;
15590 }
15591 
15592 /// It returns EVT::Other if the type should be determined using generic
15593 /// target-independent logic.
15594 EVT PPCTargetLowering::getOptimalMemOpType(
15595     const MemOp &Op, const AttributeList &FuncAttributes) const {
15596   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15597     // We should use Altivec/VSX loads and stores when available. For unaligned
15598     // addresses, unaligned VSX loads are only fast starting with the P8.
15599     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15600         (Op.isAligned(Align(16)) ||
15601          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15602       return MVT::v4i32;
15603   }
15604 
15605   if (Subtarget.isPPC64()) {
15606     return MVT::i64;
15607   }
15608 
15609   return MVT::i32;
15610 }
15611 
15612 /// Returns true if it is beneficial to convert a load of a constant
15613 /// to just the constant itself.
15614 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15615                                                           Type *Ty) const {
15616   assert(Ty->isIntegerTy());
15617 
15618   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15619   return !(BitSize == 0 || BitSize > 64);
15620 }
15621 
15622 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15623   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15624     return false;
15625   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15626   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15627   return NumBits1 == 64 && NumBits2 == 32;
15628 }
15629 
15630 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15631   if (!VT1.isInteger() || !VT2.isInteger())
15632     return false;
15633   unsigned NumBits1 = VT1.getSizeInBits();
15634   unsigned NumBits2 = VT2.getSizeInBits();
15635   return NumBits1 == 64 && NumBits2 == 32;
15636 }
15637 
15638 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15639   // Generally speaking, zexts are not free, but they are free when they can be
15640   // folded with other operations.
15641   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15642     EVT MemVT = LD->getMemoryVT();
15643     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15644          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15645         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15646          LD->getExtensionType() == ISD::ZEXTLOAD))
15647       return true;
15648   }
15649 
15650   // FIXME: Add other cases...
15651   //  - 32-bit shifts with a zext to i64
15652   //  - zext after ctlz, bswap, etc.
15653   //  - zext after and by a constant mask
15654 
15655   return TargetLowering::isZExtFree(Val, VT2);
15656 }
15657 
15658 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15659   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15660          "invalid fpext types");
15661   // Extending to float128 is not free.
15662   if (DestVT == MVT::f128)
15663     return false;
15664   return true;
15665 }
15666 
15667 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15668   return isInt<16>(Imm) || isUInt<16>(Imm);
15669 }
15670 
15671 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15672   return isInt<16>(Imm) || isUInt<16>(Imm);
15673 }
15674 
15675 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15676                                                        unsigned,
15677                                                        unsigned,
15678                                                        MachineMemOperand::Flags,
15679                                                        bool *Fast) const {
15680   if (DisablePPCUnaligned)
15681     return false;
15682 
15683   // PowerPC supports unaligned memory access for simple non-vector types.
15684   // Although accessing unaligned addresses is not as efficient as accessing
15685   // aligned addresses, it is generally more efficient than manual expansion,
15686   // and generally only traps for software emulation when crossing page
15687   // boundaries.
15688 
15689   if (!VT.isSimple())
15690     return false;
15691 
15692   if (VT.isFloatingPoint() && !VT.isVector() &&
15693       !Subtarget.allowsUnalignedFPAccess())
15694     return false;
15695 
15696   if (VT.getSimpleVT().isVector()) {
15697     if (Subtarget.hasVSX()) {
15698       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15699           VT != MVT::v4f32 && VT != MVT::v4i32)
15700         return false;
15701     } else {
15702       return false;
15703     }
15704   }
15705 
15706   if (VT == MVT::ppcf128)
15707     return false;
15708 
15709   if (Fast)
15710     *Fast = true;
15711 
15712   return true;
15713 }
15714 
15715 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15716                                                    EVT VT) const {
15717   return isFMAFasterThanFMulAndFAdd(
15718       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15719 }
15720 
15721 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15722                                                    Type *Ty) const {
15723   switch (Ty->getScalarType()->getTypeID()) {
15724   case Type::FloatTyID:
15725   case Type::DoubleTyID:
15726     return true;
15727   case Type::FP128TyID:
15728     return Subtarget.hasP9Vector();
15729   default:
15730     return false;
15731   }
15732 }
15733 
15734 // FIXME: add more patterns which are not profitable to hoist.
15735 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15736   if (!I->hasOneUse())
15737     return true;
15738 
15739   Instruction *User = I->user_back();
15740   assert(User && "A single use instruction with no uses.");
15741 
15742   switch (I->getOpcode()) {
15743   case Instruction::FMul: {
15744     // Don't break FMA, PowerPC prefers FMA.
15745     if (User->getOpcode() != Instruction::FSub &&
15746         User->getOpcode() != Instruction::FAdd)
15747       return true;
15748 
15749     const TargetOptions &Options = getTargetMachine().Options;
15750     const Function *F = I->getFunction();
15751     const DataLayout &DL = F->getParent()->getDataLayout();
15752     Type *Ty = User->getOperand(0)->getType();
15753 
15754     return !(
15755         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15756         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15757         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15758   }
15759   case Instruction::Load: {
15760     // Don't break "store (load float*)" pattern, this pattern will be combined
15761     // to "store (load int32)" in later InstCombine pass. See function
15762     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15763     // cycles than loading a 32 bit integer.
15764     LoadInst *LI = cast<LoadInst>(I);
15765     // For the loads that combineLoadToOperationType does nothing, like
15766     // ordered load, it should be profitable to hoist them.
15767     // For swifterror load, it can only be used for pointer to pointer type, so
15768     // later type check should get rid of this case.
15769     if (!LI->isUnordered())
15770       return true;
15771 
15772     if (User->getOpcode() != Instruction::Store)
15773       return true;
15774 
15775     if (I->getType()->getTypeID() != Type::FloatTyID)
15776       return true;
15777 
15778     return false;
15779   }
15780   default:
15781     return true;
15782   }
15783   return true;
15784 }
15785 
15786 const MCPhysReg *
15787 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15788   // LR is a callee-save register, but we must treat it as clobbered by any call
15789   // site. Hence we include LR in the scratch registers, which are in turn added
15790   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15791   // to CTR, which is used by any indirect call.
15792   static const MCPhysReg ScratchRegs[] = {
15793     PPC::X12, PPC::LR8, PPC::CTR8, 0
15794   };
15795 
15796   return ScratchRegs;
15797 }
15798 
15799 Register PPCTargetLowering::getExceptionPointerRegister(
15800     const Constant *PersonalityFn) const {
15801   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15802 }
15803 
15804 Register PPCTargetLowering::getExceptionSelectorRegister(
15805     const Constant *PersonalityFn) const {
15806   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15807 }
15808 
15809 bool
15810 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15811                      EVT VT , unsigned DefinedValues) const {
15812   if (VT == MVT::v2i64)
15813     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15814 
15815   if (Subtarget.hasVSX())
15816     return true;
15817 
15818   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15819 }
15820 
15821 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15822   if (DisableILPPref || Subtarget.enableMachineScheduler())
15823     return TargetLowering::getSchedulingPreference(N);
15824 
15825   return Sched::ILP;
15826 }
15827 
15828 // Create a fast isel object.
15829 FastISel *
15830 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15831                                   const TargetLibraryInfo *LibInfo) const {
15832   return PPC::createFastISel(FuncInfo, LibInfo);
15833 }
15834 
15835 // 'Inverted' means the FMA opcode after negating one multiplicand.
15836 // For example, (fma -a b c) = (fnmsub a b c)
15837 static unsigned invertFMAOpcode(unsigned Opc) {
15838   switch (Opc) {
15839   default:
15840     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15841   case ISD::FMA:
15842     return PPCISD::FNMSUB;
15843   case PPCISD::FNMSUB:
15844     return ISD::FMA;
15845   }
15846 }
15847 
15848 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15849                                                 bool LegalOps, bool OptForSize,
15850                                                 NegatibleCost &Cost,
15851                                                 unsigned Depth) const {
15852   if (Depth > SelectionDAG::MaxRecursionDepth)
15853     return SDValue();
15854 
15855   unsigned Opc = Op.getOpcode();
15856   EVT VT = Op.getValueType();
15857   SDNodeFlags Flags = Op.getNode()->getFlags();
15858 
15859   switch (Opc) {
15860   case PPCISD::FNMSUB:
15861     if (!Op.hasOneUse() || !isTypeLegal(VT))
15862       break;
15863 
15864     const TargetOptions &Options = getTargetMachine().Options;
15865     SDValue N0 = Op.getOperand(0);
15866     SDValue N1 = Op.getOperand(1);
15867     SDValue N2 = Op.getOperand(2);
15868     SDLoc Loc(Op);
15869 
15870     NegatibleCost N2Cost = NegatibleCost::Expensive;
15871     SDValue NegN2 =
15872         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15873 
15874     if (!NegN2)
15875       return SDValue();
15876 
15877     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15878     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15879     // These transformations may change sign of zeroes. For example,
15880     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15881     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15882       // Try and choose the cheaper one to negate.
15883       NegatibleCost N0Cost = NegatibleCost::Expensive;
15884       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15885                                            N0Cost, Depth + 1);
15886 
15887       NegatibleCost N1Cost = NegatibleCost::Expensive;
15888       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15889                                            N1Cost, Depth + 1);
15890 
15891       if (NegN0 && N0Cost <= N1Cost) {
15892         Cost = std::min(N0Cost, N2Cost);
15893         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15894       } else if (NegN1) {
15895         Cost = std::min(N1Cost, N2Cost);
15896         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15897       }
15898     }
15899 
15900     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15901     if (isOperationLegal(ISD::FMA, VT)) {
15902       Cost = N2Cost;
15903       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15904     }
15905 
15906     break;
15907   }
15908 
15909   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15910                                               Cost, Depth);
15911 }
15912 
15913 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15914 bool PPCTargetLowering::useLoadStackGuardNode() const {
15915   if (!Subtarget.isTargetLinux())
15916     return TargetLowering::useLoadStackGuardNode();
15917   return true;
15918 }
15919 
15920 // Override to disable global variable loading on Linux.
15921 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15922   if (!Subtarget.isTargetLinux())
15923     return TargetLowering::insertSSPDeclarations(M);
15924 }
15925 
15926 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15927                                      bool ForCodeSize) const {
15928   if (!VT.isSimple() || !Subtarget.hasVSX())
15929     return false;
15930 
15931   switch(VT.getSimpleVT().SimpleTy) {
15932   default:
15933     // For FP types that are currently not supported by PPC backend, return
15934     // false. Examples: f16, f80.
15935     return false;
15936   case MVT::f32:
15937   case MVT::f64:
15938     if (Subtarget.hasPrefixInstrs()) {
15939       // With prefixed instructions, we can materialize anything that can be
15940       // represented with a 32-bit immediate, not just positive zero.
15941       APFloat APFloatOfImm = Imm;
15942       return convertToNonDenormSingle(APFloatOfImm);
15943     }
15944     LLVM_FALLTHROUGH;
15945   case MVT::ppcf128:
15946     return Imm.isPosZero();
15947   }
15948 }
15949 
15950 // For vector shift operation op, fold
15951 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15952 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15953                                   SelectionDAG &DAG) {
15954   SDValue N0 = N->getOperand(0);
15955   SDValue N1 = N->getOperand(1);
15956   EVT VT = N0.getValueType();
15957   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15958   unsigned Opcode = N->getOpcode();
15959   unsigned TargetOpcode;
15960 
15961   switch (Opcode) {
15962   default:
15963     llvm_unreachable("Unexpected shift operation");
15964   case ISD::SHL:
15965     TargetOpcode = PPCISD::SHL;
15966     break;
15967   case ISD::SRL:
15968     TargetOpcode = PPCISD::SRL;
15969     break;
15970   case ISD::SRA:
15971     TargetOpcode = PPCISD::SRA;
15972     break;
15973   }
15974 
15975   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15976       N1->getOpcode() == ISD::AND)
15977     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15978       if (Mask->getZExtValue() == OpSizeInBits - 1)
15979         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15980 
15981   return SDValue();
15982 }
15983 
15984 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15985   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15986     return Value;
15987 
15988   SDValue N0 = N->getOperand(0);
15989   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15990   if (!Subtarget.isISA3_0() ||
15991       N0.getOpcode() != ISD::SIGN_EXTEND ||
15992       N0.getOperand(0).getValueType() != MVT::i32 ||
15993       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15994     return SDValue();
15995 
15996   // We can't save an operation here if the value is already extended, and
15997   // the existing shift is easier to combine.
15998   SDValue ExtsSrc = N0.getOperand(0);
15999   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16000       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16001     return SDValue();
16002 
16003   SDLoc DL(N0);
16004   SDValue ShiftBy = SDValue(CN1, 0);
16005   // We want the shift amount to be i32 on the extswli, but the shift could
16006   // have an i64.
16007   if (ShiftBy.getValueType() == MVT::i64)
16008     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16009 
16010   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16011                          ShiftBy);
16012 }
16013 
16014 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16015   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16016     return Value;
16017 
16018   return SDValue();
16019 }
16020 
16021 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16022   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16023     return Value;
16024 
16025   return SDValue();
16026 }
16027 
16028 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16029 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16030 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16031 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16032 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16033                                  const PPCSubtarget &Subtarget) {
16034   if (!Subtarget.isPPC64())
16035     return SDValue();
16036 
16037   SDValue LHS = N->getOperand(0);
16038   SDValue RHS = N->getOperand(1);
16039 
16040   auto isZextOfCompareWithConstant = [](SDValue Op) {
16041     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16042         Op.getValueType() != MVT::i64)
16043       return false;
16044 
16045     SDValue Cmp = Op.getOperand(0);
16046     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16047         Cmp.getOperand(0).getValueType() != MVT::i64)
16048       return false;
16049 
16050     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16051       int64_t NegConstant = 0 - Constant->getSExtValue();
16052       // Due to the limitations of the addi instruction,
16053       // -C is required to be [-32768, 32767].
16054       return isInt<16>(NegConstant);
16055     }
16056 
16057     return false;
16058   };
16059 
16060   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16061   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16062 
16063   // If there is a pattern, canonicalize a zext operand to the RHS.
16064   if (LHSHasPattern && !RHSHasPattern)
16065     std::swap(LHS, RHS);
16066   else if (!LHSHasPattern && !RHSHasPattern)
16067     return SDValue();
16068 
16069   SDLoc DL(N);
16070   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16071   SDValue Cmp = RHS.getOperand(0);
16072   SDValue Z = Cmp.getOperand(0);
16073   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16074 
16075   assert(Constant && "Constant Should not be a null pointer.");
16076   int64_t NegConstant = 0 - Constant->getSExtValue();
16077 
16078   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16079   default: break;
16080   case ISD::SETNE: {
16081     //                                 when C == 0
16082     //                             --> addze X, (addic Z, -1).carry
16083     //                            /
16084     // add X, (zext(setne Z, C))--
16085     //                            \    when -32768 <= -C <= 32767 && C != 0
16086     //                             --> addze X, (addic (addi Z, -C), -1).carry
16087     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16088                               DAG.getConstant(NegConstant, DL, MVT::i64));
16089     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16090     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16091                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16092     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16093                        SDValue(Addc.getNode(), 1));
16094     }
16095   case ISD::SETEQ: {
16096     //                                 when C == 0
16097     //                             --> addze X, (subfic Z, 0).carry
16098     //                            /
16099     // add X, (zext(sete  Z, C))--
16100     //                            \    when -32768 <= -C <= 32767 && C != 0
16101     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16102     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16103                               DAG.getConstant(NegConstant, DL, MVT::i64));
16104     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16105     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16106                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16107     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16108                        SDValue(Subc.getNode(), 1));
16109     }
16110   }
16111 
16112   return SDValue();
16113 }
16114 
16115 // Transform
16116 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16117 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16118 // In this case both C1 and C2 must be known constants.
16119 // C1+C2 must fit into a 34 bit signed integer.
16120 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16121                                           const PPCSubtarget &Subtarget) {
16122   if (!Subtarget.isUsingPCRelativeCalls())
16123     return SDValue();
16124 
16125   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16126   // If we find that node try to cast the Global Address and the Constant.
16127   SDValue LHS = N->getOperand(0);
16128   SDValue RHS = N->getOperand(1);
16129 
16130   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16131     std::swap(LHS, RHS);
16132 
16133   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16134     return SDValue();
16135 
16136   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16137   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16138   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16139 
16140   // Check that both casts succeeded.
16141   if (!GSDN || !ConstNode)
16142     return SDValue();
16143 
16144   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16145   SDLoc DL(GSDN);
16146 
16147   // The signed int offset needs to fit in 34 bits.
16148   if (!isInt<34>(NewOffset))
16149     return SDValue();
16150 
16151   // The new global address is a copy of the old global address except
16152   // that it has the updated Offset.
16153   SDValue GA =
16154       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16155                                  NewOffset, GSDN->getTargetFlags());
16156   SDValue MatPCRel =
16157       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16158   return MatPCRel;
16159 }
16160 
16161 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16162   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16163     return Value;
16164 
16165   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16166     return Value;
16167 
16168   return SDValue();
16169 }
16170 
16171 // Detect TRUNCATE operations on bitcasts of float128 values.
16172 // What we are looking for here is the situtation where we extract a subset
16173 // of bits from a 128 bit float.
16174 // This can be of two forms:
16175 // 1) BITCAST of f128 feeding TRUNCATE
16176 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16177 // The reason this is required is because we do not have a legal i128 type
16178 // and so we want to prevent having to store the f128 and then reload part
16179 // of it.
16180 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16181                                            DAGCombinerInfo &DCI) const {
16182   // If we are using CRBits then try that first.
16183   if (Subtarget.useCRBits()) {
16184     // Check if CRBits did anything and return that if it did.
16185     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16186       return CRTruncValue;
16187   }
16188 
16189   SDLoc dl(N);
16190   SDValue Op0 = N->getOperand(0);
16191 
16192   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16193   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16194     EVT VT = N->getValueType(0);
16195     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16196       return SDValue();
16197     SDValue Sub = Op0.getOperand(0);
16198     if (Sub.getOpcode() == ISD::SUB) {
16199       SDValue SubOp0 = Sub.getOperand(0);
16200       SDValue SubOp1 = Sub.getOperand(1);
16201       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16202           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16203         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16204                                SubOp1.getOperand(0),
16205                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16206       }
16207     }
16208   }
16209 
16210   // Looking for a truncate of i128 to i64.
16211   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16212     return SDValue();
16213 
16214   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16215 
16216   // SRL feeding TRUNCATE.
16217   if (Op0.getOpcode() == ISD::SRL) {
16218     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16219     // The right shift has to be by 64 bits.
16220     if (!ConstNode || ConstNode->getZExtValue() != 64)
16221       return SDValue();
16222 
16223     // Switch the element number to extract.
16224     EltToExtract = EltToExtract ? 0 : 1;
16225     // Update Op0 past the SRL.
16226     Op0 = Op0.getOperand(0);
16227   }
16228 
16229   // BITCAST feeding a TRUNCATE possibly via SRL.
16230   if (Op0.getOpcode() == ISD::BITCAST &&
16231       Op0.getValueType() == MVT::i128 &&
16232       Op0.getOperand(0).getValueType() == MVT::f128) {
16233     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16234     return DCI.DAG.getNode(
16235         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16236         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16237   }
16238   return SDValue();
16239 }
16240 
16241 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16242   SelectionDAG &DAG = DCI.DAG;
16243 
16244   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16245   if (!ConstOpOrElement)
16246     return SDValue();
16247 
16248   // An imul is usually smaller than the alternative sequence for legal type.
16249   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16250       isOperationLegal(ISD::MUL, N->getValueType(0)))
16251     return SDValue();
16252 
16253   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16254     switch (this->Subtarget.getCPUDirective()) {
16255     default:
16256       // TODO: enhance the condition for subtarget before pwr8
16257       return false;
16258     case PPC::DIR_PWR8:
16259       //  type        mul     add    shl
16260       // scalar        4       1      1
16261       // vector        7       2      2
16262       return true;
16263     case PPC::DIR_PWR9:
16264     case PPC::DIR_PWR10:
16265     case PPC::DIR_PWR_FUTURE:
16266       //  type        mul     add    shl
16267       // scalar        5       2      2
16268       // vector        7       2      2
16269 
16270       // The cycle RATIO of related operations are showed as a table above.
16271       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16272       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16273       // are 4, it is always profitable; but for 3 instrs patterns
16274       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16275       // So we should only do it for vector type.
16276       return IsAddOne && IsNeg ? VT.isVector() : true;
16277     }
16278   };
16279 
16280   EVT VT = N->getValueType(0);
16281   SDLoc DL(N);
16282 
16283   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16284   bool IsNeg = MulAmt.isNegative();
16285   APInt MulAmtAbs = MulAmt.abs();
16286 
16287   if ((MulAmtAbs - 1).isPowerOf2()) {
16288     // (mul x, 2^N + 1) => (add (shl x, N), x)
16289     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16290 
16291     if (!IsProfitable(IsNeg, true, VT))
16292       return SDValue();
16293 
16294     SDValue Op0 = N->getOperand(0);
16295     SDValue Op1 =
16296         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16297                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16298     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16299 
16300     if (!IsNeg)
16301       return Res;
16302 
16303     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16304   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16305     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16306     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16307 
16308     if (!IsProfitable(IsNeg, false, VT))
16309       return SDValue();
16310 
16311     SDValue Op0 = N->getOperand(0);
16312     SDValue Op1 =
16313         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16314                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16315 
16316     if (!IsNeg)
16317       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16318     else
16319       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16320 
16321   } else {
16322     return SDValue();
16323   }
16324 }
16325 
16326 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16327 // in combiner since we need to check SD flags and other subtarget features.
16328 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16329                                           DAGCombinerInfo &DCI) const {
16330   SDValue N0 = N->getOperand(0);
16331   SDValue N1 = N->getOperand(1);
16332   SDValue N2 = N->getOperand(2);
16333   SDNodeFlags Flags = N->getFlags();
16334   EVT VT = N->getValueType(0);
16335   SelectionDAG &DAG = DCI.DAG;
16336   const TargetOptions &Options = getTargetMachine().Options;
16337   unsigned Opc = N->getOpcode();
16338   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16339   bool LegalOps = !DCI.isBeforeLegalizeOps();
16340   SDLoc Loc(N);
16341 
16342   if (!isOperationLegal(ISD::FMA, VT))
16343     return SDValue();
16344 
16345   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16346   // since (fnmsub a b c)=-0 while c-ab=+0.
16347   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16348     return SDValue();
16349 
16350   // (fma (fneg a) b c) => (fnmsub a b c)
16351   // (fnmsub (fneg a) b c) => (fma a b c)
16352   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16353     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16354 
16355   // (fma a (fneg b) c) => (fnmsub a b c)
16356   // (fnmsub a (fneg b) c) => (fma a b c)
16357   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16358     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16359 
16360   return SDValue();
16361 }
16362 
16363 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16364   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16365   if (!Subtarget.is64BitELFABI())
16366     return false;
16367 
16368   // If not a tail call then no need to proceed.
16369   if (!CI->isTailCall())
16370     return false;
16371 
16372   // If sibling calls have been disabled and tail-calls aren't guaranteed
16373   // there is no reason to duplicate.
16374   auto &TM = getTargetMachine();
16375   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16376     return false;
16377 
16378   // Can't tail call a function called indirectly, or if it has variadic args.
16379   const Function *Callee = CI->getCalledFunction();
16380   if (!Callee || Callee->isVarArg())
16381     return false;
16382 
16383   // Make sure the callee and caller calling conventions are eligible for tco.
16384   const Function *Caller = CI->getParent()->getParent();
16385   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16386                                            CI->getCallingConv()))
16387       return false;
16388 
16389   // If the function is local then we have a good chance at tail-calling it
16390   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16391 }
16392 
16393 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16394   if (!Subtarget.hasVSX())
16395     return false;
16396   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16397     return true;
16398   return VT == MVT::f32 || VT == MVT::f64 ||
16399     VT == MVT::v4f32 || VT == MVT::v2f64;
16400 }
16401 
16402 bool PPCTargetLowering::
16403 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16404   const Value *Mask = AndI.getOperand(1);
16405   // If the mask is suitable for andi. or andis. we should sink the and.
16406   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16407     // Can't handle constants wider than 64-bits.
16408     if (CI->getBitWidth() > 64)
16409       return false;
16410     int64_t ConstVal = CI->getZExtValue();
16411     return isUInt<16>(ConstVal) ||
16412       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16413   }
16414 
16415   // For non-constant masks, we can always use the record-form and.
16416   return true;
16417 }
16418 
16419 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16420 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16421 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16422 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16423 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16424 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16425   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16426   assert(Subtarget.hasP9Altivec() &&
16427          "Only combine this when P9 altivec supported!");
16428   EVT VT = N->getValueType(0);
16429   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16430     return SDValue();
16431 
16432   SelectionDAG &DAG = DCI.DAG;
16433   SDLoc dl(N);
16434   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16435     // Even for signed integers, if it's known to be positive (as signed
16436     // integer) due to zero-extended inputs.
16437     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16438     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16439     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16440          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16441         (SubOpcd1 == ISD::ZERO_EXTEND ||
16442          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16443       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16444                          N->getOperand(0)->getOperand(0),
16445                          N->getOperand(0)->getOperand(1),
16446                          DAG.getTargetConstant(0, dl, MVT::i32));
16447     }
16448 
16449     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16450     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16451         N->getOperand(0).hasOneUse()) {
16452       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16453                          N->getOperand(0)->getOperand(0),
16454                          N->getOperand(0)->getOperand(1),
16455                          DAG.getTargetConstant(1, dl, MVT::i32));
16456     }
16457   }
16458 
16459   return SDValue();
16460 }
16461 
16462 // For type v4i32/v8ii16/v16i8, transform
16463 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16464 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16465 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16466 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16467 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16468                                           DAGCombinerInfo &DCI) const {
16469   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16470   assert(Subtarget.hasP9Altivec() &&
16471          "Only combine this when P9 altivec supported!");
16472 
16473   SelectionDAG &DAG = DCI.DAG;
16474   SDLoc dl(N);
16475   SDValue Cond = N->getOperand(0);
16476   SDValue TrueOpnd = N->getOperand(1);
16477   SDValue FalseOpnd = N->getOperand(2);
16478   EVT VT = N->getOperand(1).getValueType();
16479 
16480   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16481       FalseOpnd.getOpcode() != ISD::SUB)
16482     return SDValue();
16483 
16484   // ABSD only available for type v4i32/v8i16/v16i8
16485   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16486     return SDValue();
16487 
16488   // At least to save one more dependent computation
16489   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16490     return SDValue();
16491 
16492   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16493 
16494   // Can only handle unsigned comparison here
16495   switch (CC) {
16496   default:
16497     return SDValue();
16498   case ISD::SETUGT:
16499   case ISD::SETUGE:
16500     break;
16501   case ISD::SETULT:
16502   case ISD::SETULE:
16503     std::swap(TrueOpnd, FalseOpnd);
16504     break;
16505   }
16506 
16507   SDValue CmpOpnd1 = Cond.getOperand(0);
16508   SDValue CmpOpnd2 = Cond.getOperand(1);
16509 
16510   // SETCC CmpOpnd1 CmpOpnd2 cond
16511   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16512   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16513   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16514       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16515       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16516       FalseOpnd.getOperand(1) == CmpOpnd1) {
16517     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16518                        CmpOpnd1, CmpOpnd2,
16519                        DAG.getTargetConstant(0, dl, MVT::i32));
16520   }
16521 
16522   return SDValue();
16523 }
16524