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   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
266   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
267 
268   // We do not currently implement these libm ops for PowerPC.
269   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
270   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
271   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
272   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
273   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
274   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
275 
276   // PowerPC has no SREM/UREM instructions unless we are on P9
277   // On P9 we may use a hardware instruction to compute the remainder.
278   // When the result of both the remainder and the division is required it is
279   // more efficient to compute the remainder from the result of the division
280   // rather than use the remainder instruction. The instructions are legalized
281   // directly because the DivRemPairsPass performs the transformation at the IR
282   // level.
283   if (Subtarget.isISA3_0()) {
284     setOperationAction(ISD::SREM, MVT::i32, Legal);
285     setOperationAction(ISD::UREM, MVT::i32, Legal);
286     setOperationAction(ISD::SREM, MVT::i64, Legal);
287     setOperationAction(ISD::UREM, MVT::i64, Legal);
288   } else {
289     setOperationAction(ISD::SREM, MVT::i32, Expand);
290     setOperationAction(ISD::UREM, MVT::i32, Expand);
291     setOperationAction(ISD::SREM, MVT::i64, Expand);
292     setOperationAction(ISD::UREM, MVT::i64, Expand);
293   }
294 
295   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
296   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
297   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
298   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
299   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
300   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
301   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
302   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
303   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
304 
305   // Handle constrained floating-point operations of scalar.
306   // TODO: Handle SPE specific operation.
307   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
308   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
309   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
310   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
311   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
312   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
313 
314   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
315   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
316   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
317   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
318   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
319   if (Subtarget.hasVSX()) {
320     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
321     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
322   }
323 
324   if (Subtarget.hasFSQRT()) {
325     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
326     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
327   }
328 
329   if (Subtarget.hasFPRND()) {
330     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
331     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
332     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
333     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
334 
335     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
336     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
337     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
338     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
339   }
340 
341   // We don't support sin/cos/sqrt/fmod/pow
342   setOperationAction(ISD::FSIN , MVT::f64, Expand);
343   setOperationAction(ISD::FCOS , MVT::f64, Expand);
344   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
345   setOperationAction(ISD::FREM , MVT::f64, Expand);
346   setOperationAction(ISD::FPOW , MVT::f64, Expand);
347   setOperationAction(ISD::FSIN , MVT::f32, Expand);
348   setOperationAction(ISD::FCOS , MVT::f32, Expand);
349   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
350   setOperationAction(ISD::FREM , MVT::f32, Expand);
351   setOperationAction(ISD::FPOW , MVT::f32, Expand);
352   if (Subtarget.hasSPE()) {
353     setOperationAction(ISD::FMA  , MVT::f64, Expand);
354     setOperationAction(ISD::FMA  , MVT::f32, Expand);
355   } else {
356     setOperationAction(ISD::FMA  , MVT::f64, Legal);
357     setOperationAction(ISD::FMA  , MVT::f32, Legal);
358   }
359 
360   if (Subtarget.hasSPE())
361     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
362 
363   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
364 
365   // If we're enabling GP optimizations, use hardware square root
366   if (!Subtarget.hasFSQRT() &&
367       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
368         Subtarget.hasFRE()))
369     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
370 
371   if (!Subtarget.hasFSQRT() &&
372       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
373         Subtarget.hasFRES()))
374     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
375 
376   if (Subtarget.hasFCPSGN()) {
377     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
378     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
379   } else {
380     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
381     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
382   }
383 
384   if (Subtarget.hasFPRND()) {
385     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
386     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
387     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
388     setOperationAction(ISD::FROUND, MVT::f64, Legal);
389 
390     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
391     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
392     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
393     setOperationAction(ISD::FROUND, MVT::f32, Legal);
394   }
395 
396   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
397   // to speed up scalar BSWAP64.
398   // CTPOP or CTTZ were introduced in P8/P9 respectively
399   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
400   if (Subtarget.hasP9Vector())
401     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
402   else
403     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
404   if (Subtarget.isISA3_0()) {
405     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
406     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
407   } else {
408     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
409     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
410   }
411 
412   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
413     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
414     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
415   } else {
416     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
417     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
418   }
419 
420   // PowerPC does not have ROTR
421   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
422   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
423 
424   if (!Subtarget.useCRBits()) {
425     // PowerPC does not have Select
426     setOperationAction(ISD::SELECT, MVT::i32, Expand);
427     setOperationAction(ISD::SELECT, MVT::i64, Expand);
428     setOperationAction(ISD::SELECT, MVT::f32, Expand);
429     setOperationAction(ISD::SELECT, MVT::f64, Expand);
430   }
431 
432   // PowerPC wants to turn select_cc of FP into fsel when possible.
433   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
434   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
435 
436   // PowerPC wants to optimize integer setcc a bit
437   if (!Subtarget.useCRBits())
438     setOperationAction(ISD::SETCC, MVT::i32, Custom);
439 
440   if (Subtarget.hasFPU()) {
441     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
442     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
443     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
444 
445     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
446     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
447     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
448   }
449 
450   // PowerPC does not have BRCOND which requires SetCC
451   if (!Subtarget.useCRBits())
452     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
453 
454   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
455 
456   if (Subtarget.hasSPE()) {
457     // SPE has built-in conversions
458     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
459     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
460     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
461     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
462     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
463     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
464   } else {
465     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
466     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
467     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
468 
469     // PowerPC does not have [U|S]INT_TO_FP
470     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
471     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
472     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
473     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
474   }
475 
476   if (Subtarget.hasDirectMove() && isPPC64) {
477     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
478     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
479     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
480     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
481     if (TM.Options.UnsafeFPMath) {
482       setOperationAction(ISD::LRINT, MVT::f64, Legal);
483       setOperationAction(ISD::LRINT, MVT::f32, Legal);
484       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
485       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
486       setOperationAction(ISD::LROUND, MVT::f64, Legal);
487       setOperationAction(ISD::LROUND, MVT::f32, Legal);
488       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
489       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
490     }
491   } else {
492     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
493     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
494     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
495     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
496   }
497 
498   // We cannot sextinreg(i1).  Expand to shifts.
499   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
500 
501   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
502   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
503   // support continuation, user-level threading, and etc.. As a result, no
504   // other SjLj exception interfaces are implemented and please don't build
505   // your own exception handling based on them.
506   // LLVM/Clang supports zero-cost DWARF exception handling.
507   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
508   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
509 
510   // We want to legalize GlobalAddress and ConstantPool nodes into the
511   // appropriate instructions to materialize the address.
512   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
513   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
514   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
515   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
516   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
517   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
518   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
519   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
520   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
521   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
522 
523   // TRAP is legal.
524   setOperationAction(ISD::TRAP, MVT::Other, Legal);
525 
526   // TRAMPOLINE is custom lowered.
527   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
528   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
529 
530   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
531   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
532 
533   if (Subtarget.is64BitELFABI()) {
534     // VAARG always uses double-word chunks, so promote anything smaller.
535     setOperationAction(ISD::VAARG, MVT::i1, Promote);
536     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
537     setOperationAction(ISD::VAARG, MVT::i8, Promote);
538     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
539     setOperationAction(ISD::VAARG, MVT::i16, Promote);
540     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
541     setOperationAction(ISD::VAARG, MVT::i32, Promote);
542     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
543     setOperationAction(ISD::VAARG, MVT::Other, Expand);
544   } else if (Subtarget.is32BitELFABI()) {
545     // VAARG is custom lowered with the 32-bit SVR4 ABI.
546     setOperationAction(ISD::VAARG, MVT::Other, Custom);
547     setOperationAction(ISD::VAARG, MVT::i64, Custom);
548   } else
549     setOperationAction(ISD::VAARG, MVT::Other, Expand);
550 
551   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
552   if (Subtarget.is32BitELFABI())
553     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
554   else
555     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
556 
557   // Use the default implementation.
558   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
559   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
560   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
561   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
562   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
563   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
564   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
565   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
566   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
567 
568   // We want to custom lower some of our intrinsics.
569   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
570 
571   // To handle counter-based loop conditions.
572   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
573 
574   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
575   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
576   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
577   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
578 
579   // Comparisons that require checking two conditions.
580   if (Subtarget.hasSPE()) {
581     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
582     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
583     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
584     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
585   }
586   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
587   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
588   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
589   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
590   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
591   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
592   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
593   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
594   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
595   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
596   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
597   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
598 
599   if (Subtarget.has64BitSupport()) {
600     // They also have instructions for converting between i64 and fp.
601     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
602     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
603     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
604     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
605     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
606     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
607     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
608     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
609     // This is just the low 32 bits of a (signed) fp->i64 conversion.
610     // We cannot do this with Promote because i64 is not a legal type.
611     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
612     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
613 
614     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
615       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
616       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
617     }
618   } else {
619     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
620     if (Subtarget.hasSPE()) {
621       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
622       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
623     } else {
624       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
625       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
626     }
627   }
628 
629   // With the instructions enabled under FPCVT, we can do everything.
630   if (Subtarget.hasFPCVT()) {
631     if (Subtarget.has64BitSupport()) {
632       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
633       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
634       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
635       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
636       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
637       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
638       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
639       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
640     }
641 
642     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
643     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
645     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
646     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
647     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
648     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
649     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
650   }
651 
652   if (Subtarget.use64BitRegs()) {
653     // 64-bit PowerPC implementations can support i64 types directly
654     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
655     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
656     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
657     // 64-bit PowerPC wants to expand i128 shifts itself.
658     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
659     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
660     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
661   } else {
662     // 32-bit PowerPC wants to expand i64 shifts itself.
663     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
664     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
665     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
666   }
667 
668   // PowerPC has better expansions for funnel shifts than the generic
669   // TargetLowering::expandFunnelShift.
670   if (Subtarget.has64BitSupport()) {
671     setOperationAction(ISD::FSHL, MVT::i64, Custom);
672     setOperationAction(ISD::FSHR, MVT::i64, Custom);
673   }
674   setOperationAction(ISD::FSHL, MVT::i32, Custom);
675   setOperationAction(ISD::FSHR, MVT::i32, Custom);
676 
677   if (Subtarget.hasVSX()) {
678     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
679     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
680     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
681     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
682   }
683 
684   if (Subtarget.hasAltivec()) {
685     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
686       setOperationAction(ISD::SADDSAT, VT, Legal);
687       setOperationAction(ISD::SSUBSAT, VT, Legal);
688       setOperationAction(ISD::UADDSAT, VT, Legal);
689       setOperationAction(ISD::USUBSAT, VT, Legal);
690     }
691     // First set operation action for all vector types to expand. Then we
692     // will selectively turn on ones that can be effectively codegen'd.
693     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
694       // add/sub are legal for all supported vector VT's.
695       setOperationAction(ISD::ADD, VT, Legal);
696       setOperationAction(ISD::SUB, VT, Legal);
697 
698       // For v2i64, these are only valid with P8Vector. This is corrected after
699       // the loop.
700       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
701         setOperationAction(ISD::SMAX, VT, Legal);
702         setOperationAction(ISD::SMIN, VT, Legal);
703         setOperationAction(ISD::UMAX, VT, Legal);
704         setOperationAction(ISD::UMIN, VT, Legal);
705       }
706       else {
707         setOperationAction(ISD::SMAX, VT, Expand);
708         setOperationAction(ISD::SMIN, VT, Expand);
709         setOperationAction(ISD::UMAX, VT, Expand);
710         setOperationAction(ISD::UMIN, VT, Expand);
711       }
712 
713       if (Subtarget.hasVSX()) {
714         setOperationAction(ISD::FMAXNUM, VT, Legal);
715         setOperationAction(ISD::FMINNUM, VT, Legal);
716       }
717 
718       // Vector instructions introduced in P8
719       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
720         setOperationAction(ISD::CTPOP, VT, Legal);
721         setOperationAction(ISD::CTLZ, VT, Legal);
722       }
723       else {
724         setOperationAction(ISD::CTPOP, VT, Expand);
725         setOperationAction(ISD::CTLZ, VT, Expand);
726       }
727 
728       // Vector instructions introduced in P9
729       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
730         setOperationAction(ISD::CTTZ, VT, Legal);
731       else
732         setOperationAction(ISD::CTTZ, VT, Expand);
733 
734       // We promote all shuffles to v16i8.
735       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
736       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
737 
738       // We promote all non-typed operations to v4i32.
739       setOperationAction(ISD::AND   , VT, Promote);
740       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
741       setOperationAction(ISD::OR    , VT, Promote);
742       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
743       setOperationAction(ISD::XOR   , VT, Promote);
744       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
745       setOperationAction(ISD::LOAD  , VT, Promote);
746       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
747       setOperationAction(ISD::SELECT, VT, Promote);
748       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
749       setOperationAction(ISD::VSELECT, VT, Legal);
750       setOperationAction(ISD::SELECT_CC, VT, Promote);
751       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
752       setOperationAction(ISD::STORE, VT, Promote);
753       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
754 
755       // No other operations are legal.
756       setOperationAction(ISD::MUL , VT, Expand);
757       setOperationAction(ISD::SDIV, VT, Expand);
758       setOperationAction(ISD::SREM, VT, Expand);
759       setOperationAction(ISD::UDIV, VT, Expand);
760       setOperationAction(ISD::UREM, VT, Expand);
761       setOperationAction(ISD::FDIV, VT, Expand);
762       setOperationAction(ISD::FREM, VT, Expand);
763       setOperationAction(ISD::FNEG, VT, Expand);
764       setOperationAction(ISD::FSQRT, VT, Expand);
765       setOperationAction(ISD::FLOG, VT, Expand);
766       setOperationAction(ISD::FLOG10, VT, Expand);
767       setOperationAction(ISD::FLOG2, VT, Expand);
768       setOperationAction(ISD::FEXP, VT, Expand);
769       setOperationAction(ISD::FEXP2, VT, Expand);
770       setOperationAction(ISD::FSIN, VT, Expand);
771       setOperationAction(ISD::FCOS, VT, Expand);
772       setOperationAction(ISD::FABS, VT, Expand);
773       setOperationAction(ISD::FFLOOR, VT, Expand);
774       setOperationAction(ISD::FCEIL,  VT, Expand);
775       setOperationAction(ISD::FTRUNC, VT, Expand);
776       setOperationAction(ISD::FRINT,  VT, Expand);
777       setOperationAction(ISD::FNEARBYINT, VT, Expand);
778       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
779       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
780       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
781       setOperationAction(ISD::MULHU, VT, Expand);
782       setOperationAction(ISD::MULHS, VT, Expand);
783       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
784       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
785       setOperationAction(ISD::UDIVREM, VT, Expand);
786       setOperationAction(ISD::SDIVREM, VT, Expand);
787       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
788       setOperationAction(ISD::FPOW, VT, Expand);
789       setOperationAction(ISD::BSWAP, VT, Expand);
790       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
791       setOperationAction(ISD::ROTL, VT, Expand);
792       setOperationAction(ISD::ROTR, VT, Expand);
793 
794       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
795         setTruncStoreAction(VT, InnerVT, Expand);
796         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
797         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
798         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
799       }
800     }
801     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
802     if (!Subtarget.hasP8Vector()) {
803       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
804       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
805       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
806       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
807     }
808 
809     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
810       setOperationAction(ISD::ABS, VT, Custom);
811 
812     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
813     // with merges, splats, etc.
814     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
815 
816     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
817     // are cheap, so handle them before they get expanded to scalar.
818     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
819     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
820     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
821     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
822     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
823 
824     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
825     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
826     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
827     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
828     setOperationAction(ISD::SELECT, MVT::v4i32,
829                        Subtarget.useCRBits() ? Legal : Expand);
830     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
831     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
832     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
833     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
834     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
835     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
836     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
837     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
838     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
839     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
840     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
841     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
842     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
843 
844     // Without hasP8Altivec set, v2i64 SMAX isn't available.
845     // But ABS custom lowering requires SMAX support.
846     if (!Subtarget.hasP8Altivec())
847       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
848 
849     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
850     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
851     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
852     if (Subtarget.hasAltivec())
853       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
854         setOperationAction(ISD::ROTL, VT, Legal);
855     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
856     if (Subtarget.hasP8Altivec())
857       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
858 
859     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
860     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
861     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
862     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
863 
864     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
865     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
866 
867     if (Subtarget.hasVSX()) {
868       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
869       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
870     }
871 
872     if (Subtarget.hasP8Altivec())
873       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
874     else
875       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
876 
877     if (Subtarget.isISA3_1()) {
878       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
879       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
880       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
881       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
882       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
883       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
884       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
885       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
886       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
887       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
888       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
889       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
890       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
891       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
892       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
893       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
894       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
895       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
896     }
897 
898     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
899     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
900 
901     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
902     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
903 
904     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
905     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
906     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
907     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
908 
909     // Altivec does not contain unordered floating-point compare instructions
910     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
911     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
912     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
913     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
914 
915     if (Subtarget.hasVSX()) {
916       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
917       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
918       if (Subtarget.hasP8Vector()) {
919         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
920         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
921       }
922       if (Subtarget.hasDirectMove() && isPPC64) {
923         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
924         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
925         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
926         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
927         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
928         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
929         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
930         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
931       }
932       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
933 
934       // The nearbyint variants are not allowed to raise the inexact exception
935       // so we can only code-gen them with unsafe math.
936       if (TM.Options.UnsafeFPMath) {
937         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
938         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
939       }
940 
941       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
942       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
943       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
944       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
945       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
946       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
947       setOperationAction(ISD::FROUND, MVT::f64, Legal);
948       setOperationAction(ISD::FRINT, MVT::f64, Legal);
949 
950       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
951       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
952       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
953       setOperationAction(ISD::FROUND, MVT::f32, Legal);
954       setOperationAction(ISD::FRINT, MVT::f32, Legal);
955 
956       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
957       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
958 
959       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
960       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
961 
962       // Share the Altivec comparison restrictions.
963       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
964       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
965       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
966       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
967 
968       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
969       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
970 
971       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
972 
973       if (Subtarget.hasP8Vector())
974         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
975 
976       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
977 
978       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
979       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
980       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
981 
982       if (Subtarget.hasP8Altivec()) {
983         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
984         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
985         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
986 
987         // 128 bit shifts can be accomplished via 3 instructions for SHL and
988         // SRL, but not for SRA because of the instructions available:
989         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
990         // doing
991         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
992         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
993         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
994 
995         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
996       }
997       else {
998         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
999         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1000         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1001 
1002         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1003 
1004         // VSX v2i64 only supports non-arithmetic operations.
1005         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1006         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1007       }
1008 
1009       if (Subtarget.isISA3_1())
1010         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1011       else
1012         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1013 
1014       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1015       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1016       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1017       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1018 
1019       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1020 
1021       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1022       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1023       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1024       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1025       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1026       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1027       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1028       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1029 
1030       // Custom handling for partial vectors of integers converted to
1031       // floating point. We already have optimal handling for v2i32 through
1032       // the DAG combine, so those aren't necessary.
1033       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1034       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1035       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1036       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1037       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1038       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1039       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1040       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1041       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1042       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1043       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1044       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1045       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1046       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1047       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1048       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1049 
1050       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1051       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1052       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1053       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1054       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1055       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1056 
1057       if (Subtarget.hasDirectMove())
1058         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1059       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1060 
1061       // Handle constrained floating-point operations of vector.
1062       // The predictor is `hasVSX` because altivec instruction has
1063       // no exception but VSX vector instruction has.
1064       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1065       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1066       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1067       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1068       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1069       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1070       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1071       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1072       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1073       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1074       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1075       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1076       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1077 
1078       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1079       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1080       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1081       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1082       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1083       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1084       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1085       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1086       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1087       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1088       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1089       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1090       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1091 
1092       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1093     }
1094 
1095     if (Subtarget.hasP8Altivec()) {
1096       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1097       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1098     }
1099 
1100     if (Subtarget.hasP9Vector()) {
1101       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1102       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1103 
1104       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1105       // SRL, but not for SRA because of the instructions available:
1106       // VS{RL} and VS{RL}O.
1107       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1108       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1109       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1110 
1111       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1112       setOperationAction(ISD::FADD, MVT::f128, Legal);
1113       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1114       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1115       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1116       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1117       // No extending loads to f128 on PPC.
1118       for (MVT FPT : MVT::fp_valuetypes())
1119         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1120       setOperationAction(ISD::FMA, MVT::f128, Legal);
1121       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1122       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1123       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1124       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1125       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1126       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1127 
1128       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1129       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1130       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1131       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1132       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1133       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1134 
1135       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1136       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1137       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1138       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1139       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1140       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1141       // No implementation for these ops for PowerPC.
1142       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1143       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1144       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1145       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1146       setOperationAction(ISD::FREM, MVT::f128, Expand);
1147 
1148       // Handle constrained floating-point operations of fp128
1149       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1150       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1151       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1152       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1153       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1154       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1155       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1156       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1157       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1158       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1159       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1160       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1161       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1162       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1163       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1164       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1165       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1166       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1167       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1168       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1169     }
1170 
1171     if (Subtarget.hasP9Altivec()) {
1172       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1173       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1174 
1175       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1176       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1177       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1178       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1179       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1180       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1181       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1182     }
1183   }
1184 
1185   if (Subtarget.pairedVectorMemops()) {
1186     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1187     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1188     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1189   }
1190   if (Subtarget.hasMMA()) {
1191     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1192     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1193     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1194     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1195   }
1196 
1197   if (Subtarget.has64BitSupport())
1198     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1199 
1200   if (Subtarget.isISA3_1())
1201     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1202 
1203   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1204 
1205   if (!isPPC64) {
1206     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1207     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1208   }
1209 
1210   setBooleanContents(ZeroOrOneBooleanContent);
1211 
1212   if (Subtarget.hasAltivec()) {
1213     // Altivec instructions set fields to all zeros or all ones.
1214     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1215   }
1216 
1217   if (!isPPC64) {
1218     // These libcalls are not available in 32-bit.
1219     setLibcallName(RTLIB::SHL_I128, nullptr);
1220     setLibcallName(RTLIB::SRL_I128, nullptr);
1221     setLibcallName(RTLIB::SRA_I128, nullptr);
1222   }
1223 
1224   if (!isPPC64)
1225     setMaxAtomicSizeInBitsSupported(32);
1226 
1227   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1228 
1229   // We have target-specific dag combine patterns for the following nodes:
1230   setTargetDAGCombine(ISD::ADD);
1231   setTargetDAGCombine(ISD::SHL);
1232   setTargetDAGCombine(ISD::SRA);
1233   setTargetDAGCombine(ISD::SRL);
1234   setTargetDAGCombine(ISD::MUL);
1235   setTargetDAGCombine(ISD::FMA);
1236   setTargetDAGCombine(ISD::SINT_TO_FP);
1237   setTargetDAGCombine(ISD::BUILD_VECTOR);
1238   if (Subtarget.hasFPCVT())
1239     setTargetDAGCombine(ISD::UINT_TO_FP);
1240   setTargetDAGCombine(ISD::LOAD);
1241   setTargetDAGCombine(ISD::STORE);
1242   setTargetDAGCombine(ISD::BR_CC);
1243   if (Subtarget.useCRBits())
1244     setTargetDAGCombine(ISD::BRCOND);
1245   setTargetDAGCombine(ISD::BSWAP);
1246   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1247   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1248   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1249 
1250   setTargetDAGCombine(ISD::SIGN_EXTEND);
1251   setTargetDAGCombine(ISD::ZERO_EXTEND);
1252   setTargetDAGCombine(ISD::ANY_EXTEND);
1253 
1254   setTargetDAGCombine(ISD::TRUNCATE);
1255   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1256 
1257 
1258   if (Subtarget.useCRBits()) {
1259     setTargetDAGCombine(ISD::TRUNCATE);
1260     setTargetDAGCombine(ISD::SETCC);
1261     setTargetDAGCombine(ISD::SELECT_CC);
1262   }
1263 
1264   if (Subtarget.hasP9Altivec()) {
1265     setTargetDAGCombine(ISD::ABS);
1266     setTargetDAGCombine(ISD::VSELECT);
1267   }
1268 
1269   setLibcallName(RTLIB::LOG_F128, "logf128");
1270   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1271   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1272   setLibcallName(RTLIB::EXP_F128, "expf128");
1273   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1274   setLibcallName(RTLIB::SIN_F128, "sinf128");
1275   setLibcallName(RTLIB::COS_F128, "cosf128");
1276   setLibcallName(RTLIB::POW_F128, "powf128");
1277   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1278   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1279   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1280   setLibcallName(RTLIB::REM_F128, "fmodf128");
1281 
1282   // With 32 condition bits, we don't need to sink (and duplicate) compares
1283   // aggressively in CodeGenPrep.
1284   if (Subtarget.useCRBits()) {
1285     setHasMultipleConditionRegisters();
1286     setJumpIsExpensive();
1287   }
1288 
1289   setMinFunctionAlignment(Align(4));
1290 
1291   switch (Subtarget.getCPUDirective()) {
1292   default: break;
1293   case PPC::DIR_970:
1294   case PPC::DIR_A2:
1295   case PPC::DIR_E500:
1296   case PPC::DIR_E500mc:
1297   case PPC::DIR_E5500:
1298   case PPC::DIR_PWR4:
1299   case PPC::DIR_PWR5:
1300   case PPC::DIR_PWR5X:
1301   case PPC::DIR_PWR6:
1302   case PPC::DIR_PWR6X:
1303   case PPC::DIR_PWR7:
1304   case PPC::DIR_PWR8:
1305   case PPC::DIR_PWR9:
1306   case PPC::DIR_PWR10:
1307   case PPC::DIR_PWR_FUTURE:
1308     setPrefLoopAlignment(Align(16));
1309     setPrefFunctionAlignment(Align(16));
1310     break;
1311   }
1312 
1313   if (Subtarget.enableMachineScheduler())
1314     setSchedulingPreference(Sched::Source);
1315   else
1316     setSchedulingPreference(Sched::Hybrid);
1317 
1318   computeRegisterProperties(STI.getRegisterInfo());
1319 
1320   // The Freescale cores do better with aggressive inlining of memcpy and
1321   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1322   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1323       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1324     MaxStoresPerMemset = 32;
1325     MaxStoresPerMemsetOptSize = 16;
1326     MaxStoresPerMemcpy = 32;
1327     MaxStoresPerMemcpyOptSize = 8;
1328     MaxStoresPerMemmove = 32;
1329     MaxStoresPerMemmoveOptSize = 8;
1330   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1331     // The A2 also benefits from (very) aggressive inlining of memcpy and
1332     // friends. The overhead of a the function call, even when warm, can be
1333     // over one hundred cycles.
1334     MaxStoresPerMemset = 128;
1335     MaxStoresPerMemcpy = 128;
1336     MaxStoresPerMemmove = 128;
1337     MaxLoadsPerMemcmp = 128;
1338   } else {
1339     MaxLoadsPerMemcmp = 8;
1340     MaxLoadsPerMemcmpOptSize = 4;
1341   }
1342 
1343   IsStrictFPEnabled = true;
1344 
1345   // Let the subtarget (CPU) decide if a predictable select is more expensive
1346   // than the corresponding branch. This information is used in CGP to decide
1347   // when to convert selects into branches.
1348   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1349 }
1350 
1351 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1352 /// the desired ByVal argument alignment.
1353 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1354   if (MaxAlign == MaxMaxAlign)
1355     return;
1356   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1357     if (MaxMaxAlign >= 32 &&
1358         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1359       MaxAlign = Align(32);
1360     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1361              MaxAlign < 16)
1362       MaxAlign = Align(16);
1363   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1364     Align EltAlign;
1365     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1366     if (EltAlign > MaxAlign)
1367       MaxAlign = EltAlign;
1368   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1369     for (auto *EltTy : STy->elements()) {
1370       Align EltAlign;
1371       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1372       if (EltAlign > MaxAlign)
1373         MaxAlign = EltAlign;
1374       if (MaxAlign == MaxMaxAlign)
1375         break;
1376     }
1377   }
1378 }
1379 
1380 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1381 /// function arguments in the caller parameter area.
1382 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1383                                                   const DataLayout &DL) const {
1384   // 16byte and wider vectors are passed on 16byte boundary.
1385   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1386   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1387   if (Subtarget.hasAltivec())
1388     getMaxByValAlign(Ty, Alignment, Align(16));
1389   return Alignment.value();
1390 }
1391 
1392 bool PPCTargetLowering::useSoftFloat() const {
1393   return Subtarget.useSoftFloat();
1394 }
1395 
1396 bool PPCTargetLowering::hasSPE() const {
1397   return Subtarget.hasSPE();
1398 }
1399 
1400 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1401   return VT.isScalarInteger();
1402 }
1403 
1404 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1405 /// type is cheaper than a multiply followed by a shift.
1406 /// This is true for words and doublewords on 64-bit PowerPC.
1407 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1408   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1409                               isOperationLegal(ISD::MULHU, Type)))
1410     return true;
1411   return TargetLowering::isMulhCheaperThanMulShift(Type);
1412 }
1413 
1414 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1415   switch ((PPCISD::NodeType)Opcode) {
1416   case PPCISD::FIRST_NUMBER:    break;
1417   case PPCISD::FSEL:            return "PPCISD::FSEL";
1418   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1419   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1420   case PPCISD::FCFID:           return "PPCISD::FCFID";
1421   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1422   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1423   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1424   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1425   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1426   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1427   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1428   case PPCISD::FP_TO_UINT_IN_VSR:
1429                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1430   case PPCISD::FP_TO_SINT_IN_VSR:
1431                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1432   case PPCISD::FRE:             return "PPCISD::FRE";
1433   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1434   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1435   case PPCISD::VPERM:           return "PPCISD::VPERM";
1436   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1437   case PPCISD::XXSPLTI_SP_TO_DP:
1438     return "PPCISD::XXSPLTI_SP_TO_DP";
1439   case PPCISD::XXSPLTI32DX:
1440     return "PPCISD::XXSPLTI32DX";
1441   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1442   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1443   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1444   case PPCISD::CMPB:            return "PPCISD::CMPB";
1445   case PPCISD::Hi:              return "PPCISD::Hi";
1446   case PPCISD::Lo:              return "PPCISD::Lo";
1447   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1448   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1449   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1450   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1451   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1452   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1453   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1454   case PPCISD::SRL:             return "PPCISD::SRL";
1455   case PPCISD::SRA:             return "PPCISD::SRA";
1456   case PPCISD::SHL:             return "PPCISD::SHL";
1457   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1458   case PPCISD::CALL:            return "PPCISD::CALL";
1459   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1460   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1461   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1462   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1463   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1464   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1465   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1466   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1467   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1468   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1469   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1470   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1471   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1472   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1473   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1474   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1475     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1476   case PPCISD::ANDI_rec_1_EQ_BIT:
1477     return "PPCISD::ANDI_rec_1_EQ_BIT";
1478   case PPCISD::ANDI_rec_1_GT_BIT:
1479     return "PPCISD::ANDI_rec_1_GT_BIT";
1480   case PPCISD::VCMP:            return "PPCISD::VCMP";
1481   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1482   case PPCISD::LBRX:            return "PPCISD::LBRX";
1483   case PPCISD::STBRX:           return "PPCISD::STBRX";
1484   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1485   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1486   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1487   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1488   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1489   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1490   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1491   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1492   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1493   case PPCISD::ST_VSR_SCAL_INT:
1494                                 return "PPCISD::ST_VSR_SCAL_INT";
1495   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1496   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1497   case PPCISD::BDZ:             return "PPCISD::BDZ";
1498   case PPCISD::MFFS:            return "PPCISD::MFFS";
1499   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1500   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1501   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1502   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1503   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1504   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1505   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1506   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1507   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1508   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1509   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1510   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1511   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1512   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1513   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1514   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1515   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1516   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1517   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1518   case PPCISD::PADDI_DTPREL:
1519     return "PPCISD::PADDI_DTPREL";
1520   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1521   case PPCISD::SC:              return "PPCISD::SC";
1522   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1523   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1524   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1525   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1526   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1527   case PPCISD::VABSD:           return "PPCISD::VABSD";
1528   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1529   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1530   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1531   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1532   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1533   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1534   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1535   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1536     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1537   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1538     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1539   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1540   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1541   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1542   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1543   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1544   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1545   case PPCISD::STRICT_FADDRTZ:
1546     return "PPCISD::STRICT_FADDRTZ";
1547   case PPCISD::STRICT_FCTIDZ:
1548     return "PPCISD::STRICT_FCTIDZ";
1549   case PPCISD::STRICT_FCTIWZ:
1550     return "PPCISD::STRICT_FCTIWZ";
1551   case PPCISD::STRICT_FCTIDUZ:
1552     return "PPCISD::STRICT_FCTIDUZ";
1553   case PPCISD::STRICT_FCTIWUZ:
1554     return "PPCISD::STRICT_FCTIWUZ";
1555   case PPCISD::STRICT_FCFID:
1556     return "PPCISD::STRICT_FCFID";
1557   case PPCISD::STRICT_FCFIDU:
1558     return "PPCISD::STRICT_FCFIDU";
1559   case PPCISD::STRICT_FCFIDS:
1560     return "PPCISD::STRICT_FCFIDS";
1561   case PPCISD::STRICT_FCFIDUS:
1562     return "PPCISD::STRICT_FCFIDUS";
1563   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1564   }
1565   return nullptr;
1566 }
1567 
1568 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1569                                           EVT VT) const {
1570   if (!VT.isVector())
1571     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1572 
1573   return VT.changeVectorElementTypeToInteger();
1574 }
1575 
1576 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1577   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1578   return true;
1579 }
1580 
1581 //===----------------------------------------------------------------------===//
1582 // Node matching predicates, for use by the tblgen matching code.
1583 //===----------------------------------------------------------------------===//
1584 
1585 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1586 static bool isFloatingPointZero(SDValue Op) {
1587   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1588     return CFP->getValueAPF().isZero();
1589   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1590     // Maybe this has already been legalized into the constant pool?
1591     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1592       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1593         return CFP->getValueAPF().isZero();
1594   }
1595   return false;
1596 }
1597 
1598 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1599 /// true if Op is undef or if it matches the specified value.
1600 static bool isConstantOrUndef(int Op, int Val) {
1601   return Op < 0 || Op == Val;
1602 }
1603 
1604 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1605 /// VPKUHUM instruction.
1606 /// The ShuffleKind distinguishes between big-endian operations with
1607 /// two different inputs (0), either-endian operations with two identical
1608 /// inputs (1), and little-endian operations with two different inputs (2).
1609 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1610 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1611                                SelectionDAG &DAG) {
1612   bool IsLE = DAG.getDataLayout().isLittleEndian();
1613   if (ShuffleKind == 0) {
1614     if (IsLE)
1615       return false;
1616     for (unsigned i = 0; i != 16; ++i)
1617       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1618         return false;
1619   } else if (ShuffleKind == 2) {
1620     if (!IsLE)
1621       return false;
1622     for (unsigned i = 0; i != 16; ++i)
1623       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1624         return false;
1625   } else if (ShuffleKind == 1) {
1626     unsigned j = IsLE ? 0 : 1;
1627     for (unsigned i = 0; i != 8; ++i)
1628       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1629           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1630         return false;
1631   }
1632   return true;
1633 }
1634 
1635 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1636 /// VPKUWUM instruction.
1637 /// The ShuffleKind distinguishes between big-endian operations with
1638 /// two different inputs (0), either-endian operations with two identical
1639 /// inputs (1), and little-endian operations with two different inputs (2).
1640 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1641 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1642                                SelectionDAG &DAG) {
1643   bool IsLE = DAG.getDataLayout().isLittleEndian();
1644   if (ShuffleKind == 0) {
1645     if (IsLE)
1646       return false;
1647     for (unsigned i = 0; i != 16; i += 2)
1648       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1649           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1650         return false;
1651   } else if (ShuffleKind == 2) {
1652     if (!IsLE)
1653       return false;
1654     for (unsigned i = 0; i != 16; i += 2)
1655       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1656           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1657         return false;
1658   } else if (ShuffleKind == 1) {
1659     unsigned j = IsLE ? 0 : 2;
1660     for (unsigned i = 0; i != 8; i += 2)
1661       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1662           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1663           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1664           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1665         return false;
1666   }
1667   return true;
1668 }
1669 
1670 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1671 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1672 /// current subtarget.
1673 ///
1674 /// The ShuffleKind distinguishes between big-endian operations with
1675 /// two different inputs (0), either-endian operations with two identical
1676 /// inputs (1), and little-endian operations with two different inputs (2).
1677 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1678 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1679                                SelectionDAG &DAG) {
1680   const PPCSubtarget& Subtarget =
1681       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1682   if (!Subtarget.hasP8Vector())
1683     return false;
1684 
1685   bool IsLE = DAG.getDataLayout().isLittleEndian();
1686   if (ShuffleKind == 0) {
1687     if (IsLE)
1688       return false;
1689     for (unsigned i = 0; i != 16; i += 4)
1690       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1691           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1692           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1693           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1694         return false;
1695   } else if (ShuffleKind == 2) {
1696     if (!IsLE)
1697       return false;
1698     for (unsigned i = 0; i != 16; i += 4)
1699       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1700           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1701           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1702           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1703         return false;
1704   } else if (ShuffleKind == 1) {
1705     unsigned j = IsLE ? 0 : 4;
1706     for (unsigned i = 0; i != 8; i += 4)
1707       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1708           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1709           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1710           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1711           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1712           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1713           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1714           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1715         return false;
1716   }
1717   return true;
1718 }
1719 
1720 /// isVMerge - Common function, used to match vmrg* shuffles.
1721 ///
1722 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1723                      unsigned LHSStart, unsigned RHSStart) {
1724   if (N->getValueType(0) != MVT::v16i8)
1725     return false;
1726   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1727          "Unsupported merge size!");
1728 
1729   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1730     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1731       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1732                              LHSStart+j+i*UnitSize) ||
1733           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1734                              RHSStart+j+i*UnitSize))
1735         return false;
1736     }
1737   return true;
1738 }
1739 
1740 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1741 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1742 /// The ShuffleKind distinguishes between big-endian merges with two
1743 /// different inputs (0), either-endian merges with two identical inputs (1),
1744 /// and little-endian merges with two different inputs (2).  For the latter,
1745 /// the input operands are swapped (see PPCInstrAltivec.td).
1746 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1747                              unsigned ShuffleKind, SelectionDAG &DAG) {
1748   if (DAG.getDataLayout().isLittleEndian()) {
1749     if (ShuffleKind == 1) // unary
1750       return isVMerge(N, UnitSize, 0, 0);
1751     else if (ShuffleKind == 2) // swapped
1752       return isVMerge(N, UnitSize, 0, 16);
1753     else
1754       return false;
1755   } else {
1756     if (ShuffleKind == 1) // unary
1757       return isVMerge(N, UnitSize, 8, 8);
1758     else if (ShuffleKind == 0) // normal
1759       return isVMerge(N, UnitSize, 8, 24);
1760     else
1761       return false;
1762   }
1763 }
1764 
1765 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1766 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1767 /// The ShuffleKind distinguishes between big-endian merges with two
1768 /// different inputs (0), either-endian merges with two identical inputs (1),
1769 /// and little-endian merges with two different inputs (2).  For the latter,
1770 /// the input operands are swapped (see PPCInstrAltivec.td).
1771 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1772                              unsigned ShuffleKind, SelectionDAG &DAG) {
1773   if (DAG.getDataLayout().isLittleEndian()) {
1774     if (ShuffleKind == 1) // unary
1775       return isVMerge(N, UnitSize, 8, 8);
1776     else if (ShuffleKind == 2) // swapped
1777       return isVMerge(N, UnitSize, 8, 24);
1778     else
1779       return false;
1780   } else {
1781     if (ShuffleKind == 1) // unary
1782       return isVMerge(N, UnitSize, 0, 0);
1783     else if (ShuffleKind == 0) // normal
1784       return isVMerge(N, UnitSize, 0, 16);
1785     else
1786       return false;
1787   }
1788 }
1789 
1790 /**
1791  * Common function used to match vmrgew and vmrgow shuffles
1792  *
1793  * The indexOffset determines whether to look for even or odd words in
1794  * the shuffle mask. This is based on the of the endianness of the target
1795  * machine.
1796  *   - Little Endian:
1797  *     - Use offset of 0 to check for odd elements
1798  *     - Use offset of 4 to check for even elements
1799  *   - Big Endian:
1800  *     - Use offset of 0 to check for even elements
1801  *     - Use offset of 4 to check for odd elements
1802  * A detailed description of the vector element ordering for little endian and
1803  * big endian can be found at
1804  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1805  * Targeting your applications - what little endian and big endian IBM XL C/C++
1806  * compiler differences mean to you
1807  *
1808  * The mask to the shuffle vector instruction specifies the indices of the
1809  * elements from the two input vectors to place in the result. The elements are
1810  * numbered in array-access order, starting with the first vector. These vectors
1811  * are always of type v16i8, thus each vector will contain 16 elements of size
1812  * 8. More info on the shuffle vector can be found in the
1813  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1814  * Language Reference.
1815  *
1816  * The RHSStartValue indicates whether the same input vectors are used (unary)
1817  * or two different input vectors are used, based on the following:
1818  *   - If the instruction uses the same vector for both inputs, the range of the
1819  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1820  *     be 0.
1821  *   - If the instruction has two different vectors then the range of the
1822  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1823  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1824  *     to 31 specify elements in the second vector).
1825  *
1826  * \param[in] N The shuffle vector SD Node to analyze
1827  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1828  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1829  * vector to the shuffle_vector instruction
1830  * \return true iff this shuffle vector represents an even or odd word merge
1831  */
1832 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1833                      unsigned RHSStartValue) {
1834   if (N->getValueType(0) != MVT::v16i8)
1835     return false;
1836 
1837   for (unsigned i = 0; i < 2; ++i)
1838     for (unsigned j = 0; j < 4; ++j)
1839       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1840                              i*RHSStartValue+j+IndexOffset) ||
1841           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1842                              i*RHSStartValue+j+IndexOffset+8))
1843         return false;
1844   return true;
1845 }
1846 
1847 /**
1848  * Determine if the specified shuffle mask is suitable for the vmrgew or
1849  * vmrgow instructions.
1850  *
1851  * \param[in] N The shuffle vector SD Node to analyze
1852  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1853  * \param[in] ShuffleKind Identify the type of merge:
1854  *   - 0 = big-endian merge with two different inputs;
1855  *   - 1 = either-endian merge with two identical inputs;
1856  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1857  *     little-endian merges).
1858  * \param[in] DAG The current SelectionDAG
1859  * \return true iff this shuffle mask
1860  */
1861 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1862                               unsigned ShuffleKind, SelectionDAG &DAG) {
1863   if (DAG.getDataLayout().isLittleEndian()) {
1864     unsigned indexOffset = CheckEven ? 4 : 0;
1865     if (ShuffleKind == 1) // Unary
1866       return isVMerge(N, indexOffset, 0);
1867     else if (ShuffleKind == 2) // swapped
1868       return isVMerge(N, indexOffset, 16);
1869     else
1870       return false;
1871   }
1872   else {
1873     unsigned indexOffset = CheckEven ? 0 : 4;
1874     if (ShuffleKind == 1) // Unary
1875       return isVMerge(N, indexOffset, 0);
1876     else if (ShuffleKind == 0) // Normal
1877       return isVMerge(N, indexOffset, 16);
1878     else
1879       return false;
1880   }
1881   return false;
1882 }
1883 
1884 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1885 /// amount, otherwise return -1.
1886 /// The ShuffleKind distinguishes between big-endian operations with two
1887 /// different inputs (0), either-endian operations with two identical inputs
1888 /// (1), and little-endian operations with two different inputs (2).  For the
1889 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1890 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1891                              SelectionDAG &DAG) {
1892   if (N->getValueType(0) != MVT::v16i8)
1893     return -1;
1894 
1895   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1896 
1897   // Find the first non-undef value in the shuffle mask.
1898   unsigned i;
1899   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1900     /*search*/;
1901 
1902   if (i == 16) return -1;  // all undef.
1903 
1904   // Otherwise, check to see if the rest of the elements are consecutively
1905   // numbered from this value.
1906   unsigned ShiftAmt = SVOp->getMaskElt(i);
1907   if (ShiftAmt < i) return -1;
1908 
1909   ShiftAmt -= i;
1910   bool isLE = DAG.getDataLayout().isLittleEndian();
1911 
1912   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1913     // Check the rest of the elements to see if they are consecutive.
1914     for (++i; i != 16; ++i)
1915       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1916         return -1;
1917   } else if (ShuffleKind == 1) {
1918     // Check the rest of the elements to see if they are consecutive.
1919     for (++i; i != 16; ++i)
1920       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1921         return -1;
1922   } else
1923     return -1;
1924 
1925   if (isLE)
1926     ShiftAmt = 16 - ShiftAmt;
1927 
1928   return ShiftAmt;
1929 }
1930 
1931 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1932 /// specifies a splat of a single element that is suitable for input to
1933 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1934 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1935   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1936          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1937 
1938   // The consecutive indices need to specify an element, not part of two
1939   // different elements.  So abandon ship early if this isn't the case.
1940   if (N->getMaskElt(0) % EltSize != 0)
1941     return false;
1942 
1943   // This is a splat operation if each element of the permute is the same, and
1944   // if the value doesn't reference the second vector.
1945   unsigned ElementBase = N->getMaskElt(0);
1946 
1947   // FIXME: Handle UNDEF elements too!
1948   if (ElementBase >= 16)
1949     return false;
1950 
1951   // Check that the indices are consecutive, in the case of a multi-byte element
1952   // splatted with a v16i8 mask.
1953   for (unsigned i = 1; i != EltSize; ++i)
1954     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1955       return false;
1956 
1957   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1958     if (N->getMaskElt(i) < 0) continue;
1959     for (unsigned j = 0; j != EltSize; ++j)
1960       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1961         return false;
1962   }
1963   return true;
1964 }
1965 
1966 /// Check that the mask is shuffling N byte elements. Within each N byte
1967 /// element of the mask, the indices could be either in increasing or
1968 /// decreasing order as long as they are consecutive.
1969 /// \param[in] N the shuffle vector SD Node to analyze
1970 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1971 /// Word/DoubleWord/QuadWord).
1972 /// \param[in] StepLen the delta indices number among the N byte element, if
1973 /// the mask is in increasing/decreasing order then it is 1/-1.
1974 /// \return true iff the mask is shuffling N byte elements.
1975 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1976                                    int StepLen) {
1977   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1978          "Unexpected element width.");
1979   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1980 
1981   unsigned NumOfElem = 16 / Width;
1982   unsigned MaskVal[16]; //  Width is never greater than 16
1983   for (unsigned i = 0; i < NumOfElem; ++i) {
1984     MaskVal[0] = N->getMaskElt(i * Width);
1985     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1986       return false;
1987     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1988       return false;
1989     }
1990 
1991     for (unsigned int j = 1; j < Width; ++j) {
1992       MaskVal[j] = N->getMaskElt(i * Width + j);
1993       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1994         return false;
1995       }
1996     }
1997   }
1998 
1999   return true;
2000 }
2001 
2002 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2003                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2004   if (!isNByteElemShuffleMask(N, 4, 1))
2005     return false;
2006 
2007   // Now we look at mask elements 0,4,8,12
2008   unsigned M0 = N->getMaskElt(0) / 4;
2009   unsigned M1 = N->getMaskElt(4) / 4;
2010   unsigned M2 = N->getMaskElt(8) / 4;
2011   unsigned M3 = N->getMaskElt(12) / 4;
2012   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2013   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2014 
2015   // Below, let H and L be arbitrary elements of the shuffle mask
2016   // where H is in the range [4,7] and L is in the range [0,3].
2017   // H, 1, 2, 3 or L, 5, 6, 7
2018   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2019       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2020     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2021     InsertAtByte = IsLE ? 12 : 0;
2022     Swap = M0 < 4;
2023     return true;
2024   }
2025   // 0, H, 2, 3 or 4, L, 6, 7
2026   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2027       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2028     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2029     InsertAtByte = IsLE ? 8 : 4;
2030     Swap = M1 < 4;
2031     return true;
2032   }
2033   // 0, 1, H, 3 or 4, 5, L, 7
2034   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2035       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2036     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2037     InsertAtByte = IsLE ? 4 : 8;
2038     Swap = M2 < 4;
2039     return true;
2040   }
2041   // 0, 1, 2, H or 4, 5, 6, L
2042   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2043       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2044     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2045     InsertAtByte = IsLE ? 0 : 12;
2046     Swap = M3 < 4;
2047     return true;
2048   }
2049 
2050   // If both vector operands for the shuffle are the same vector, the mask will
2051   // contain only elements from the first one and the second one will be undef.
2052   if (N->getOperand(1).isUndef()) {
2053     ShiftElts = 0;
2054     Swap = true;
2055     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2056     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2057       InsertAtByte = IsLE ? 12 : 0;
2058       return true;
2059     }
2060     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2061       InsertAtByte = IsLE ? 8 : 4;
2062       return true;
2063     }
2064     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2065       InsertAtByte = IsLE ? 4 : 8;
2066       return true;
2067     }
2068     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2069       InsertAtByte = IsLE ? 0 : 12;
2070       return true;
2071     }
2072   }
2073 
2074   return false;
2075 }
2076 
2077 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2078                                bool &Swap, bool IsLE) {
2079   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2080   // Ensure each byte index of the word is consecutive.
2081   if (!isNByteElemShuffleMask(N, 4, 1))
2082     return false;
2083 
2084   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2085   unsigned M0 = N->getMaskElt(0) / 4;
2086   unsigned M1 = N->getMaskElt(4) / 4;
2087   unsigned M2 = N->getMaskElt(8) / 4;
2088   unsigned M3 = N->getMaskElt(12) / 4;
2089 
2090   // If both vector operands for the shuffle are the same vector, the mask will
2091   // contain only elements from the first one and the second one will be undef.
2092   if (N->getOperand(1).isUndef()) {
2093     assert(M0 < 4 && "Indexing into an undef vector?");
2094     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2095       return false;
2096 
2097     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2098     Swap = false;
2099     return true;
2100   }
2101 
2102   // Ensure each word index of the ShuffleVector Mask is consecutive.
2103   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2104     return false;
2105 
2106   if (IsLE) {
2107     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2108       // Input vectors don't need to be swapped if the leading element
2109       // of the result is one of the 3 left elements of the second vector
2110       // (or if there is no shift to be done at all).
2111       Swap = false;
2112       ShiftElts = (8 - M0) % 8;
2113     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2114       // Input vectors need to be swapped if the leading element
2115       // of the result is one of the 3 left elements of the first vector
2116       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2117       Swap = true;
2118       ShiftElts = (4 - M0) % 4;
2119     }
2120 
2121     return true;
2122   } else {                                          // BE
2123     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2124       // Input vectors don't need to be swapped if the leading element
2125       // of the result is one of the 4 elements of the first vector.
2126       Swap = false;
2127       ShiftElts = M0;
2128     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2129       // Input vectors need to be swapped if the leading element
2130       // of the result is one of the 4 elements of the right vector.
2131       Swap = true;
2132       ShiftElts = M0 - 4;
2133     }
2134 
2135     return true;
2136   }
2137 }
2138 
2139 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2140   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2141 
2142   if (!isNByteElemShuffleMask(N, Width, -1))
2143     return false;
2144 
2145   for (int i = 0; i < 16; i += Width)
2146     if (N->getMaskElt(i) != i + Width - 1)
2147       return false;
2148 
2149   return true;
2150 }
2151 
2152 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2153   return isXXBRShuffleMaskHelper(N, 2);
2154 }
2155 
2156 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2157   return isXXBRShuffleMaskHelper(N, 4);
2158 }
2159 
2160 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2161   return isXXBRShuffleMaskHelper(N, 8);
2162 }
2163 
2164 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2165   return isXXBRShuffleMaskHelper(N, 16);
2166 }
2167 
2168 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2169 /// if the inputs to the instruction should be swapped and set \p DM to the
2170 /// value for the immediate.
2171 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2172 /// AND element 0 of the result comes from the first input (LE) or second input
2173 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2174 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2175 /// mask.
2176 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2177                                bool &Swap, bool IsLE) {
2178   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2179 
2180   // Ensure each byte index of the double word is consecutive.
2181   if (!isNByteElemShuffleMask(N, 8, 1))
2182     return false;
2183 
2184   unsigned M0 = N->getMaskElt(0) / 8;
2185   unsigned M1 = N->getMaskElt(8) / 8;
2186   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2187 
2188   // If both vector operands for the shuffle are the same vector, the mask will
2189   // contain only elements from the first one and the second one will be undef.
2190   if (N->getOperand(1).isUndef()) {
2191     if ((M0 | M1) < 2) {
2192       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2193       Swap = false;
2194       return true;
2195     } else
2196       return false;
2197   }
2198 
2199   if (IsLE) {
2200     if (M0 > 1 && M1 < 2) {
2201       Swap = false;
2202     } else if (M0 < 2 && M1 > 1) {
2203       M0 = (M0 + 2) % 4;
2204       M1 = (M1 + 2) % 4;
2205       Swap = true;
2206     } else
2207       return false;
2208 
2209     // Note: if control flow comes here that means Swap is already set above
2210     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2211     return true;
2212   } else { // BE
2213     if (M0 < 2 && M1 > 1) {
2214       Swap = false;
2215     } else if (M0 > 1 && M1 < 2) {
2216       M0 = (M0 + 2) % 4;
2217       M1 = (M1 + 2) % 4;
2218       Swap = true;
2219     } else
2220       return false;
2221 
2222     // Note: if control flow comes here that means Swap is already set above
2223     DM = (M0 << 1) + (M1 & 1);
2224     return true;
2225   }
2226 }
2227 
2228 
2229 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2230 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2231 /// elements are counted from the left of the vector register).
2232 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2233                                          SelectionDAG &DAG) {
2234   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2235   assert(isSplatShuffleMask(SVOp, EltSize));
2236   if (DAG.getDataLayout().isLittleEndian())
2237     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2238   else
2239     return SVOp->getMaskElt(0) / EltSize;
2240 }
2241 
2242 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2243 /// by using a vspltis[bhw] instruction of the specified element size, return
2244 /// the constant being splatted.  The ByteSize field indicates the number of
2245 /// bytes of each element [124] -> [bhw].
2246 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2247   SDValue OpVal(nullptr, 0);
2248 
2249   // If ByteSize of the splat is bigger than the element size of the
2250   // build_vector, then we have a case where we are checking for a splat where
2251   // multiple elements of the buildvector are folded together into a single
2252   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2253   unsigned EltSize = 16/N->getNumOperands();
2254   if (EltSize < ByteSize) {
2255     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2256     SDValue UniquedVals[4];
2257     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2258 
2259     // See if all of the elements in the buildvector agree across.
2260     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2261       if (N->getOperand(i).isUndef()) continue;
2262       // If the element isn't a constant, bail fully out.
2263       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2264 
2265       if (!UniquedVals[i&(Multiple-1)].getNode())
2266         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2267       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2268         return SDValue();  // no match.
2269     }
2270 
2271     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2272     // either constant or undef values that are identical for each chunk.  See
2273     // if these chunks can form into a larger vspltis*.
2274 
2275     // Check to see if all of the leading entries are either 0 or -1.  If
2276     // neither, then this won't fit into the immediate field.
2277     bool LeadingZero = true;
2278     bool LeadingOnes = true;
2279     for (unsigned i = 0; i != Multiple-1; ++i) {
2280       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2281 
2282       LeadingZero &= isNullConstant(UniquedVals[i]);
2283       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2284     }
2285     // Finally, check the least significant entry.
2286     if (LeadingZero) {
2287       if (!UniquedVals[Multiple-1].getNode())
2288         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2289       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2290       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2291         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2292     }
2293     if (LeadingOnes) {
2294       if (!UniquedVals[Multiple-1].getNode())
2295         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2296       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2297       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2298         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2299     }
2300 
2301     return SDValue();
2302   }
2303 
2304   // Check to see if this buildvec has a single non-undef value in its elements.
2305   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2306     if (N->getOperand(i).isUndef()) continue;
2307     if (!OpVal.getNode())
2308       OpVal = N->getOperand(i);
2309     else if (OpVal != N->getOperand(i))
2310       return SDValue();
2311   }
2312 
2313   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2314 
2315   unsigned ValSizeInBytes = EltSize;
2316   uint64_t Value = 0;
2317   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2318     Value = CN->getZExtValue();
2319   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2320     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2321     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2322   }
2323 
2324   // If the splat value is larger than the element value, then we can never do
2325   // this splat.  The only case that we could fit the replicated bits into our
2326   // immediate field for would be zero, and we prefer to use vxor for it.
2327   if (ValSizeInBytes < ByteSize) return SDValue();
2328 
2329   // If the element value is larger than the splat value, check if it consists
2330   // of a repeated bit pattern of size ByteSize.
2331   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2332     return SDValue();
2333 
2334   // Properly sign extend the value.
2335   int MaskVal = SignExtend32(Value, ByteSize * 8);
2336 
2337   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2338   if (MaskVal == 0) return SDValue();
2339 
2340   // Finally, if this value fits in a 5 bit sext field, return it
2341   if (SignExtend32<5>(MaskVal) == MaskVal)
2342     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2343   return SDValue();
2344 }
2345 
2346 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2347 /// amount, otherwise return -1.
2348 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2349   EVT VT = N->getValueType(0);
2350   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2351     return -1;
2352 
2353   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2354 
2355   // Find the first non-undef value in the shuffle mask.
2356   unsigned i;
2357   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2358     /*search*/;
2359 
2360   if (i == 4) return -1;  // all undef.
2361 
2362   // Otherwise, check to see if the rest of the elements are consecutively
2363   // numbered from this value.
2364   unsigned ShiftAmt = SVOp->getMaskElt(i);
2365   if (ShiftAmt < i) return -1;
2366   ShiftAmt -= i;
2367 
2368   // Check the rest of the elements to see if they are consecutive.
2369   for (++i; i != 4; ++i)
2370     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2371       return -1;
2372 
2373   return ShiftAmt;
2374 }
2375 
2376 //===----------------------------------------------------------------------===//
2377 //  Addressing Mode Selection
2378 //===----------------------------------------------------------------------===//
2379 
2380 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2381 /// or 64-bit immediate, and if the value can be accurately represented as a
2382 /// sign extension from a 16-bit value.  If so, this returns true and the
2383 /// immediate.
2384 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2385   if (!isa<ConstantSDNode>(N))
2386     return false;
2387 
2388   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2389   if (N->getValueType(0) == MVT::i32)
2390     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2391   else
2392     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2393 }
2394 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2395   return isIntS16Immediate(Op.getNode(), Imm);
2396 }
2397 
2398 
2399 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2400 /// be represented as an indexed [r+r] operation.
2401 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2402                                                SDValue &Index,
2403                                                SelectionDAG &DAG) const {
2404   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2405       UI != E; ++UI) {
2406     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2407       if (Memop->getMemoryVT() == MVT::f64) {
2408           Base = N.getOperand(0);
2409           Index = N.getOperand(1);
2410           return true;
2411       }
2412     }
2413   }
2414   return false;
2415 }
2416 
2417 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2418 /// can be represented as an indexed [r+r] operation.  Returns false if it
2419 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2420 /// non-zero and N can be represented by a base register plus a signed 16-bit
2421 /// displacement, make a more precise judgement by checking (displacement % \p
2422 /// EncodingAlignment).
2423 bool PPCTargetLowering::SelectAddressRegReg(
2424     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2425     MaybeAlign EncodingAlignment) const {
2426   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2427   // a [pc+imm].
2428   if (SelectAddressPCRel(N, Base))
2429     return false;
2430 
2431   int16_t Imm = 0;
2432   if (N.getOpcode() == ISD::ADD) {
2433     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2434     // SPE load/store can only handle 8-bit offsets.
2435     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2436         return true;
2437     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2438         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2439       return false; // r+i
2440     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2441       return false;    // r+i
2442 
2443     Base = N.getOperand(0);
2444     Index = N.getOperand(1);
2445     return true;
2446   } else if (N.getOpcode() == ISD::OR) {
2447     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2448         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2449       return false; // r+i can fold it if we can.
2450 
2451     // If this is an or of disjoint bitfields, we can codegen this as an add
2452     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2453     // disjoint.
2454     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2455 
2456     if (LHSKnown.Zero.getBoolValue()) {
2457       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2458       // If all of the bits are known zero on the LHS or RHS, the add won't
2459       // carry.
2460       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2461         Base = N.getOperand(0);
2462         Index = N.getOperand(1);
2463         return true;
2464       }
2465     }
2466   }
2467 
2468   return false;
2469 }
2470 
2471 // If we happen to be doing an i64 load or store into a stack slot that has
2472 // less than a 4-byte alignment, then the frame-index elimination may need to
2473 // use an indexed load or store instruction (because the offset may not be a
2474 // multiple of 4). The extra register needed to hold the offset comes from the
2475 // register scavenger, and it is possible that the scavenger will need to use
2476 // an emergency spill slot. As a result, we need to make sure that a spill slot
2477 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2478 // stack slot.
2479 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2480   // FIXME: This does not handle the LWA case.
2481   if (VT != MVT::i64)
2482     return;
2483 
2484   // NOTE: We'll exclude negative FIs here, which come from argument
2485   // lowering, because there are no known test cases triggering this problem
2486   // using packed structures (or similar). We can remove this exclusion if
2487   // we find such a test case. The reason why this is so test-case driven is
2488   // because this entire 'fixup' is only to prevent crashes (from the
2489   // register scavenger) on not-really-valid inputs. For example, if we have:
2490   //   %a = alloca i1
2491   //   %b = bitcast i1* %a to i64*
2492   //   store i64* a, i64 b
2493   // then the store should really be marked as 'align 1', but is not. If it
2494   // were marked as 'align 1' then the indexed form would have been
2495   // instruction-selected initially, and the problem this 'fixup' is preventing
2496   // won't happen regardless.
2497   if (FrameIdx < 0)
2498     return;
2499 
2500   MachineFunction &MF = DAG.getMachineFunction();
2501   MachineFrameInfo &MFI = MF.getFrameInfo();
2502 
2503   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2504     return;
2505 
2506   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2507   FuncInfo->setHasNonRISpills();
2508 }
2509 
2510 /// Returns true if the address N can be represented by a base register plus
2511 /// a signed 16-bit displacement [r+imm], and if it is not better
2512 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2513 /// displacements that are multiples of that value.
2514 bool PPCTargetLowering::SelectAddressRegImm(
2515     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2516     MaybeAlign EncodingAlignment) const {
2517   // FIXME dl should come from parent load or store, not from address
2518   SDLoc dl(N);
2519 
2520   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2521   // a [pc+imm].
2522   if (SelectAddressPCRel(N, Base))
2523     return false;
2524 
2525   // If this can be more profitably realized as r+r, fail.
2526   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2527     return false;
2528 
2529   if (N.getOpcode() == ISD::ADD) {
2530     int16_t imm = 0;
2531     if (isIntS16Immediate(N.getOperand(1), imm) &&
2532         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2533       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2534       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2535         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2536         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2537       } else {
2538         Base = N.getOperand(0);
2539       }
2540       return true; // [r+i]
2541     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2542       // Match LOAD (ADD (X, Lo(G))).
2543       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2544              && "Cannot handle constant offsets yet!");
2545       Disp = N.getOperand(1).getOperand(0);  // The global address.
2546       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2547              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2548              Disp.getOpcode() == ISD::TargetConstantPool ||
2549              Disp.getOpcode() == ISD::TargetJumpTable);
2550       Base = N.getOperand(0);
2551       return true;  // [&g+r]
2552     }
2553   } else if (N.getOpcode() == ISD::OR) {
2554     int16_t imm = 0;
2555     if (isIntS16Immediate(N.getOperand(1), imm) &&
2556         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2557       // If this is an or of disjoint bitfields, we can codegen this as an add
2558       // (for better address arithmetic) if the LHS and RHS of the OR are
2559       // provably disjoint.
2560       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2561 
2562       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2563         // If all of the bits are known zero on the LHS or RHS, the add won't
2564         // carry.
2565         if (FrameIndexSDNode *FI =
2566               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2567           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2568           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2569         } else {
2570           Base = N.getOperand(0);
2571         }
2572         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2573         return true;
2574       }
2575     }
2576   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2577     // Loading from a constant address.
2578 
2579     // If this address fits entirely in a 16-bit sext immediate field, codegen
2580     // this as "d, 0"
2581     int16_t Imm;
2582     if (isIntS16Immediate(CN, Imm) &&
2583         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2584       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2585       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2586                              CN->getValueType(0));
2587       return true;
2588     }
2589 
2590     // Handle 32-bit sext immediates with LIS + addr mode.
2591     if ((CN->getValueType(0) == MVT::i32 ||
2592          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2593         (!EncodingAlignment ||
2594          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2595       int Addr = (int)CN->getZExtValue();
2596 
2597       // Otherwise, break this down into an LIS + disp.
2598       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2599 
2600       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2601                                    MVT::i32);
2602       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2603       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2604       return true;
2605     }
2606   }
2607 
2608   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2609   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2610     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2611     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2612   } else
2613     Base = N;
2614   return true;      // [r+0]
2615 }
2616 
2617 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2618 /// represented as an indexed [r+r] operation.
2619 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2620                                                 SDValue &Index,
2621                                                 SelectionDAG &DAG) const {
2622   // Check to see if we can easily represent this as an [r+r] address.  This
2623   // will fail if it thinks that the address is more profitably represented as
2624   // reg+imm, e.g. where imm = 0.
2625   if (SelectAddressRegReg(N, Base, Index, DAG))
2626     return true;
2627 
2628   // If the address is the result of an add, we will utilize the fact that the
2629   // address calculation includes an implicit add.  However, we can reduce
2630   // register pressure if we do not materialize a constant just for use as the
2631   // index register.  We only get rid of the add if it is not an add of a
2632   // value and a 16-bit signed constant and both have a single use.
2633   int16_t imm = 0;
2634   if (N.getOpcode() == ISD::ADD &&
2635       (!isIntS16Immediate(N.getOperand(1), imm) ||
2636        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2637     Base = N.getOperand(0);
2638     Index = N.getOperand(1);
2639     return true;
2640   }
2641 
2642   // Otherwise, do it the hard way, using R0 as the base register.
2643   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2644                          N.getValueType());
2645   Index = N;
2646   return true;
2647 }
2648 
2649 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2650   Ty *PCRelCand = dyn_cast<Ty>(N);
2651   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2652 }
2653 
2654 /// Returns true if this address is a PC Relative address.
2655 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2656 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2657 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2658   // This is a materialize PC Relative node. Always select this as PC Relative.
2659   Base = N;
2660   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2661     return true;
2662   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2663       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2664       isValidPCRelNode<JumpTableSDNode>(N) ||
2665       isValidPCRelNode<BlockAddressSDNode>(N))
2666     return true;
2667   return false;
2668 }
2669 
2670 /// Returns true if we should use a direct load into vector instruction
2671 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2672 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2673 
2674   // If there are any other uses other than scalar to vector, then we should
2675   // keep it as a scalar load -> direct move pattern to prevent multiple
2676   // loads.
2677   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2678   if (!LD)
2679     return false;
2680 
2681   EVT MemVT = LD->getMemoryVT();
2682   if (!MemVT.isSimple())
2683     return false;
2684   switch(MemVT.getSimpleVT().SimpleTy) {
2685   case MVT::i64:
2686     break;
2687   case MVT::i32:
2688     if (!ST.hasP8Vector())
2689       return false;
2690     break;
2691   case MVT::i16:
2692   case MVT::i8:
2693     if (!ST.hasP9Vector())
2694       return false;
2695     break;
2696   default:
2697     return false;
2698   }
2699 
2700   SDValue LoadedVal(N, 0);
2701   if (!LoadedVal.hasOneUse())
2702     return false;
2703 
2704   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2705        UI != UE; ++UI)
2706     if (UI.getUse().get().getResNo() == 0 &&
2707         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2708         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2709       return false;
2710 
2711   return true;
2712 }
2713 
2714 /// getPreIndexedAddressParts - returns true by value, base pointer and
2715 /// offset pointer and addressing mode by reference if the node's address
2716 /// can be legally represented as pre-indexed load / store address.
2717 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2718                                                   SDValue &Offset,
2719                                                   ISD::MemIndexedMode &AM,
2720                                                   SelectionDAG &DAG) const {
2721   if (DisablePPCPreinc) return false;
2722 
2723   bool isLoad = true;
2724   SDValue Ptr;
2725   EVT VT;
2726   unsigned Alignment;
2727   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2728     Ptr = LD->getBasePtr();
2729     VT = LD->getMemoryVT();
2730     Alignment = LD->getAlignment();
2731   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2732     Ptr = ST->getBasePtr();
2733     VT  = ST->getMemoryVT();
2734     Alignment = ST->getAlignment();
2735     isLoad = false;
2736   } else
2737     return false;
2738 
2739   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2740   // instructions because we can fold these into a more efficient instruction
2741   // instead, (such as LXSD).
2742   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2743     return false;
2744   }
2745 
2746   // PowerPC doesn't have preinc load/store instructions for vectors
2747   if (VT.isVector())
2748     return false;
2749 
2750   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2751     // Common code will reject creating a pre-inc form if the base pointer
2752     // is a frame index, or if N is a store and the base pointer is either
2753     // the same as or a predecessor of the value being stored.  Check for
2754     // those situations here, and try with swapped Base/Offset instead.
2755     bool Swap = false;
2756 
2757     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2758       Swap = true;
2759     else if (!isLoad) {
2760       SDValue Val = cast<StoreSDNode>(N)->getValue();
2761       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2762         Swap = true;
2763     }
2764 
2765     if (Swap)
2766       std::swap(Base, Offset);
2767 
2768     AM = ISD::PRE_INC;
2769     return true;
2770   }
2771 
2772   // LDU/STU can only handle immediates that are a multiple of 4.
2773   if (VT != MVT::i64) {
2774     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2775       return false;
2776   } else {
2777     // LDU/STU need an address with at least 4-byte alignment.
2778     if (Alignment < 4)
2779       return false;
2780 
2781     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2782       return false;
2783   }
2784 
2785   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2786     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2787     // sext i32 to i64 when addr mode is r+i.
2788     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2789         LD->getExtensionType() == ISD::SEXTLOAD &&
2790         isa<ConstantSDNode>(Offset))
2791       return false;
2792   }
2793 
2794   AM = ISD::PRE_INC;
2795   return true;
2796 }
2797 
2798 //===----------------------------------------------------------------------===//
2799 //  LowerOperation implementation
2800 //===----------------------------------------------------------------------===//
2801 
2802 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2803 /// and LoOpFlags to the target MO flags.
2804 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2805                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2806                                const GlobalValue *GV = nullptr) {
2807   HiOpFlags = PPCII::MO_HA;
2808   LoOpFlags = PPCII::MO_LO;
2809 
2810   // Don't use the pic base if not in PIC relocation model.
2811   if (IsPIC) {
2812     HiOpFlags |= PPCII::MO_PIC_FLAG;
2813     LoOpFlags |= PPCII::MO_PIC_FLAG;
2814   }
2815 }
2816 
2817 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2818                              SelectionDAG &DAG) {
2819   SDLoc DL(HiPart);
2820   EVT PtrVT = HiPart.getValueType();
2821   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2822 
2823   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2824   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2825 
2826   // With PIC, the first instruction is actually "GR+hi(&G)".
2827   if (isPIC)
2828     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2829                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2830 
2831   // Generate non-pic code that has direct accesses to the constant pool.
2832   // The address of the global is just (hi(&g)+lo(&g)).
2833   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2834 }
2835 
2836 static void setUsesTOCBasePtr(MachineFunction &MF) {
2837   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2838   FuncInfo->setUsesTOCBasePtr();
2839 }
2840 
2841 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2842   setUsesTOCBasePtr(DAG.getMachineFunction());
2843 }
2844 
2845 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2846                                        SDValue GA) const {
2847   const bool Is64Bit = Subtarget.isPPC64();
2848   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2849   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2850                         : Subtarget.isAIXABI()
2851                               ? DAG.getRegister(PPC::R2, VT)
2852                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2853   SDValue Ops[] = { GA, Reg };
2854   return DAG.getMemIntrinsicNode(
2855       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2856       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2857       MachineMemOperand::MOLoad);
2858 }
2859 
2860 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2861                                              SelectionDAG &DAG) const {
2862   EVT PtrVT = Op.getValueType();
2863   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2864   const Constant *C = CP->getConstVal();
2865 
2866   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2867   // The actual address of the GlobalValue is stored in the TOC.
2868   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2869     if (Subtarget.isUsingPCRelativeCalls()) {
2870       SDLoc DL(CP);
2871       EVT Ty = getPointerTy(DAG.getDataLayout());
2872       SDValue ConstPool = DAG.getTargetConstantPool(
2873           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2874       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2875     }
2876     setUsesTOCBasePtr(DAG);
2877     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2878     return getTOCEntry(DAG, SDLoc(CP), GA);
2879   }
2880 
2881   unsigned MOHiFlag, MOLoFlag;
2882   bool IsPIC = isPositionIndependent();
2883   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2884 
2885   if (IsPIC && Subtarget.isSVR4ABI()) {
2886     SDValue GA =
2887         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2888     return getTOCEntry(DAG, SDLoc(CP), GA);
2889   }
2890 
2891   SDValue CPIHi =
2892       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2893   SDValue CPILo =
2894       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2895   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2896 }
2897 
2898 // For 64-bit PowerPC, prefer the more compact relative encodings.
2899 // This trades 32 bits per jump table entry for one or two instructions
2900 // on the jump site.
2901 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2902   if (isJumpTableRelative())
2903     return MachineJumpTableInfo::EK_LabelDifference32;
2904 
2905   return TargetLowering::getJumpTableEncoding();
2906 }
2907 
2908 bool PPCTargetLowering::isJumpTableRelative() const {
2909   if (UseAbsoluteJumpTables)
2910     return false;
2911   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2912     return true;
2913   return TargetLowering::isJumpTableRelative();
2914 }
2915 
2916 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2917                                                     SelectionDAG &DAG) const {
2918   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2919     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2920 
2921   switch (getTargetMachine().getCodeModel()) {
2922   case CodeModel::Small:
2923   case CodeModel::Medium:
2924     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2925   default:
2926     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2927                        getPointerTy(DAG.getDataLayout()));
2928   }
2929 }
2930 
2931 const MCExpr *
2932 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2933                                                 unsigned JTI,
2934                                                 MCContext &Ctx) const {
2935   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2936     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2937 
2938   switch (getTargetMachine().getCodeModel()) {
2939   case CodeModel::Small:
2940   case CodeModel::Medium:
2941     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2942   default:
2943     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2944   }
2945 }
2946 
2947 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2948   EVT PtrVT = Op.getValueType();
2949   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2950 
2951   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2952   if (Subtarget.isUsingPCRelativeCalls()) {
2953     SDLoc DL(JT);
2954     EVT Ty = getPointerTy(DAG.getDataLayout());
2955     SDValue GA =
2956         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2957     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2958     return MatAddr;
2959   }
2960 
2961   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2962   // The actual address of the GlobalValue is stored in the TOC.
2963   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2964     setUsesTOCBasePtr(DAG);
2965     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2966     return getTOCEntry(DAG, SDLoc(JT), GA);
2967   }
2968 
2969   unsigned MOHiFlag, MOLoFlag;
2970   bool IsPIC = isPositionIndependent();
2971   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2972 
2973   if (IsPIC && Subtarget.isSVR4ABI()) {
2974     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2975                                         PPCII::MO_PIC_FLAG);
2976     return getTOCEntry(DAG, SDLoc(GA), GA);
2977   }
2978 
2979   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2980   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2981   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2982 }
2983 
2984 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2985                                              SelectionDAG &DAG) const {
2986   EVT PtrVT = Op.getValueType();
2987   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2988   const BlockAddress *BA = BASDN->getBlockAddress();
2989 
2990   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2991   if (Subtarget.isUsingPCRelativeCalls()) {
2992     SDLoc DL(BASDN);
2993     EVT Ty = getPointerTy(DAG.getDataLayout());
2994     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2995                                            PPCII::MO_PCREL_FLAG);
2996     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2997     return MatAddr;
2998   }
2999 
3000   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3001   // The actual BlockAddress is stored in the TOC.
3002   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3003     setUsesTOCBasePtr(DAG);
3004     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3005     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3006   }
3007 
3008   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3009   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3010     return getTOCEntry(
3011         DAG, SDLoc(BASDN),
3012         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3013 
3014   unsigned MOHiFlag, MOLoFlag;
3015   bool IsPIC = isPositionIndependent();
3016   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3017   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3018   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3019   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3020 }
3021 
3022 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3023                                               SelectionDAG &DAG) const {
3024   // FIXME: TLS addresses currently use medium model code sequences,
3025   // which is the most useful form.  Eventually support for small and
3026   // large models could be added if users need it, at the cost of
3027   // additional complexity.
3028   if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS)
3029     report_fatal_error("Thread local storage is not supported with pc-relative"
3030                        " addressing - please compile with -mno-pcrel");
3031   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3032   if (DAG.getTarget().useEmulatedTLS())
3033     return LowerToTLSEmulatedModel(GA, DAG);
3034 
3035   SDLoc dl(GA);
3036   const GlobalValue *GV = GA->getGlobal();
3037   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3038   bool is64bit = Subtarget.isPPC64();
3039   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3040   PICLevel::Level picLevel = M->getPICLevel();
3041 
3042   const TargetMachine &TM = getTargetMachine();
3043   TLSModel::Model Model = TM.getTLSModel(GV);
3044 
3045   if (Model == TLSModel::LocalExec) {
3046     if (Subtarget.isUsingPCRelativeCalls()) {
3047       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3048       SDValue TGA = DAG.getTargetGlobalAddress(
3049           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3050       SDValue MatAddr =
3051           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3052       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3053     }
3054 
3055     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3056                                                PPCII::MO_TPREL_HA);
3057     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3058                                                PPCII::MO_TPREL_LO);
3059     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3060                              : DAG.getRegister(PPC::R2, MVT::i32);
3061 
3062     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3063     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3064   }
3065 
3066   if (Model == TLSModel::InitialExec) {
3067     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3068     SDValue TGA = DAG.getTargetGlobalAddress(
3069         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3070     SDValue TGATLS = DAG.getTargetGlobalAddress(
3071         GV, dl, PtrVT, 0,
3072         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3073     SDValue TPOffset;
3074     if (IsPCRel) {
3075       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3076       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3077                              MachinePointerInfo());
3078     } else {
3079       SDValue GOTPtr;
3080       if (is64bit) {
3081         setUsesTOCBasePtr(DAG);
3082         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3083         GOTPtr =
3084             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3085       } else {
3086         if (!TM.isPositionIndependent())
3087           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3088         else 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       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3094     }
3095     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3096   }
3097 
3098   if (Model == TLSModel::GeneralDynamic) {
3099     if (Subtarget.isUsingPCRelativeCalls()) {
3100       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3101                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3102       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3103     }
3104 
3105     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3106     SDValue GOTPtr;
3107     if (is64bit) {
3108       setUsesTOCBasePtr(DAG);
3109       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3110       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3111                                    GOTReg, TGA);
3112     } else {
3113       if (picLevel == PICLevel::SmallPIC)
3114         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3115       else
3116         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3117     }
3118     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3119                        GOTPtr, TGA, TGA);
3120   }
3121 
3122   if (Model == TLSModel::LocalDynamic) {
3123     if (Subtarget.isUsingPCRelativeCalls()) {
3124       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3125                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3126       SDValue MatPCRel =
3127           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3128       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3129     }
3130 
3131     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3132     SDValue GOTPtr;
3133     if (is64bit) {
3134       setUsesTOCBasePtr(DAG);
3135       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3136       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3137                            GOTReg, TGA);
3138     } else {
3139       if (picLevel == PICLevel::SmallPIC)
3140         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3141       else
3142         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3143     }
3144     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3145                                   PtrVT, GOTPtr, TGA, TGA);
3146     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3147                                       PtrVT, TLSAddr, TGA);
3148     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3149   }
3150 
3151   llvm_unreachable("Unknown TLS model!");
3152 }
3153 
3154 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3155                                               SelectionDAG &DAG) const {
3156   EVT PtrVT = Op.getValueType();
3157   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3158   SDLoc DL(GSDN);
3159   const GlobalValue *GV = GSDN->getGlobal();
3160 
3161   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3162   // The actual address of the GlobalValue is stored in the TOC.
3163   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3164     if (Subtarget.isUsingPCRelativeCalls()) {
3165       EVT Ty = getPointerTy(DAG.getDataLayout());
3166       if (isAccessedAsGotIndirect(Op)) {
3167         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3168                                                 PPCII::MO_PCREL_FLAG |
3169                                                     PPCII::MO_GOT_FLAG);
3170         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3171         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3172                                    MachinePointerInfo());
3173         return Load;
3174       } else {
3175         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3176                                                 PPCII::MO_PCREL_FLAG);
3177         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3178       }
3179     }
3180     setUsesTOCBasePtr(DAG);
3181     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3182     return getTOCEntry(DAG, DL, GA);
3183   }
3184 
3185   unsigned MOHiFlag, MOLoFlag;
3186   bool IsPIC = isPositionIndependent();
3187   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3188 
3189   if (IsPIC && Subtarget.isSVR4ABI()) {
3190     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3191                                             GSDN->getOffset(),
3192                                             PPCII::MO_PIC_FLAG);
3193     return getTOCEntry(DAG, DL, GA);
3194   }
3195 
3196   SDValue GAHi =
3197     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3198   SDValue GALo =
3199     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3200 
3201   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3202 }
3203 
3204 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3205   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3206   SDLoc dl(Op);
3207 
3208   if (Op.getValueType() == MVT::v2i64) {
3209     // When the operands themselves are v2i64 values, we need to do something
3210     // special because VSX has no underlying comparison operations for these.
3211     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3212       // Equality can be handled by casting to the legal type for Altivec
3213       // comparisons, everything else needs to be expanded.
3214       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3215         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3216                  DAG.getSetCC(dl, MVT::v4i32,
3217                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3218                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3219                    CC));
3220       }
3221 
3222       return SDValue();
3223     }
3224 
3225     // We handle most of these in the usual way.
3226     return Op;
3227   }
3228 
3229   // If we're comparing for equality to zero, expose the fact that this is
3230   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3231   // fold the new nodes.
3232   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3233     return V;
3234 
3235   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3236     // Leave comparisons against 0 and -1 alone for now, since they're usually
3237     // optimized.  FIXME: revisit this when we can custom lower all setcc
3238     // optimizations.
3239     if (C->isAllOnesValue() || C->isNullValue())
3240       return SDValue();
3241   }
3242 
3243   // If we have an integer seteq/setne, turn it into a compare against zero
3244   // by xor'ing the rhs with the lhs, which is faster than setting a
3245   // condition register, reading it back out, and masking the correct bit.  The
3246   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3247   // the result to other bit-twiddling opportunities.
3248   EVT LHSVT = Op.getOperand(0).getValueType();
3249   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3250     EVT VT = Op.getValueType();
3251     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3252                                 Op.getOperand(1));
3253     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3254   }
3255   return SDValue();
3256 }
3257 
3258 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3259   SDNode *Node = Op.getNode();
3260   EVT VT = Node->getValueType(0);
3261   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3262   SDValue InChain = Node->getOperand(0);
3263   SDValue VAListPtr = Node->getOperand(1);
3264   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3265   SDLoc dl(Node);
3266 
3267   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3268 
3269   // gpr_index
3270   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3271                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3272   InChain = GprIndex.getValue(1);
3273 
3274   if (VT == MVT::i64) {
3275     // Check if GprIndex is even
3276     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3277                                  DAG.getConstant(1, dl, MVT::i32));
3278     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3279                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3280     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3281                                           DAG.getConstant(1, dl, MVT::i32));
3282     // Align GprIndex to be even if it isn't
3283     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3284                            GprIndex);
3285   }
3286 
3287   // fpr index is 1 byte after gpr
3288   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3289                                DAG.getConstant(1, dl, MVT::i32));
3290 
3291   // fpr
3292   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3293                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3294   InChain = FprIndex.getValue(1);
3295 
3296   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3297                                        DAG.getConstant(8, dl, MVT::i32));
3298 
3299   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3300                                         DAG.getConstant(4, dl, MVT::i32));
3301 
3302   // areas
3303   SDValue OverflowArea =
3304       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3305   InChain = OverflowArea.getValue(1);
3306 
3307   SDValue RegSaveArea =
3308       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3309   InChain = RegSaveArea.getValue(1);
3310 
3311   // select overflow_area if index > 8
3312   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3313                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3314 
3315   // adjustment constant gpr_index * 4/8
3316   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3317                                     VT.isInteger() ? GprIndex : FprIndex,
3318                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3319                                                     MVT::i32));
3320 
3321   // OurReg = RegSaveArea + RegConstant
3322   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3323                                RegConstant);
3324 
3325   // Floating types are 32 bytes into RegSaveArea
3326   if (VT.isFloatingPoint())
3327     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3328                          DAG.getConstant(32, dl, MVT::i32));
3329 
3330   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3331   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3332                                    VT.isInteger() ? GprIndex : FprIndex,
3333                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3334                                                    MVT::i32));
3335 
3336   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3337                               VT.isInteger() ? VAListPtr : FprPtr,
3338                               MachinePointerInfo(SV), MVT::i8);
3339 
3340   // determine if we should load from reg_save_area or overflow_area
3341   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3342 
3343   // increase overflow_area by 4/8 if gpr/fpr > 8
3344   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3345                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3346                                           dl, MVT::i32));
3347 
3348   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3349                              OverflowAreaPlusN);
3350 
3351   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3352                               MachinePointerInfo(), MVT::i32);
3353 
3354   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3355 }
3356 
3357 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3358   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3359 
3360   // We have to copy the entire va_list struct:
3361   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3362   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3363                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3364                        false, true, false, MachinePointerInfo(),
3365                        MachinePointerInfo());
3366 }
3367 
3368 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3369                                                   SelectionDAG &DAG) const {
3370   if (Subtarget.isAIXABI())
3371     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3372 
3373   return Op.getOperand(0);
3374 }
3375 
3376 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3377                                                 SelectionDAG &DAG) const {
3378   if (Subtarget.isAIXABI())
3379     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3380 
3381   SDValue Chain = Op.getOperand(0);
3382   SDValue Trmp = Op.getOperand(1); // trampoline
3383   SDValue FPtr = Op.getOperand(2); // nested function
3384   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3385   SDLoc dl(Op);
3386 
3387   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3388   bool isPPC64 = (PtrVT == MVT::i64);
3389   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3390 
3391   TargetLowering::ArgListTy Args;
3392   TargetLowering::ArgListEntry Entry;
3393 
3394   Entry.Ty = IntPtrTy;
3395   Entry.Node = Trmp; Args.push_back(Entry);
3396 
3397   // TrampSize == (isPPC64 ? 48 : 40);
3398   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3399                                isPPC64 ? MVT::i64 : MVT::i32);
3400   Args.push_back(Entry);
3401 
3402   Entry.Node = FPtr; Args.push_back(Entry);
3403   Entry.Node = Nest; Args.push_back(Entry);
3404 
3405   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3406   TargetLowering::CallLoweringInfo CLI(DAG);
3407   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3408       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3409       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3410 
3411   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3412   return CallResult.second;
3413 }
3414 
3415 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3416   MachineFunction &MF = DAG.getMachineFunction();
3417   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3418   EVT PtrVT = getPointerTy(MF.getDataLayout());
3419 
3420   SDLoc dl(Op);
3421 
3422   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3423     // vastart just stores the address of the VarArgsFrameIndex slot into the
3424     // memory location argument.
3425     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3426     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3427     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3428                         MachinePointerInfo(SV));
3429   }
3430 
3431   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3432   // We suppose the given va_list is already allocated.
3433   //
3434   // typedef struct {
3435   //  char gpr;     /* index into the array of 8 GPRs
3436   //                 * stored in the register save area
3437   //                 * gpr=0 corresponds to r3,
3438   //                 * gpr=1 to r4, etc.
3439   //                 */
3440   //  char fpr;     /* index into the array of 8 FPRs
3441   //                 * stored in the register save area
3442   //                 * fpr=0 corresponds to f1,
3443   //                 * fpr=1 to f2, etc.
3444   //                 */
3445   //  char *overflow_arg_area;
3446   //                /* location on stack that holds
3447   //                 * the next overflow argument
3448   //                 */
3449   //  char *reg_save_area;
3450   //               /* where r3:r10 and f1:f8 (if saved)
3451   //                * are stored
3452   //                */
3453   // } va_list[1];
3454 
3455   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3456   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3457   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3458                                             PtrVT);
3459   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3460                                  PtrVT);
3461 
3462   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3463   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3464 
3465   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3466   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3467 
3468   uint64_t FPROffset = 1;
3469   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3470 
3471   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3472 
3473   // Store first byte : number of int regs
3474   SDValue firstStore =
3475       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3476                         MachinePointerInfo(SV), MVT::i8);
3477   uint64_t nextOffset = FPROffset;
3478   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3479                                   ConstFPROffset);
3480 
3481   // Store second byte : number of float regs
3482   SDValue secondStore =
3483       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3484                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3485   nextOffset += StackOffset;
3486   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3487 
3488   // Store second word : arguments given on stack
3489   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3490                                     MachinePointerInfo(SV, nextOffset));
3491   nextOffset += FrameOffset;
3492   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3493 
3494   // Store third word : arguments given in registers
3495   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3496                       MachinePointerInfo(SV, nextOffset));
3497 }
3498 
3499 /// FPR - The set of FP registers that should be allocated for arguments
3500 /// on Darwin and AIX.
3501 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3502                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3503                                 PPC::F11, PPC::F12, PPC::F13};
3504 
3505 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3506 /// the stack.
3507 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3508                                        unsigned PtrByteSize) {
3509   unsigned ArgSize = ArgVT.getStoreSize();
3510   if (Flags.isByVal())
3511     ArgSize = Flags.getByValSize();
3512 
3513   // Round up to multiples of the pointer size, except for array members,
3514   // which are always packed.
3515   if (!Flags.isInConsecutiveRegs())
3516     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3517 
3518   return ArgSize;
3519 }
3520 
3521 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3522 /// on the stack.
3523 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3524                                          ISD::ArgFlagsTy Flags,
3525                                          unsigned PtrByteSize) {
3526   Align Alignment(PtrByteSize);
3527 
3528   // Altivec parameters are padded to a 16 byte boundary.
3529   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3530       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3531       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3532       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3533     Alignment = Align(16);
3534 
3535   // ByVal parameters are aligned as requested.
3536   if (Flags.isByVal()) {
3537     auto BVAlign = Flags.getNonZeroByValAlign();
3538     if (BVAlign > PtrByteSize) {
3539       if (BVAlign.value() % PtrByteSize != 0)
3540         llvm_unreachable(
3541             "ByVal alignment is not a multiple of the pointer size");
3542 
3543       Alignment = BVAlign;
3544     }
3545   }
3546 
3547   // Array members are always packed to their original alignment.
3548   if (Flags.isInConsecutiveRegs()) {
3549     // If the array member was split into multiple registers, the first
3550     // needs to be aligned to the size of the full type.  (Except for
3551     // ppcf128, which is only aligned as its f64 components.)
3552     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3553       Alignment = Align(OrigVT.getStoreSize());
3554     else
3555       Alignment = Align(ArgVT.getStoreSize());
3556   }
3557 
3558   return Alignment;
3559 }
3560 
3561 /// CalculateStackSlotUsed - Return whether this argument will use its
3562 /// stack slot (instead of being passed in registers).  ArgOffset,
3563 /// AvailableFPRs, and AvailableVRs must hold the current argument
3564 /// position, and will be updated to account for this argument.
3565 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3566                                    unsigned PtrByteSize, unsigned LinkageSize,
3567                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3568                                    unsigned &AvailableFPRs,
3569                                    unsigned &AvailableVRs) {
3570   bool UseMemory = false;
3571 
3572   // Respect alignment of argument on the stack.
3573   Align Alignment =
3574       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3575   ArgOffset = alignTo(ArgOffset, Alignment);
3576   // If there's no space left in the argument save area, we must
3577   // use memory (this check also catches zero-sized arguments).
3578   if (ArgOffset >= LinkageSize + ParamAreaSize)
3579     UseMemory = true;
3580 
3581   // Allocate argument on the stack.
3582   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3583   if (Flags.isInConsecutiveRegsLast())
3584     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3585   // If we overran the argument save area, we must use memory
3586   // (this check catches arguments passed partially in memory)
3587   if (ArgOffset > LinkageSize + ParamAreaSize)
3588     UseMemory = true;
3589 
3590   // However, if the argument is actually passed in an FPR or a VR,
3591   // we don't use memory after all.
3592   if (!Flags.isByVal()) {
3593     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3594       if (AvailableFPRs > 0) {
3595         --AvailableFPRs;
3596         return false;
3597       }
3598     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3599         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3600         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3601         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3602       if (AvailableVRs > 0) {
3603         --AvailableVRs;
3604         return false;
3605       }
3606   }
3607 
3608   return UseMemory;
3609 }
3610 
3611 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3612 /// ensure minimum alignment required for target.
3613 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3614                                      unsigned NumBytes) {
3615   return alignTo(NumBytes, Lowering->getStackAlign());
3616 }
3617 
3618 SDValue PPCTargetLowering::LowerFormalArguments(
3619     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3620     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3621     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3622   if (Subtarget.isAIXABI())
3623     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3624                                     InVals);
3625   if (Subtarget.is64BitELFABI())
3626     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3627                                        InVals);
3628   if (Subtarget.is32BitELFABI())
3629     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3630                                        InVals);
3631 
3632   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3633                                      InVals);
3634 }
3635 
3636 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3637     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3638     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3639     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3640 
3641   // 32-bit SVR4 ABI Stack Frame Layout:
3642   //              +-----------------------------------+
3643   //        +-->  |            Back chain             |
3644   //        |     +-----------------------------------+
3645   //        |     | Floating-point register save area |
3646   //        |     +-----------------------------------+
3647   //        |     |    General register save area     |
3648   //        |     +-----------------------------------+
3649   //        |     |          CR save word             |
3650   //        |     +-----------------------------------+
3651   //        |     |         VRSAVE save word          |
3652   //        |     +-----------------------------------+
3653   //        |     |         Alignment padding         |
3654   //        |     +-----------------------------------+
3655   //        |     |     Vector register save area     |
3656   //        |     +-----------------------------------+
3657   //        |     |       Local variable space        |
3658   //        |     +-----------------------------------+
3659   //        |     |        Parameter list area        |
3660   //        |     +-----------------------------------+
3661   //        |     |           LR save word            |
3662   //        |     +-----------------------------------+
3663   // SP-->  +---  |            Back chain             |
3664   //              +-----------------------------------+
3665   //
3666   // Specifications:
3667   //   System V Application Binary Interface PowerPC Processor Supplement
3668   //   AltiVec Technology Programming Interface Manual
3669 
3670   MachineFunction &MF = DAG.getMachineFunction();
3671   MachineFrameInfo &MFI = MF.getFrameInfo();
3672   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3673 
3674   EVT PtrVT = getPointerTy(MF.getDataLayout());
3675   // Potential tail calls could cause overwriting of argument stack slots.
3676   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3677                        (CallConv == CallingConv::Fast));
3678   const Align PtrAlign(4);
3679 
3680   // Assign locations to all of the incoming arguments.
3681   SmallVector<CCValAssign, 16> ArgLocs;
3682   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3683                  *DAG.getContext());
3684 
3685   // Reserve space for the linkage area on the stack.
3686   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3687   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3688   if (useSoftFloat())
3689     CCInfo.PreAnalyzeFormalArguments(Ins);
3690 
3691   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3692   CCInfo.clearWasPPCF128();
3693 
3694   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3695     CCValAssign &VA = ArgLocs[i];
3696 
3697     // Arguments stored in registers.
3698     if (VA.isRegLoc()) {
3699       const TargetRegisterClass *RC;
3700       EVT ValVT = VA.getValVT();
3701 
3702       switch (ValVT.getSimpleVT().SimpleTy) {
3703         default:
3704           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3705         case MVT::i1:
3706         case MVT::i32:
3707           RC = &PPC::GPRCRegClass;
3708           break;
3709         case MVT::f32:
3710           if (Subtarget.hasP8Vector())
3711             RC = &PPC::VSSRCRegClass;
3712           else if (Subtarget.hasSPE())
3713             RC = &PPC::GPRCRegClass;
3714           else
3715             RC = &PPC::F4RCRegClass;
3716           break;
3717         case MVT::f64:
3718           if (Subtarget.hasVSX())
3719             RC = &PPC::VSFRCRegClass;
3720           else if (Subtarget.hasSPE())
3721             // SPE passes doubles in GPR pairs.
3722             RC = &PPC::GPRCRegClass;
3723           else
3724             RC = &PPC::F8RCRegClass;
3725           break;
3726         case MVT::v16i8:
3727         case MVT::v8i16:
3728         case MVT::v4i32:
3729           RC = &PPC::VRRCRegClass;
3730           break;
3731         case MVT::v4f32:
3732           RC = &PPC::VRRCRegClass;
3733           break;
3734         case MVT::v2f64:
3735         case MVT::v2i64:
3736           RC = &PPC::VRRCRegClass;
3737           break;
3738       }
3739 
3740       SDValue ArgValue;
3741       // Transform the arguments stored in physical registers into
3742       // virtual ones.
3743       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3744         assert(i + 1 < e && "No second half of double precision argument");
3745         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3746         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3747         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3748         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3749         if (!Subtarget.isLittleEndian())
3750           std::swap (ArgValueLo, ArgValueHi);
3751         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3752                                ArgValueHi);
3753       } else {
3754         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3755         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3756                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3757         if (ValVT == MVT::i1)
3758           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3759       }
3760 
3761       InVals.push_back(ArgValue);
3762     } else {
3763       // Argument stored in memory.
3764       assert(VA.isMemLoc());
3765 
3766       // Get the extended size of the argument type in stack
3767       unsigned ArgSize = VA.getLocVT().getStoreSize();
3768       // Get the actual size of the argument type
3769       unsigned ObjSize = VA.getValVT().getStoreSize();
3770       unsigned ArgOffset = VA.getLocMemOffset();
3771       // Stack objects in PPC32 are right justified.
3772       ArgOffset += ArgSize - ObjSize;
3773       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3774 
3775       // Create load nodes to retrieve arguments from the stack.
3776       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3777       InVals.push_back(
3778           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3779     }
3780   }
3781 
3782   // Assign locations to all of the incoming aggregate by value arguments.
3783   // Aggregates passed by value are stored in the local variable space of the
3784   // caller's stack frame, right above the parameter list area.
3785   SmallVector<CCValAssign, 16> ByValArgLocs;
3786   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3787                       ByValArgLocs, *DAG.getContext());
3788 
3789   // Reserve stack space for the allocations in CCInfo.
3790   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3791 
3792   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3793 
3794   // Area that is at least reserved in the caller of this function.
3795   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3796   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3797 
3798   // Set the size that is at least reserved in caller of this function.  Tail
3799   // call optimized function's reserved stack space needs to be aligned so that
3800   // taking the difference between two stack areas will result in an aligned
3801   // stack.
3802   MinReservedArea =
3803       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3804   FuncInfo->setMinReservedArea(MinReservedArea);
3805 
3806   SmallVector<SDValue, 8> MemOps;
3807 
3808   // If the function takes variable number of arguments, make a frame index for
3809   // the start of the first vararg value... for expansion of llvm.va_start.
3810   if (isVarArg) {
3811     static const MCPhysReg GPArgRegs[] = {
3812       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3813       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3814     };
3815     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3816 
3817     static const MCPhysReg FPArgRegs[] = {
3818       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3819       PPC::F8
3820     };
3821     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3822 
3823     if (useSoftFloat() || hasSPE())
3824        NumFPArgRegs = 0;
3825 
3826     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3827     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3828 
3829     // Make room for NumGPArgRegs and NumFPArgRegs.
3830     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3831                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3832 
3833     FuncInfo->setVarArgsStackOffset(
3834       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3835                             CCInfo.getNextStackOffset(), true));
3836 
3837     FuncInfo->setVarArgsFrameIndex(
3838         MFI.CreateStackObject(Depth, Align(8), false));
3839     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3840 
3841     // The fixed integer arguments of a variadic function are stored to the
3842     // VarArgsFrameIndex on the stack so that they may be loaded by
3843     // dereferencing the result of va_next.
3844     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3845       // Get an existing live-in vreg, or add a new one.
3846       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3847       if (!VReg)
3848         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3849 
3850       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3851       SDValue Store =
3852           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3853       MemOps.push_back(Store);
3854       // Increment the address by four for the next argument to store
3855       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3856       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3857     }
3858 
3859     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3860     // is set.
3861     // The double arguments are stored to the VarArgsFrameIndex
3862     // on the stack.
3863     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3864       // Get an existing live-in vreg, or add a new one.
3865       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3866       if (!VReg)
3867         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3868 
3869       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3870       SDValue Store =
3871           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3872       MemOps.push_back(Store);
3873       // Increment the address by eight for the next argument to store
3874       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3875                                          PtrVT);
3876       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3877     }
3878   }
3879 
3880   if (!MemOps.empty())
3881     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3882 
3883   return Chain;
3884 }
3885 
3886 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3887 // value to MVT::i64 and then truncate to the correct register size.
3888 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3889                                              EVT ObjectVT, SelectionDAG &DAG,
3890                                              SDValue ArgVal,
3891                                              const SDLoc &dl) const {
3892   if (Flags.isSExt())
3893     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3894                          DAG.getValueType(ObjectVT));
3895   else if (Flags.isZExt())
3896     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3897                          DAG.getValueType(ObjectVT));
3898 
3899   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3900 }
3901 
3902 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3903     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3904     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3905     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3906   // TODO: add description of PPC stack frame format, or at least some docs.
3907   //
3908   bool isELFv2ABI = Subtarget.isELFv2ABI();
3909   bool isLittleEndian = Subtarget.isLittleEndian();
3910   MachineFunction &MF = DAG.getMachineFunction();
3911   MachineFrameInfo &MFI = MF.getFrameInfo();
3912   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3913 
3914   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3915          "fastcc not supported on varargs functions");
3916 
3917   EVT PtrVT = getPointerTy(MF.getDataLayout());
3918   // Potential tail calls could cause overwriting of argument stack slots.
3919   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3920                        (CallConv == CallingConv::Fast));
3921   unsigned PtrByteSize = 8;
3922   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3923 
3924   static const MCPhysReg GPR[] = {
3925     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3926     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3927   };
3928   static const MCPhysReg VR[] = {
3929     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3930     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3931   };
3932 
3933   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3934   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3935   const unsigned Num_VR_Regs  = array_lengthof(VR);
3936 
3937   // Do a first pass over the arguments to determine whether the ABI
3938   // guarantees that our caller has allocated the parameter save area
3939   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3940   // in the ELFv2 ABI, it is true if this is a vararg function or if
3941   // any parameter is located in a stack slot.
3942 
3943   bool HasParameterArea = !isELFv2ABI || isVarArg;
3944   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3945   unsigned NumBytes = LinkageSize;
3946   unsigned AvailableFPRs = Num_FPR_Regs;
3947   unsigned AvailableVRs = Num_VR_Regs;
3948   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3949     if (Ins[i].Flags.isNest())
3950       continue;
3951 
3952     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3953                                PtrByteSize, LinkageSize, ParamAreaSize,
3954                                NumBytes, AvailableFPRs, AvailableVRs))
3955       HasParameterArea = true;
3956   }
3957 
3958   // Add DAG nodes to load the arguments or copy them out of registers.  On
3959   // entry to a function on PPC, the arguments start after the linkage area,
3960   // although the first ones are often in registers.
3961 
3962   unsigned ArgOffset = LinkageSize;
3963   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3964   SmallVector<SDValue, 8> MemOps;
3965   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3966   unsigned CurArgIdx = 0;
3967   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3968     SDValue ArgVal;
3969     bool needsLoad = false;
3970     EVT ObjectVT = Ins[ArgNo].VT;
3971     EVT OrigVT = Ins[ArgNo].ArgVT;
3972     unsigned ObjSize = ObjectVT.getStoreSize();
3973     unsigned ArgSize = ObjSize;
3974     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3975     if (Ins[ArgNo].isOrigArg()) {
3976       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3977       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3978     }
3979     // We re-align the argument offset for each argument, except when using the
3980     // fast calling convention, when we need to make sure we do that only when
3981     // we'll actually use a stack slot.
3982     unsigned CurArgOffset;
3983     Align Alignment;
3984     auto ComputeArgOffset = [&]() {
3985       /* Respect alignment of argument on the stack.  */
3986       Alignment =
3987           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3988       ArgOffset = alignTo(ArgOffset, Alignment);
3989       CurArgOffset = ArgOffset;
3990     };
3991 
3992     if (CallConv != CallingConv::Fast) {
3993       ComputeArgOffset();
3994 
3995       /* Compute GPR index associated with argument offset.  */
3996       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3997       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3998     }
3999 
4000     // FIXME the codegen can be much improved in some cases.
4001     // We do not have to keep everything in memory.
4002     if (Flags.isByVal()) {
4003       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4004 
4005       if (CallConv == CallingConv::Fast)
4006         ComputeArgOffset();
4007 
4008       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4009       ObjSize = Flags.getByValSize();
4010       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4011       // Empty aggregate parameters do not take up registers.  Examples:
4012       //   struct { } a;
4013       //   union  { } b;
4014       //   int c[0];
4015       // etc.  However, we have to provide a place-holder in InVals, so
4016       // pretend we have an 8-byte item at the current address for that
4017       // purpose.
4018       if (!ObjSize) {
4019         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4020         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4021         InVals.push_back(FIN);
4022         continue;
4023       }
4024 
4025       // Create a stack object covering all stack doublewords occupied
4026       // by the argument.  If the argument is (fully or partially) on
4027       // the stack, or if the argument is fully in registers but the
4028       // caller has allocated the parameter save anyway, we can refer
4029       // directly to the caller's stack frame.  Otherwise, create a
4030       // local copy in our own frame.
4031       int FI;
4032       if (HasParameterArea ||
4033           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4034         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4035       else
4036         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4037       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4038 
4039       // Handle aggregates smaller than 8 bytes.
4040       if (ObjSize < PtrByteSize) {
4041         // The value of the object is its address, which differs from the
4042         // address of the enclosing doubleword on big-endian systems.
4043         SDValue Arg = FIN;
4044         if (!isLittleEndian) {
4045           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4046           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4047         }
4048         InVals.push_back(Arg);
4049 
4050         if (GPR_idx != Num_GPR_Regs) {
4051           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4052           FuncInfo->addLiveInAttr(VReg, Flags);
4053           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4054           SDValue Store;
4055 
4056           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4057             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4058                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4059             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4060                                       MachinePointerInfo(&*FuncArg), ObjType);
4061           } else {
4062             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4063             // store the whole register as-is to the parameter save area
4064             // slot.
4065             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4066                                  MachinePointerInfo(&*FuncArg));
4067           }
4068 
4069           MemOps.push_back(Store);
4070         }
4071         // Whether we copied from a register or not, advance the offset
4072         // into the parameter save area by a full doubleword.
4073         ArgOffset += PtrByteSize;
4074         continue;
4075       }
4076 
4077       // The value of the object is its address, which is the address of
4078       // its first stack doubleword.
4079       InVals.push_back(FIN);
4080 
4081       // Store whatever pieces of the object are in registers to memory.
4082       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4083         if (GPR_idx == Num_GPR_Regs)
4084           break;
4085 
4086         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4087         FuncInfo->addLiveInAttr(VReg, Flags);
4088         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4089         SDValue Addr = FIN;
4090         if (j) {
4091           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4092           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4093         }
4094         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4095                                      MachinePointerInfo(&*FuncArg, j));
4096         MemOps.push_back(Store);
4097         ++GPR_idx;
4098       }
4099       ArgOffset += ArgSize;
4100       continue;
4101     }
4102 
4103     switch (ObjectVT.getSimpleVT().SimpleTy) {
4104     default: llvm_unreachable("Unhandled argument type!");
4105     case MVT::i1:
4106     case MVT::i32:
4107     case MVT::i64:
4108       if (Flags.isNest()) {
4109         // The 'nest' parameter, if any, is passed in R11.
4110         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4111         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4112 
4113         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4114           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4115 
4116         break;
4117       }
4118 
4119       // These can be scalar arguments or elements of an integer array type
4120       // passed directly.  Clang may use those instead of "byval" aggregate
4121       // types to avoid forcing arguments to memory unnecessarily.
4122       if (GPR_idx != Num_GPR_Regs) {
4123         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4124         FuncInfo->addLiveInAttr(VReg, Flags);
4125         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4126 
4127         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4128           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4129           // value to MVT::i64 and then truncate to the correct register size.
4130           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4131       } else {
4132         if (CallConv == CallingConv::Fast)
4133           ComputeArgOffset();
4134 
4135         needsLoad = true;
4136         ArgSize = PtrByteSize;
4137       }
4138       if (CallConv != CallingConv::Fast || needsLoad)
4139         ArgOffset += 8;
4140       break;
4141 
4142     case MVT::f32:
4143     case MVT::f64:
4144       // These can be scalar arguments or elements of a float array type
4145       // passed directly.  The latter are used to implement ELFv2 homogenous
4146       // float aggregates.
4147       if (FPR_idx != Num_FPR_Regs) {
4148         unsigned VReg;
4149 
4150         if (ObjectVT == MVT::f32)
4151           VReg = MF.addLiveIn(FPR[FPR_idx],
4152                               Subtarget.hasP8Vector()
4153                                   ? &PPC::VSSRCRegClass
4154                                   : &PPC::F4RCRegClass);
4155         else
4156           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4157                                                 ? &PPC::VSFRCRegClass
4158                                                 : &PPC::F8RCRegClass);
4159 
4160         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4161         ++FPR_idx;
4162       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4163         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4164         // once we support fp <-> gpr moves.
4165 
4166         // This can only ever happen in the presence of f32 array types,
4167         // since otherwise we never run out of FPRs before running out
4168         // of GPRs.
4169         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4170         FuncInfo->addLiveInAttr(VReg, Flags);
4171         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4172 
4173         if (ObjectVT == MVT::f32) {
4174           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4175             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4176                                  DAG.getConstant(32, dl, MVT::i32));
4177           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4178         }
4179 
4180         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4181       } else {
4182         if (CallConv == CallingConv::Fast)
4183           ComputeArgOffset();
4184 
4185         needsLoad = true;
4186       }
4187 
4188       // When passing an array of floats, the array occupies consecutive
4189       // space in the argument area; only round up to the next doubleword
4190       // at the end of the array.  Otherwise, each float takes 8 bytes.
4191       if (CallConv != CallingConv::Fast || needsLoad) {
4192         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4193         ArgOffset += ArgSize;
4194         if (Flags.isInConsecutiveRegsLast())
4195           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4196       }
4197       break;
4198     case MVT::v4f32:
4199     case MVT::v4i32:
4200     case MVT::v8i16:
4201     case MVT::v16i8:
4202     case MVT::v2f64:
4203     case MVT::v2i64:
4204     case MVT::v1i128:
4205     case MVT::f128:
4206       // These can be scalar arguments or elements of a vector array type
4207       // passed directly.  The latter are used to implement ELFv2 homogenous
4208       // vector aggregates.
4209       if (VR_idx != Num_VR_Regs) {
4210         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4211         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4212         ++VR_idx;
4213       } else {
4214         if (CallConv == CallingConv::Fast)
4215           ComputeArgOffset();
4216         needsLoad = true;
4217       }
4218       if (CallConv != CallingConv::Fast || needsLoad)
4219         ArgOffset += 16;
4220       break;
4221     }
4222 
4223     // We need to load the argument to a virtual register if we determined
4224     // above that we ran out of physical registers of the appropriate type.
4225     if (needsLoad) {
4226       if (ObjSize < ArgSize && !isLittleEndian)
4227         CurArgOffset += ArgSize - ObjSize;
4228       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4229       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4230       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4231     }
4232 
4233     InVals.push_back(ArgVal);
4234   }
4235 
4236   // Area that is at least reserved in the caller of this function.
4237   unsigned MinReservedArea;
4238   if (HasParameterArea)
4239     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4240   else
4241     MinReservedArea = LinkageSize;
4242 
4243   // Set the size that is at least reserved in caller of this function.  Tail
4244   // call optimized functions' reserved stack space needs to be aligned so that
4245   // taking the difference between two stack areas will result in an aligned
4246   // stack.
4247   MinReservedArea =
4248       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4249   FuncInfo->setMinReservedArea(MinReservedArea);
4250 
4251   // If the function takes variable number of arguments, make a frame index for
4252   // the start of the first vararg value... for expansion of llvm.va_start.
4253   // On ELFv2ABI spec, it writes:
4254   // C programs that are intended to be *portable* across different compilers
4255   // and architectures must use the header file <stdarg.h> to deal with variable
4256   // argument lists.
4257   if (isVarArg && MFI.hasVAStart()) {
4258     int Depth = ArgOffset;
4259 
4260     FuncInfo->setVarArgsFrameIndex(
4261       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4262     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4263 
4264     // If this function is vararg, store any remaining integer argument regs
4265     // to their spots on the stack so that they may be loaded by dereferencing
4266     // the result of va_next.
4267     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4268          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4269       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4270       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4271       SDValue Store =
4272           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4273       MemOps.push_back(Store);
4274       // Increment the address by four for the next argument to store
4275       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4276       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4277     }
4278   }
4279 
4280   if (!MemOps.empty())
4281     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4282 
4283   return Chain;
4284 }
4285 
4286 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4287     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4288     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4289     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4290   // TODO: add description of PPC stack frame format, or at least some docs.
4291   //
4292   MachineFunction &MF = DAG.getMachineFunction();
4293   MachineFrameInfo &MFI = MF.getFrameInfo();
4294   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4295 
4296   EVT PtrVT = getPointerTy(MF.getDataLayout());
4297   bool isPPC64 = PtrVT == MVT::i64;
4298   // Potential tail calls could cause overwriting of argument stack slots.
4299   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4300                        (CallConv == CallingConv::Fast));
4301   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4302   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4303   unsigned ArgOffset = LinkageSize;
4304   // Area that is at least reserved in caller of this function.
4305   unsigned MinReservedArea = ArgOffset;
4306 
4307   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4308     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4309     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4310   };
4311   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4312     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4313     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4314   };
4315   static const MCPhysReg VR[] = {
4316     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4317     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4318   };
4319 
4320   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4321   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4322   const unsigned Num_VR_Regs  = array_lengthof( VR);
4323 
4324   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4325 
4326   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4327 
4328   // In 32-bit non-varargs functions, the stack space for vectors is after the
4329   // stack space for non-vectors.  We do not use this space unless we have
4330   // too many vectors to fit in registers, something that only occurs in
4331   // constructed examples:), but we have to walk the arglist to figure
4332   // that out...for the pathological case, compute VecArgOffset as the
4333   // start of the vector parameter area.  Computing VecArgOffset is the
4334   // entire point of the following loop.
4335   unsigned VecArgOffset = ArgOffset;
4336   if (!isVarArg && !isPPC64) {
4337     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4338          ++ArgNo) {
4339       EVT ObjectVT = Ins[ArgNo].VT;
4340       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4341 
4342       if (Flags.isByVal()) {
4343         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4344         unsigned ObjSize = Flags.getByValSize();
4345         unsigned ArgSize =
4346                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4347         VecArgOffset += ArgSize;
4348         continue;
4349       }
4350 
4351       switch(ObjectVT.getSimpleVT().SimpleTy) {
4352       default: llvm_unreachable("Unhandled argument type!");
4353       case MVT::i1:
4354       case MVT::i32:
4355       case MVT::f32:
4356         VecArgOffset += 4;
4357         break;
4358       case MVT::i64:  // PPC64
4359       case MVT::f64:
4360         // FIXME: We are guaranteed to be !isPPC64 at this point.
4361         // Does MVT::i64 apply?
4362         VecArgOffset += 8;
4363         break;
4364       case MVT::v4f32:
4365       case MVT::v4i32:
4366       case MVT::v8i16:
4367       case MVT::v16i8:
4368         // Nothing to do, we're only looking at Nonvector args here.
4369         break;
4370       }
4371     }
4372   }
4373   // We've found where the vector parameter area in memory is.  Skip the
4374   // first 12 parameters; these don't use that memory.
4375   VecArgOffset = ((VecArgOffset+15)/16)*16;
4376   VecArgOffset += 12*16;
4377 
4378   // Add DAG nodes to load the arguments or copy them out of registers.  On
4379   // entry to a function on PPC, the arguments start after the linkage area,
4380   // although the first ones are often in registers.
4381 
4382   SmallVector<SDValue, 8> MemOps;
4383   unsigned nAltivecParamsAtEnd = 0;
4384   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4385   unsigned CurArgIdx = 0;
4386   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4387     SDValue ArgVal;
4388     bool needsLoad = false;
4389     EVT ObjectVT = Ins[ArgNo].VT;
4390     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4391     unsigned ArgSize = ObjSize;
4392     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4393     if (Ins[ArgNo].isOrigArg()) {
4394       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4395       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4396     }
4397     unsigned CurArgOffset = ArgOffset;
4398 
4399     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4400     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4401         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4402       if (isVarArg || isPPC64) {
4403         MinReservedArea = ((MinReservedArea+15)/16)*16;
4404         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4405                                                   Flags,
4406                                                   PtrByteSize);
4407       } else  nAltivecParamsAtEnd++;
4408     } else
4409       // Calculate min reserved area.
4410       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4411                                                 Flags,
4412                                                 PtrByteSize);
4413 
4414     // FIXME the codegen can be much improved in some cases.
4415     // We do not have to keep everything in memory.
4416     if (Flags.isByVal()) {
4417       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4418 
4419       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4420       ObjSize = Flags.getByValSize();
4421       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4422       // Objects of size 1 and 2 are right justified, everything else is
4423       // left justified.  This means the memory address is adjusted forwards.
4424       if (ObjSize==1 || ObjSize==2) {
4425         CurArgOffset = CurArgOffset + (4 - ObjSize);
4426       }
4427       // The value of the object is its address.
4428       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4429       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4430       InVals.push_back(FIN);
4431       if (ObjSize==1 || ObjSize==2) {
4432         if (GPR_idx != Num_GPR_Regs) {
4433           unsigned VReg;
4434           if (isPPC64)
4435             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4436           else
4437             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4438           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4439           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4440           SDValue Store =
4441               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4442                                 MachinePointerInfo(&*FuncArg), ObjType);
4443           MemOps.push_back(Store);
4444           ++GPR_idx;
4445         }
4446 
4447         ArgOffset += PtrByteSize;
4448 
4449         continue;
4450       }
4451       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4452         // Store whatever pieces of the object are in registers
4453         // to memory.  ArgOffset will be the address of the beginning
4454         // of the object.
4455         if (GPR_idx != Num_GPR_Regs) {
4456           unsigned VReg;
4457           if (isPPC64)
4458             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4459           else
4460             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4461           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4462           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4463           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4464           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4465                                        MachinePointerInfo(&*FuncArg, j));
4466           MemOps.push_back(Store);
4467           ++GPR_idx;
4468           ArgOffset += PtrByteSize;
4469         } else {
4470           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4471           break;
4472         }
4473       }
4474       continue;
4475     }
4476 
4477     switch (ObjectVT.getSimpleVT().SimpleTy) {
4478     default: llvm_unreachable("Unhandled argument type!");
4479     case MVT::i1:
4480     case MVT::i32:
4481       if (!isPPC64) {
4482         if (GPR_idx != Num_GPR_Regs) {
4483           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4484           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4485 
4486           if (ObjectVT == MVT::i1)
4487             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4488 
4489           ++GPR_idx;
4490         } else {
4491           needsLoad = true;
4492           ArgSize = PtrByteSize;
4493         }
4494         // All int arguments reserve stack space in the Darwin ABI.
4495         ArgOffset += PtrByteSize;
4496         break;
4497       }
4498       LLVM_FALLTHROUGH;
4499     case MVT::i64:  // PPC64
4500       if (GPR_idx != Num_GPR_Regs) {
4501         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4502         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4503 
4504         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4505           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4506           // value to MVT::i64 and then truncate to the correct register size.
4507           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4508 
4509         ++GPR_idx;
4510       } else {
4511         needsLoad = true;
4512         ArgSize = PtrByteSize;
4513       }
4514       // All int arguments reserve stack space in the Darwin ABI.
4515       ArgOffset += 8;
4516       break;
4517 
4518     case MVT::f32:
4519     case MVT::f64:
4520       // Every 4 bytes of argument space consumes one of the GPRs available for
4521       // argument passing.
4522       if (GPR_idx != Num_GPR_Regs) {
4523         ++GPR_idx;
4524         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4525           ++GPR_idx;
4526       }
4527       if (FPR_idx != Num_FPR_Regs) {
4528         unsigned VReg;
4529 
4530         if (ObjectVT == MVT::f32)
4531           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4532         else
4533           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4534 
4535         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4536         ++FPR_idx;
4537       } else {
4538         needsLoad = true;
4539       }
4540 
4541       // All FP arguments reserve stack space in the Darwin ABI.
4542       ArgOffset += isPPC64 ? 8 : ObjSize;
4543       break;
4544     case MVT::v4f32:
4545     case MVT::v4i32:
4546     case MVT::v8i16:
4547     case MVT::v16i8:
4548       // Note that vector arguments in registers don't reserve stack space,
4549       // except in varargs functions.
4550       if (VR_idx != Num_VR_Regs) {
4551         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4552         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4553         if (isVarArg) {
4554           while ((ArgOffset % 16) != 0) {
4555             ArgOffset += PtrByteSize;
4556             if (GPR_idx != Num_GPR_Regs)
4557               GPR_idx++;
4558           }
4559           ArgOffset += 16;
4560           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4561         }
4562         ++VR_idx;
4563       } else {
4564         if (!isVarArg && !isPPC64) {
4565           // Vectors go after all the nonvectors.
4566           CurArgOffset = VecArgOffset;
4567           VecArgOffset += 16;
4568         } else {
4569           // Vectors are aligned.
4570           ArgOffset = ((ArgOffset+15)/16)*16;
4571           CurArgOffset = ArgOffset;
4572           ArgOffset += 16;
4573         }
4574         needsLoad = true;
4575       }
4576       break;
4577     }
4578 
4579     // We need to load the argument to a virtual register if we determined above
4580     // that we ran out of physical registers of the appropriate type.
4581     if (needsLoad) {
4582       int FI = MFI.CreateFixedObject(ObjSize,
4583                                      CurArgOffset + (ArgSize - ObjSize),
4584                                      isImmutable);
4585       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4586       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4587     }
4588 
4589     InVals.push_back(ArgVal);
4590   }
4591 
4592   // Allow for Altivec parameters at the end, if needed.
4593   if (nAltivecParamsAtEnd) {
4594     MinReservedArea = ((MinReservedArea+15)/16)*16;
4595     MinReservedArea += 16*nAltivecParamsAtEnd;
4596   }
4597 
4598   // Area that is at least reserved in the caller of this function.
4599   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4600 
4601   // Set the size that is at least reserved in caller of this function.  Tail
4602   // call optimized functions' reserved stack space needs to be aligned so that
4603   // taking the difference between two stack areas will result in an aligned
4604   // stack.
4605   MinReservedArea =
4606       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4607   FuncInfo->setMinReservedArea(MinReservedArea);
4608 
4609   // If the function takes variable number of arguments, make a frame index for
4610   // the start of the first vararg value... for expansion of llvm.va_start.
4611   if (isVarArg) {
4612     int Depth = ArgOffset;
4613 
4614     FuncInfo->setVarArgsFrameIndex(
4615       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4616                             Depth, true));
4617     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4618 
4619     // If this function is vararg, store any remaining integer argument regs
4620     // to their spots on the stack so that they may be loaded by dereferencing
4621     // the result of va_next.
4622     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4623       unsigned VReg;
4624 
4625       if (isPPC64)
4626         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4627       else
4628         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4629 
4630       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4631       SDValue Store =
4632           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4633       MemOps.push_back(Store);
4634       // Increment the address by four for the next argument to store
4635       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4636       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4637     }
4638   }
4639 
4640   if (!MemOps.empty())
4641     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4642 
4643   return Chain;
4644 }
4645 
4646 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4647 /// adjusted to accommodate the arguments for the tailcall.
4648 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4649                                    unsigned ParamSize) {
4650 
4651   if (!isTailCall) return 0;
4652 
4653   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4654   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4655   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4656   // Remember only if the new adjustment is bigger.
4657   if (SPDiff < FI->getTailCallSPDelta())
4658     FI->setTailCallSPDelta(SPDiff);
4659 
4660   return SPDiff;
4661 }
4662 
4663 static bool isFunctionGlobalAddress(SDValue Callee);
4664 
4665 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4666                               const TargetMachine &TM) {
4667   // It does not make sense to call callsShareTOCBase() with a caller that
4668   // is PC Relative since PC Relative callers do not have a TOC.
4669 #ifndef NDEBUG
4670   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4671   assert(!STICaller->isUsingPCRelativeCalls() &&
4672          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4673 #endif
4674 
4675   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4676   // don't have enough information to determine if the caller and callee share
4677   // the same  TOC base, so we have to pessimistically assume they don't for
4678   // correctness.
4679   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4680   if (!G)
4681     return false;
4682 
4683   const GlobalValue *GV = G->getGlobal();
4684 
4685   // If the callee is preemptable, then the static linker will use a plt-stub
4686   // which saves the toc to the stack, and needs a nop after the call
4687   // instruction to convert to a toc-restore.
4688   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4689     return false;
4690 
4691   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4692   // We may need a TOC restore in the situation where the caller requires a
4693   // valid TOC but the callee is PC Relative and does not.
4694   const Function *F = dyn_cast<Function>(GV);
4695   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4696 
4697   // If we have an Alias we can try to get the function from there.
4698   if (Alias) {
4699     const GlobalObject *GlobalObj = Alias->getBaseObject();
4700     F = dyn_cast<Function>(GlobalObj);
4701   }
4702 
4703   // If we still have no valid function pointer we do not have enough
4704   // information to determine if the callee uses PC Relative calls so we must
4705   // assume that it does.
4706   if (!F)
4707     return false;
4708 
4709   // If the callee uses PC Relative we cannot guarantee that the callee won't
4710   // clobber the TOC of the caller and so we must assume that the two
4711   // functions do not share a TOC base.
4712   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4713   if (STICallee->isUsingPCRelativeCalls())
4714     return false;
4715 
4716   // The medium and large code models are expected to provide a sufficiently
4717   // large TOC to provide all data addressing needs of a module with a
4718   // single TOC.
4719   if (CodeModel::Medium == TM.getCodeModel() ||
4720       CodeModel::Large == TM.getCodeModel())
4721     return true;
4722 
4723   // Otherwise we need to ensure callee and caller are in the same section,
4724   // since the linker may allocate multiple TOCs, and we don't know which
4725   // sections will belong to the same TOC base.
4726   if (!GV->isStrongDefinitionForLinker())
4727     return false;
4728 
4729   // Any explicitly-specified sections and section prefixes must also match.
4730   // Also, if we're using -ffunction-sections, then each function is always in
4731   // a different section (the same is true for COMDAT functions).
4732   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4733       GV->getSection() != Caller->getSection())
4734     return false;
4735   if (const auto *F = dyn_cast<Function>(GV)) {
4736     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4737       return false;
4738   }
4739 
4740   return true;
4741 }
4742 
4743 static bool
4744 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4745                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4746   assert(Subtarget.is64BitELFABI());
4747 
4748   const unsigned PtrByteSize = 8;
4749   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4750 
4751   static const MCPhysReg GPR[] = {
4752     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4753     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4754   };
4755   static const MCPhysReg VR[] = {
4756     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4757     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4758   };
4759 
4760   const unsigned NumGPRs = array_lengthof(GPR);
4761   const unsigned NumFPRs = 13;
4762   const unsigned NumVRs = array_lengthof(VR);
4763   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4764 
4765   unsigned NumBytes = LinkageSize;
4766   unsigned AvailableFPRs = NumFPRs;
4767   unsigned AvailableVRs = NumVRs;
4768 
4769   for (const ISD::OutputArg& Param : Outs) {
4770     if (Param.Flags.isNest()) continue;
4771 
4772     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4773                                LinkageSize, ParamAreaSize, NumBytes,
4774                                AvailableFPRs, AvailableVRs))
4775       return true;
4776   }
4777   return false;
4778 }
4779 
4780 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4781   if (CB.arg_size() != CallerFn->arg_size())
4782     return false;
4783 
4784   auto CalleeArgIter = CB.arg_begin();
4785   auto CalleeArgEnd = CB.arg_end();
4786   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4787 
4788   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4789     const Value* CalleeArg = *CalleeArgIter;
4790     const Value* CallerArg = &(*CallerArgIter);
4791     if (CalleeArg == CallerArg)
4792       continue;
4793 
4794     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4795     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4796     //      }
4797     // 1st argument of callee is undef and has the same type as caller.
4798     if (CalleeArg->getType() == CallerArg->getType() &&
4799         isa<UndefValue>(CalleeArg))
4800       continue;
4801 
4802     return false;
4803   }
4804 
4805   return true;
4806 }
4807 
4808 // Returns true if TCO is possible between the callers and callees
4809 // calling conventions.
4810 static bool
4811 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4812                                     CallingConv::ID CalleeCC) {
4813   // Tail calls are possible with fastcc and ccc.
4814   auto isTailCallableCC  = [] (CallingConv::ID CC){
4815       return  CC == CallingConv::C || CC == CallingConv::Fast;
4816   };
4817   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4818     return false;
4819 
4820   // We can safely tail call both fastcc and ccc callees from a c calling
4821   // convention caller. If the caller is fastcc, we may have less stack space
4822   // than a non-fastcc caller with the same signature so disable tail-calls in
4823   // that case.
4824   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4825 }
4826 
4827 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4828     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4829     const SmallVectorImpl<ISD::OutputArg> &Outs,
4830     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4831   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4832 
4833   if (DisableSCO && !TailCallOpt) return false;
4834 
4835   // Variadic argument functions are not supported.
4836   if (isVarArg) return false;
4837 
4838   auto &Caller = DAG.getMachineFunction().getFunction();
4839   // Check that the calling conventions are compatible for tco.
4840   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4841     return false;
4842 
4843   // Caller contains any byval parameter is not supported.
4844   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4845     return false;
4846 
4847   // Callee contains any byval parameter is not supported, too.
4848   // Note: This is a quick work around, because in some cases, e.g.
4849   // caller's stack size > callee's stack size, we are still able to apply
4850   // sibling call optimization. For example, gcc is able to do SCO for caller1
4851   // in the following example, but not for caller2.
4852   //   struct test {
4853   //     long int a;
4854   //     char ary[56];
4855   //   } gTest;
4856   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4857   //     b->a = v.a;
4858   //     return 0;
4859   //   }
4860   //   void caller1(struct test a, struct test c, struct test *b) {
4861   //     callee(gTest, b); }
4862   //   void caller2(struct test *b) { callee(gTest, b); }
4863   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4864     return false;
4865 
4866   // If callee and caller use different calling conventions, we cannot pass
4867   // parameters on stack since offsets for the parameter area may be different.
4868   if (Caller.getCallingConv() != CalleeCC &&
4869       needStackSlotPassParameters(Subtarget, Outs))
4870     return false;
4871 
4872   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4873   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4874   // callee potentially have different TOC bases then we cannot tail call since
4875   // we need to restore the TOC pointer after the call.
4876   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4877   // We cannot guarantee this for indirect calls or calls to external functions.
4878   // When PC-Relative addressing is used, the concept of the TOC is no longer
4879   // applicable so this check is not required.
4880   // Check first for indirect calls.
4881   if (!Subtarget.isUsingPCRelativeCalls() &&
4882       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4883     return false;
4884 
4885   // Check if we share the TOC base.
4886   if (!Subtarget.isUsingPCRelativeCalls() &&
4887       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4888     return false;
4889 
4890   // TCO allows altering callee ABI, so we don't have to check further.
4891   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4892     return true;
4893 
4894   if (DisableSCO) return false;
4895 
4896   // If callee use the same argument list that caller is using, then we can
4897   // apply SCO on this case. If it is not, then we need to check if callee needs
4898   // stack for passing arguments.
4899   // PC Relative tail calls may not have a CallBase.
4900   // If there is no CallBase we cannot verify if we have the same argument
4901   // list so assume that we don't have the same argument list.
4902   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4903       needStackSlotPassParameters(Subtarget, Outs))
4904     return false;
4905   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4906     return false;
4907 
4908   return true;
4909 }
4910 
4911 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4912 /// for tail call optimization. Targets which want to do tail call
4913 /// optimization should implement this function.
4914 bool
4915 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4916                                                      CallingConv::ID CalleeCC,
4917                                                      bool isVarArg,
4918                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4919                                                      SelectionDAG& DAG) const {
4920   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4921     return false;
4922 
4923   // Variable argument functions are not supported.
4924   if (isVarArg)
4925     return false;
4926 
4927   MachineFunction &MF = DAG.getMachineFunction();
4928   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4929   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4930     // Functions containing by val parameters are not supported.
4931     for (unsigned i = 0; i != Ins.size(); i++) {
4932        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4933        if (Flags.isByVal()) return false;
4934     }
4935 
4936     // Non-PIC/GOT tail calls are supported.
4937     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4938       return true;
4939 
4940     // At the moment we can only do local tail calls (in same module, hidden
4941     // or protected) if we are generating PIC.
4942     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4943       return G->getGlobal()->hasHiddenVisibility()
4944           || G->getGlobal()->hasProtectedVisibility();
4945   }
4946 
4947   return false;
4948 }
4949 
4950 /// isCallCompatibleAddress - Return the immediate to use if the specified
4951 /// 32-bit value is representable in the immediate field of a BxA instruction.
4952 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4953   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4954   if (!C) return nullptr;
4955 
4956   int Addr = C->getZExtValue();
4957   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4958       SignExtend32<26>(Addr) != Addr)
4959     return nullptr;  // Top 6 bits have to be sext of immediate.
4960 
4961   return DAG
4962       .getConstant(
4963           (int)C->getZExtValue() >> 2, SDLoc(Op),
4964           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4965       .getNode();
4966 }
4967 
4968 namespace {
4969 
4970 struct TailCallArgumentInfo {
4971   SDValue Arg;
4972   SDValue FrameIdxOp;
4973   int FrameIdx = 0;
4974 
4975   TailCallArgumentInfo() = default;
4976 };
4977 
4978 } // end anonymous namespace
4979 
4980 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4981 static void StoreTailCallArgumentsToStackSlot(
4982     SelectionDAG &DAG, SDValue Chain,
4983     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4984     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4985   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4986     SDValue Arg = TailCallArgs[i].Arg;
4987     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4988     int FI = TailCallArgs[i].FrameIdx;
4989     // Store relative to framepointer.
4990     MemOpChains.push_back(DAG.getStore(
4991         Chain, dl, Arg, FIN,
4992         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4993   }
4994 }
4995 
4996 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4997 /// the appropriate stack slot for the tail call optimized function call.
4998 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4999                                              SDValue OldRetAddr, SDValue OldFP,
5000                                              int SPDiff, const SDLoc &dl) {
5001   if (SPDiff) {
5002     // Calculate the new stack slot for the return address.
5003     MachineFunction &MF = DAG.getMachineFunction();
5004     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5005     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5006     bool isPPC64 = Subtarget.isPPC64();
5007     int SlotSize = isPPC64 ? 8 : 4;
5008     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5009     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5010                                                          NewRetAddrLoc, true);
5011     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5012     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5013     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5014                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5015   }
5016   return Chain;
5017 }
5018 
5019 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5020 /// the position of the argument.
5021 static void
5022 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5023                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5024                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5025   int Offset = ArgOffset + SPDiff;
5026   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5027   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5028   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5029   SDValue FIN = DAG.getFrameIndex(FI, VT);
5030   TailCallArgumentInfo Info;
5031   Info.Arg = Arg;
5032   Info.FrameIdxOp = FIN;
5033   Info.FrameIdx = FI;
5034   TailCallArguments.push_back(Info);
5035 }
5036 
5037 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5038 /// stack slot. Returns the chain as result and the loaded frame pointers in
5039 /// LROpOut/FPOpout. Used when tail calling.
5040 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5041     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5042     SDValue &FPOpOut, const SDLoc &dl) const {
5043   if (SPDiff) {
5044     // Load the LR and FP stack slot for later adjusting.
5045     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5046     LROpOut = getReturnAddrFrameIndex(DAG);
5047     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5048     Chain = SDValue(LROpOut.getNode(), 1);
5049   }
5050   return Chain;
5051 }
5052 
5053 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5054 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5055 /// specified by the specific parameter attribute. The copy will be passed as
5056 /// a byval function parameter.
5057 /// Sometimes what we are copying is the end of a larger object, the part that
5058 /// does not fit in registers.
5059 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5060                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5061                                          SelectionDAG &DAG, const SDLoc &dl) {
5062   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5063   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5064                        Flags.getNonZeroByValAlign(), false, false, false,
5065                        MachinePointerInfo(), MachinePointerInfo());
5066 }
5067 
5068 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5069 /// tail calls.
5070 static void LowerMemOpCallTo(
5071     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5072     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5073     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5074     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5075   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5076   if (!isTailCall) {
5077     if (isVector) {
5078       SDValue StackPtr;
5079       if (isPPC64)
5080         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5081       else
5082         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5083       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5084                            DAG.getConstant(ArgOffset, dl, PtrVT));
5085     }
5086     MemOpChains.push_back(
5087         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5088     // Calculate and remember argument location.
5089   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5090                                   TailCallArguments);
5091 }
5092 
5093 static void
5094 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5095                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5096                 SDValue FPOp,
5097                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5098   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5099   // might overwrite each other in case of tail call optimization.
5100   SmallVector<SDValue, 8> MemOpChains2;
5101   // Do not flag preceding copytoreg stuff together with the following stuff.
5102   InFlag = SDValue();
5103   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5104                                     MemOpChains2, dl);
5105   if (!MemOpChains2.empty())
5106     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5107 
5108   // Store the return address to the appropriate stack slot.
5109   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5110 
5111   // Emit callseq_end just before tailcall node.
5112   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5113                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5114   InFlag = Chain.getValue(1);
5115 }
5116 
5117 // Is this global address that of a function that can be called by name? (as
5118 // opposed to something that must hold a descriptor for an indirect call).
5119 static bool isFunctionGlobalAddress(SDValue Callee) {
5120   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5121     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5122         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5123       return false;
5124 
5125     return G->getGlobal()->getValueType()->isFunctionTy();
5126   }
5127 
5128   return false;
5129 }
5130 
5131 SDValue PPCTargetLowering::LowerCallResult(
5132     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5133     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5134     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5135   SmallVector<CCValAssign, 16> RVLocs;
5136   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5137                     *DAG.getContext());
5138 
5139   CCRetInfo.AnalyzeCallResult(
5140       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5141                ? RetCC_PPC_Cold
5142                : RetCC_PPC);
5143 
5144   // Copy all of the result registers out of their specified physreg.
5145   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5146     CCValAssign &VA = RVLocs[i];
5147     assert(VA.isRegLoc() && "Can only return in registers!");
5148 
5149     SDValue Val;
5150 
5151     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5152       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5153                                       InFlag);
5154       Chain = Lo.getValue(1);
5155       InFlag = Lo.getValue(2);
5156       VA = RVLocs[++i]; // skip ahead to next loc
5157       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5158                                       InFlag);
5159       Chain = Hi.getValue(1);
5160       InFlag = Hi.getValue(2);
5161       if (!Subtarget.isLittleEndian())
5162         std::swap (Lo, Hi);
5163       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5164     } else {
5165       Val = DAG.getCopyFromReg(Chain, dl,
5166                                VA.getLocReg(), VA.getLocVT(), InFlag);
5167       Chain = Val.getValue(1);
5168       InFlag = Val.getValue(2);
5169     }
5170 
5171     switch (VA.getLocInfo()) {
5172     default: llvm_unreachable("Unknown loc info!");
5173     case CCValAssign::Full: break;
5174     case CCValAssign::AExt:
5175       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5176       break;
5177     case CCValAssign::ZExt:
5178       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5179                         DAG.getValueType(VA.getValVT()));
5180       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5181       break;
5182     case CCValAssign::SExt:
5183       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5184                         DAG.getValueType(VA.getValVT()));
5185       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5186       break;
5187     }
5188 
5189     InVals.push_back(Val);
5190   }
5191 
5192   return Chain;
5193 }
5194 
5195 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5196                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5197   // PatchPoint calls are not indirect.
5198   if (isPatchPoint)
5199     return false;
5200 
5201   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5202     return false;
5203 
5204   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5205   // becuase the immediate function pointer points to a descriptor instead of
5206   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5207   // pointer immediate points to the global entry point, while the BLA would
5208   // need to jump to the local entry point (see rL211174).
5209   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5210       isBLACompatibleAddress(Callee, DAG))
5211     return false;
5212 
5213   return true;
5214 }
5215 
5216 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5217 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5218   return Subtarget.isAIXABI() ||
5219          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5220 }
5221 
5222 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5223                               const Function &Caller,
5224                               const SDValue &Callee,
5225                               const PPCSubtarget &Subtarget,
5226                               const TargetMachine &TM) {
5227   if (CFlags.IsTailCall)
5228     return PPCISD::TC_RETURN;
5229 
5230   // This is a call through a function pointer.
5231   if (CFlags.IsIndirect) {
5232     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5233     // indirect calls. The save of the caller's TOC pointer to the stack will be
5234     // inserted into the DAG as part of call lowering. The restore of the TOC
5235     // pointer is modeled by using a pseudo instruction for the call opcode that
5236     // represents the 2 instruction sequence of an indirect branch and link,
5237     // immediately followed by a load of the TOC pointer from the the stack save
5238     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5239     // as it is not saved or used.
5240     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5241                                                : PPCISD::BCTRL;
5242   }
5243 
5244   if (Subtarget.isUsingPCRelativeCalls()) {
5245     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5246     return PPCISD::CALL_NOTOC;
5247   }
5248 
5249   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5250   // immediately following the call instruction if the caller and callee may
5251   // have different TOC bases. At link time if the linker determines the calls
5252   // may not share a TOC base, the call is redirected to a trampoline inserted
5253   // by the linker. The trampoline will (among other things) save the callers
5254   // TOC pointer at an ABI designated offset in the linkage area and the linker
5255   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5256   // into gpr2.
5257   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5258     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5259                                                   : PPCISD::CALL_NOP;
5260 
5261   return PPCISD::CALL;
5262 }
5263 
5264 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5265                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5266   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5267     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5268       return SDValue(Dest, 0);
5269 
5270   // Returns true if the callee is local, and false otherwise.
5271   auto isLocalCallee = [&]() {
5272     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5273     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5274     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5275 
5276     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5277            !dyn_cast_or_null<GlobalIFunc>(GV);
5278   };
5279 
5280   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5281   // a static relocation model causes some versions of GNU LD (2.17.50, at
5282   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5283   // built with secure-PLT.
5284   bool UsePlt =
5285       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5286       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5287 
5288   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5289     const TargetMachine &TM = Subtarget.getTargetMachine();
5290     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5291     MCSymbolXCOFF *S =
5292         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5293 
5294     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5295     return DAG.getMCSymbol(S, PtrVT);
5296   };
5297 
5298   if (isFunctionGlobalAddress(Callee)) {
5299     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5300 
5301     if (Subtarget.isAIXABI()) {
5302       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5303       return getAIXFuncEntryPointSymbolSDNode(GV);
5304     }
5305     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5306                                       UsePlt ? PPCII::MO_PLT : 0);
5307   }
5308 
5309   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5310     const char *SymName = S->getSymbol();
5311     if (Subtarget.isAIXABI()) {
5312       // If there exists a user-declared function whose name is the same as the
5313       // ExternalSymbol's, then we pick up the user-declared version.
5314       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5315       if (const Function *F =
5316               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5317         return getAIXFuncEntryPointSymbolSDNode(F);
5318 
5319       // On AIX, direct function calls reference the symbol for the function's
5320       // entry point, which is named by prepending a "." before the function's
5321       // C-linkage name. A Qualname is returned here because an external
5322       // function entry point is a csect with XTY_ER property.
5323       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5324         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5325         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5326             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5327             SectionKind::getMetadata());
5328         return Sec->getQualNameSymbol();
5329       };
5330 
5331       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5332     }
5333     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5334                                        UsePlt ? PPCII::MO_PLT : 0);
5335   }
5336 
5337   // No transformation needed.
5338   assert(Callee.getNode() && "What no callee?");
5339   return Callee;
5340 }
5341 
5342 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5343   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5344          "Expected a CALLSEQ_STARTSDNode.");
5345 
5346   // The last operand is the chain, except when the node has glue. If the node
5347   // has glue, then the last operand is the glue, and the chain is the second
5348   // last operand.
5349   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5350   if (LastValue.getValueType() != MVT::Glue)
5351     return LastValue;
5352 
5353   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5354 }
5355 
5356 // Creates the node that moves a functions address into the count register
5357 // to prepare for an indirect call instruction.
5358 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5359                                 SDValue &Glue, SDValue &Chain,
5360                                 const SDLoc &dl) {
5361   SDValue MTCTROps[] = {Chain, Callee, Glue};
5362   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5363   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5364                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5365   // The glue is the second value produced.
5366   Glue = Chain.getValue(1);
5367 }
5368 
5369 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5370                                           SDValue &Glue, SDValue &Chain,
5371                                           SDValue CallSeqStart,
5372                                           const CallBase *CB, const SDLoc &dl,
5373                                           bool hasNest,
5374                                           const PPCSubtarget &Subtarget) {
5375   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5376   // entry point, but to the function descriptor (the function entry point
5377   // address is part of the function descriptor though).
5378   // The function descriptor is a three doubleword structure with the
5379   // following fields: function entry point, TOC base address and
5380   // environment pointer.
5381   // Thus for a call through a function pointer, the following actions need
5382   // to be performed:
5383   //   1. Save the TOC of the caller in the TOC save area of its stack
5384   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5385   //   2. Load the address of the function entry point from the function
5386   //      descriptor.
5387   //   3. Load the TOC of the callee from the function descriptor into r2.
5388   //   4. Load the environment pointer from the function descriptor into
5389   //      r11.
5390   //   5. Branch to the function entry point address.
5391   //   6. On return of the callee, the TOC of the caller needs to be
5392   //      restored (this is done in FinishCall()).
5393   //
5394   // The loads are scheduled at the beginning of the call sequence, and the
5395   // register copies are flagged together to ensure that no other
5396   // operations can be scheduled in between. E.g. without flagging the
5397   // copies together, a TOC access in the caller could be scheduled between
5398   // the assignment of the callee TOC and the branch to the callee, which leads
5399   // to incorrect code.
5400 
5401   // Start by loading the function address from the descriptor.
5402   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5403   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5404                       ? (MachineMemOperand::MODereferenceable |
5405                          MachineMemOperand::MOInvariant)
5406                       : MachineMemOperand::MONone;
5407 
5408   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5409 
5410   // Registers used in building the DAG.
5411   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5412   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5413 
5414   // Offsets of descriptor members.
5415   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5416   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5417 
5418   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5419   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5420 
5421   // One load for the functions entry point address.
5422   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5423                                     Alignment, MMOFlags);
5424 
5425   // One for loading the TOC anchor for the module that contains the called
5426   // function.
5427   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5428   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5429   SDValue TOCPtr =
5430       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5431                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5432 
5433   // One for loading the environment pointer.
5434   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5435   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5436   SDValue LoadEnvPtr =
5437       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5438                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5439 
5440 
5441   // Then copy the newly loaded TOC anchor to the TOC pointer.
5442   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5443   Chain = TOCVal.getValue(0);
5444   Glue = TOCVal.getValue(1);
5445 
5446   // If the function call has an explicit 'nest' parameter, it takes the
5447   // place of the environment pointer.
5448   assert((!hasNest || !Subtarget.isAIXABI()) &&
5449          "Nest parameter is not supported on AIX.");
5450   if (!hasNest) {
5451     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5452     Chain = EnvVal.getValue(0);
5453     Glue = EnvVal.getValue(1);
5454   }
5455 
5456   // The rest of the indirect call sequence is the same as the non-descriptor
5457   // DAG.
5458   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5459 }
5460 
5461 static void
5462 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5463                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5464                   SelectionDAG &DAG,
5465                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5466                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5467                   const PPCSubtarget &Subtarget) {
5468   const bool IsPPC64 = Subtarget.isPPC64();
5469   // MVT for a general purpose register.
5470   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5471 
5472   // First operand is always the chain.
5473   Ops.push_back(Chain);
5474 
5475   // If it's a direct call pass the callee as the second operand.
5476   if (!CFlags.IsIndirect)
5477     Ops.push_back(Callee);
5478   else {
5479     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5480 
5481     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5482     // on the stack (this would have been done in `LowerCall_64SVR4` or
5483     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5484     // represents both the indirect branch and a load that restores the TOC
5485     // pointer from the linkage area. The operand for the TOC restore is an add
5486     // of the TOC save offset to the stack pointer. This must be the second
5487     // operand: after the chain input but before any other variadic arguments.
5488     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5489     // saved or used.
5490     if (isTOCSaveRestoreRequired(Subtarget)) {
5491       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5492 
5493       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5494       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5495       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5496       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5497       Ops.push_back(AddTOC);
5498     }
5499 
5500     // Add the register used for the environment pointer.
5501     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5502       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5503                                     RegVT));
5504 
5505 
5506     // Add CTR register as callee so a bctr can be emitted later.
5507     if (CFlags.IsTailCall)
5508       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5509   }
5510 
5511   // If this is a tail call add stack pointer delta.
5512   if (CFlags.IsTailCall)
5513     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5514 
5515   // Add argument registers to the end of the list so that they are known live
5516   // into the call.
5517   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5518     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5519                                   RegsToPass[i].second.getValueType()));
5520 
5521   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5522   // no way to mark dependencies as implicit here.
5523   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5524   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5525        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5526     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5527 
5528   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5529   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5530     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5531 
5532   // Add a register mask operand representing the call-preserved registers.
5533   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5534   const uint32_t *Mask =
5535       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5536   assert(Mask && "Missing call preserved mask for calling convention");
5537   Ops.push_back(DAG.getRegisterMask(Mask));
5538 
5539   // If the glue is valid, it is the last operand.
5540   if (Glue.getNode())
5541     Ops.push_back(Glue);
5542 }
5543 
5544 SDValue PPCTargetLowering::FinishCall(
5545     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5546     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5547     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5548     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5549     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5550 
5551   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5552       Subtarget.isAIXABI())
5553     setUsesTOCBasePtr(DAG);
5554 
5555   unsigned CallOpc =
5556       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5557                     Subtarget, DAG.getTarget());
5558 
5559   if (!CFlags.IsIndirect)
5560     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5561   else if (Subtarget.usesFunctionDescriptors())
5562     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5563                                   dl, CFlags.HasNest, Subtarget);
5564   else
5565     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5566 
5567   // Build the operand list for the call instruction.
5568   SmallVector<SDValue, 8> Ops;
5569   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5570                     SPDiff, Subtarget);
5571 
5572   // Emit tail call.
5573   if (CFlags.IsTailCall) {
5574     // Indirect tail call when using PC Relative calls do not have the same
5575     // constraints.
5576     assert(((Callee.getOpcode() == ISD::Register &&
5577              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5578             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5579             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5580             isa<ConstantSDNode>(Callee) ||
5581             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5582            "Expecting a global address, external symbol, absolute value, "
5583            "register or an indirect tail call when PC Relative calls are "
5584            "used.");
5585     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5586     assert(CallOpc == PPCISD::TC_RETURN &&
5587            "Unexpected call opcode for a tail call.");
5588     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5589     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5590   }
5591 
5592   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5593   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5594   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5595   Glue = Chain.getValue(1);
5596 
5597   // When performing tail call optimization the callee pops its arguments off
5598   // the stack. Account for this here so these bytes can be pushed back on in
5599   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5600   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5601                          getTargetMachine().Options.GuaranteedTailCallOpt)
5602                             ? NumBytes
5603                             : 0;
5604 
5605   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5606                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5607                              Glue, dl);
5608   Glue = Chain.getValue(1);
5609 
5610   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5611                          DAG, InVals);
5612 }
5613 
5614 SDValue
5615 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5616                              SmallVectorImpl<SDValue> &InVals) const {
5617   SelectionDAG &DAG                     = CLI.DAG;
5618   SDLoc &dl                             = CLI.DL;
5619   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5620   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5621   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5622   SDValue Chain                         = CLI.Chain;
5623   SDValue Callee                        = CLI.Callee;
5624   bool &isTailCall                      = CLI.IsTailCall;
5625   CallingConv::ID CallConv              = CLI.CallConv;
5626   bool isVarArg                         = CLI.IsVarArg;
5627   bool isPatchPoint                     = CLI.IsPatchPoint;
5628   const CallBase *CB                    = CLI.CB;
5629 
5630   if (isTailCall) {
5631     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5632       isTailCall = false;
5633     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5634       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5635           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5636     else
5637       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5638                                                      Ins, DAG);
5639     if (isTailCall) {
5640       ++NumTailCalls;
5641       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5642         ++NumSiblingCalls;
5643 
5644       // PC Relative calls no longer guarantee that the callee is a Global
5645       // Address Node. The callee could be an indirect tail call in which
5646       // case the SDValue for the callee could be a load (to load the address
5647       // of a function pointer) or it may be a register copy (to move the
5648       // address of the callee from a function parameter into a virtual
5649       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5650       assert((Subtarget.isUsingPCRelativeCalls() ||
5651               isa<GlobalAddressSDNode>(Callee)) &&
5652              "Callee should be an llvm::Function object.");
5653 
5654       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5655                         << "\nTCO callee: ");
5656       LLVM_DEBUG(Callee.dump());
5657     }
5658   }
5659 
5660   if (!isTailCall && CB && CB->isMustTailCall())
5661     report_fatal_error("failed to perform tail call elimination on a call "
5662                        "site marked musttail");
5663 
5664   // When long calls (i.e. indirect calls) are always used, calls are always
5665   // made via function pointer. If we have a function name, first translate it
5666   // into a pointer.
5667   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5668       !isTailCall)
5669     Callee = LowerGlobalAddress(Callee, DAG);
5670 
5671   CallFlags CFlags(
5672       CallConv, isTailCall, isVarArg, isPatchPoint,
5673       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5674       // hasNest
5675       Subtarget.is64BitELFABI() &&
5676           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5677       CLI.NoMerge);
5678 
5679   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5680     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5681                             InVals, CB);
5682 
5683   if (Subtarget.isSVR4ABI())
5684     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5685                             InVals, CB);
5686 
5687   if (Subtarget.isAIXABI())
5688     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5689                          InVals, CB);
5690 
5691   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5692                           InVals, CB);
5693 }
5694 
5695 SDValue PPCTargetLowering::LowerCall_32SVR4(
5696     SDValue Chain, SDValue Callee, CallFlags CFlags,
5697     const SmallVectorImpl<ISD::OutputArg> &Outs,
5698     const SmallVectorImpl<SDValue> &OutVals,
5699     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5700     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5701     const CallBase *CB) const {
5702   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5703   // of the 32-bit SVR4 ABI stack frame layout.
5704 
5705   const CallingConv::ID CallConv = CFlags.CallConv;
5706   const bool IsVarArg = CFlags.IsVarArg;
5707   const bool IsTailCall = CFlags.IsTailCall;
5708 
5709   assert((CallConv == CallingConv::C ||
5710           CallConv == CallingConv::Cold ||
5711           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5712 
5713   const Align PtrAlign(4);
5714 
5715   MachineFunction &MF = DAG.getMachineFunction();
5716 
5717   // Mark this function as potentially containing a function that contains a
5718   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5719   // and restoring the callers stack pointer in this functions epilog. This is
5720   // done because by tail calling the called function might overwrite the value
5721   // in this function's (MF) stack pointer stack slot 0(SP).
5722   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5723       CallConv == CallingConv::Fast)
5724     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5725 
5726   // Count how many bytes are to be pushed on the stack, including the linkage
5727   // area, parameter list area and the part of the local variable space which
5728   // contains copies of aggregates which are passed by value.
5729 
5730   // Assign locations to all of the outgoing arguments.
5731   SmallVector<CCValAssign, 16> ArgLocs;
5732   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5733 
5734   // Reserve space for the linkage area on the stack.
5735   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5736                        PtrAlign);
5737   if (useSoftFloat())
5738     CCInfo.PreAnalyzeCallOperands(Outs);
5739 
5740   if (IsVarArg) {
5741     // Handle fixed and variable vector arguments differently.
5742     // Fixed vector arguments go into registers as long as registers are
5743     // available. Variable vector arguments always go into memory.
5744     unsigned NumArgs = Outs.size();
5745 
5746     for (unsigned i = 0; i != NumArgs; ++i) {
5747       MVT ArgVT = Outs[i].VT;
5748       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5749       bool Result;
5750 
5751       if (Outs[i].IsFixed) {
5752         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5753                                CCInfo);
5754       } else {
5755         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5756                                       ArgFlags, CCInfo);
5757       }
5758 
5759       if (Result) {
5760 #ifndef NDEBUG
5761         errs() << "Call operand #" << i << " has unhandled type "
5762              << EVT(ArgVT).getEVTString() << "\n";
5763 #endif
5764         llvm_unreachable(nullptr);
5765       }
5766     }
5767   } else {
5768     // All arguments are treated the same.
5769     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5770   }
5771   CCInfo.clearWasPPCF128();
5772 
5773   // Assign locations to all of the outgoing aggregate by value arguments.
5774   SmallVector<CCValAssign, 16> ByValArgLocs;
5775   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5776 
5777   // Reserve stack space for the allocations in CCInfo.
5778   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5779 
5780   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5781 
5782   // Size of the linkage area, parameter list area and the part of the local
5783   // space variable where copies of aggregates which are passed by value are
5784   // stored.
5785   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5786 
5787   // Calculate by how many bytes the stack has to be adjusted in case of tail
5788   // call optimization.
5789   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5790 
5791   // Adjust the stack pointer for the new arguments...
5792   // These operations are automatically eliminated by the prolog/epilog pass
5793   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5794   SDValue CallSeqStart = Chain;
5795 
5796   // Load the return address and frame pointer so it can be moved somewhere else
5797   // later.
5798   SDValue LROp, FPOp;
5799   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5800 
5801   // Set up a copy of the stack pointer for use loading and storing any
5802   // arguments that may not fit in the registers available for argument
5803   // passing.
5804   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5805 
5806   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5807   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5808   SmallVector<SDValue, 8> MemOpChains;
5809 
5810   bool seenFloatArg = false;
5811   // Walk the register/memloc assignments, inserting copies/loads.
5812   // i - Tracks the index into the list of registers allocated for the call
5813   // RealArgIdx - Tracks the index into the list of actual function arguments
5814   // j - Tracks the index into the list of byval arguments
5815   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5816        i != e;
5817        ++i, ++RealArgIdx) {
5818     CCValAssign &VA = ArgLocs[i];
5819     SDValue Arg = OutVals[RealArgIdx];
5820     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5821 
5822     if (Flags.isByVal()) {
5823       // Argument is an aggregate which is passed by value, thus we need to
5824       // create a copy of it in the local variable space of the current stack
5825       // frame (which is the stack frame of the caller) and pass the address of
5826       // this copy to the callee.
5827       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5828       CCValAssign &ByValVA = ByValArgLocs[j++];
5829       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5830 
5831       // Memory reserved in the local variable space of the callers stack frame.
5832       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5833 
5834       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5835       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5836                            StackPtr, PtrOff);
5837 
5838       // Create a copy of the argument in the local area of the current
5839       // stack frame.
5840       SDValue MemcpyCall =
5841         CreateCopyOfByValArgument(Arg, PtrOff,
5842                                   CallSeqStart.getNode()->getOperand(0),
5843                                   Flags, DAG, dl);
5844 
5845       // This must go outside the CALLSEQ_START..END.
5846       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5847                                                      SDLoc(MemcpyCall));
5848       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5849                              NewCallSeqStart.getNode());
5850       Chain = CallSeqStart = NewCallSeqStart;
5851 
5852       // Pass the address of the aggregate copy on the stack either in a
5853       // physical register or in the parameter list area of the current stack
5854       // frame to the callee.
5855       Arg = PtrOff;
5856     }
5857 
5858     // When useCRBits() is true, there can be i1 arguments.
5859     // It is because getRegisterType(MVT::i1) => MVT::i1,
5860     // and for other integer types getRegisterType() => MVT::i32.
5861     // Extend i1 and ensure callee will get i32.
5862     if (Arg.getValueType() == MVT::i1)
5863       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5864                         dl, MVT::i32, Arg);
5865 
5866     if (VA.isRegLoc()) {
5867       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5868       // Put argument in a physical register.
5869       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5870         bool IsLE = Subtarget.isLittleEndian();
5871         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5872                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5873         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5874         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5875                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5876         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5877                              SVal.getValue(0)));
5878       } else
5879         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5880     } else {
5881       // Put argument in the parameter list area of the current stack frame.
5882       assert(VA.isMemLoc());
5883       unsigned LocMemOffset = VA.getLocMemOffset();
5884 
5885       if (!IsTailCall) {
5886         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5887         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5888                              StackPtr, PtrOff);
5889 
5890         MemOpChains.push_back(
5891             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5892       } else {
5893         // Calculate and remember argument location.
5894         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5895                                  TailCallArguments);
5896       }
5897     }
5898   }
5899 
5900   if (!MemOpChains.empty())
5901     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5902 
5903   // Build a sequence of copy-to-reg nodes chained together with token chain
5904   // and flag operands which copy the outgoing args into the appropriate regs.
5905   SDValue InFlag;
5906   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5907     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5908                              RegsToPass[i].second, InFlag);
5909     InFlag = Chain.getValue(1);
5910   }
5911 
5912   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5913   // registers.
5914   if (IsVarArg) {
5915     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5916     SDValue Ops[] = { Chain, InFlag };
5917 
5918     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5919                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5920 
5921     InFlag = Chain.getValue(1);
5922   }
5923 
5924   if (IsTailCall)
5925     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5926                     TailCallArguments);
5927 
5928   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5929                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5930 }
5931 
5932 // Copy an argument into memory, being careful to do this outside the
5933 // call sequence for the call to which the argument belongs.
5934 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5935     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5936     SelectionDAG &DAG, const SDLoc &dl) const {
5937   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5938                         CallSeqStart.getNode()->getOperand(0),
5939                         Flags, DAG, dl);
5940   // The MEMCPY must go outside the CALLSEQ_START..END.
5941   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5942   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5943                                                  SDLoc(MemcpyCall));
5944   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5945                          NewCallSeqStart.getNode());
5946   return NewCallSeqStart;
5947 }
5948 
5949 SDValue PPCTargetLowering::LowerCall_64SVR4(
5950     SDValue Chain, SDValue Callee, CallFlags CFlags,
5951     const SmallVectorImpl<ISD::OutputArg> &Outs,
5952     const SmallVectorImpl<SDValue> &OutVals,
5953     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5954     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5955     const CallBase *CB) const {
5956   bool isELFv2ABI = Subtarget.isELFv2ABI();
5957   bool isLittleEndian = Subtarget.isLittleEndian();
5958   unsigned NumOps = Outs.size();
5959   bool IsSibCall = false;
5960   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5961 
5962   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5963   unsigned PtrByteSize = 8;
5964 
5965   MachineFunction &MF = DAG.getMachineFunction();
5966 
5967   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5968     IsSibCall = true;
5969 
5970   // Mark this function as potentially containing a function that contains a
5971   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5972   // and restoring the callers stack pointer in this functions epilog. This is
5973   // done because by tail calling the called function might overwrite the value
5974   // in this function's (MF) stack pointer stack slot 0(SP).
5975   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5976     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5977 
5978   assert(!(IsFastCall && CFlags.IsVarArg) &&
5979          "fastcc not supported on varargs functions");
5980 
5981   // Count how many bytes are to be pushed on the stack, including the linkage
5982   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5983   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5984   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5985   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5986   unsigned NumBytes = LinkageSize;
5987   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5988 
5989   static const MCPhysReg GPR[] = {
5990     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5991     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5992   };
5993   static const MCPhysReg VR[] = {
5994     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5995     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5996   };
5997 
5998   const unsigned NumGPRs = array_lengthof(GPR);
5999   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6000   const unsigned NumVRs  = array_lengthof(VR);
6001 
6002   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6003   // can be passed to the callee in registers.
6004   // For the fast calling convention, there is another check below.
6005   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6006   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6007   if (!HasParameterArea) {
6008     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6009     unsigned AvailableFPRs = NumFPRs;
6010     unsigned AvailableVRs = NumVRs;
6011     unsigned NumBytesTmp = NumBytes;
6012     for (unsigned i = 0; i != NumOps; ++i) {
6013       if (Outs[i].Flags.isNest()) continue;
6014       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6015                                  PtrByteSize, LinkageSize, ParamAreaSize,
6016                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6017         HasParameterArea = true;
6018     }
6019   }
6020 
6021   // When using the fast calling convention, we don't provide backing for
6022   // arguments that will be in registers.
6023   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6024 
6025   // Avoid allocating parameter area for fastcc functions if all the arguments
6026   // can be passed in the registers.
6027   if (IsFastCall)
6028     HasParameterArea = false;
6029 
6030   // Add up all the space actually used.
6031   for (unsigned i = 0; i != NumOps; ++i) {
6032     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6033     EVT ArgVT = Outs[i].VT;
6034     EVT OrigVT = Outs[i].ArgVT;
6035 
6036     if (Flags.isNest())
6037       continue;
6038 
6039     if (IsFastCall) {
6040       if (Flags.isByVal()) {
6041         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6042         if (NumGPRsUsed > NumGPRs)
6043           HasParameterArea = true;
6044       } else {
6045         switch (ArgVT.getSimpleVT().SimpleTy) {
6046         default: llvm_unreachable("Unexpected ValueType for argument!");
6047         case MVT::i1:
6048         case MVT::i32:
6049         case MVT::i64:
6050           if (++NumGPRsUsed <= NumGPRs)
6051             continue;
6052           break;
6053         case MVT::v4i32:
6054         case MVT::v8i16:
6055         case MVT::v16i8:
6056         case MVT::v2f64:
6057         case MVT::v2i64:
6058         case MVT::v1i128:
6059         case MVT::f128:
6060           if (++NumVRsUsed <= NumVRs)
6061             continue;
6062           break;
6063         case MVT::v4f32:
6064           if (++NumVRsUsed <= NumVRs)
6065             continue;
6066           break;
6067         case MVT::f32:
6068         case MVT::f64:
6069           if (++NumFPRsUsed <= NumFPRs)
6070             continue;
6071           break;
6072         }
6073         HasParameterArea = true;
6074       }
6075     }
6076 
6077     /* Respect alignment of argument on the stack.  */
6078     auto Alignement =
6079         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6080     NumBytes = alignTo(NumBytes, Alignement);
6081 
6082     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6083     if (Flags.isInConsecutiveRegsLast())
6084       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6085   }
6086 
6087   unsigned NumBytesActuallyUsed = NumBytes;
6088 
6089   // In the old ELFv1 ABI,
6090   // the prolog code of the callee may store up to 8 GPR argument registers to
6091   // the stack, allowing va_start to index over them in memory if its varargs.
6092   // Because we cannot tell if this is needed on the caller side, we have to
6093   // conservatively assume that it is needed.  As such, make sure we have at
6094   // least enough stack space for the caller to store the 8 GPRs.
6095   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6096   // really requires memory operands, e.g. a vararg function.
6097   if (HasParameterArea)
6098     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6099   else
6100     NumBytes = LinkageSize;
6101 
6102   // Tail call needs the stack to be aligned.
6103   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6104     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6105 
6106   int SPDiff = 0;
6107 
6108   // Calculate by how many bytes the stack has to be adjusted in case of tail
6109   // call optimization.
6110   if (!IsSibCall)
6111     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6112 
6113   // To protect arguments on the stack from being clobbered in a tail call,
6114   // force all the loads to happen before doing any other lowering.
6115   if (CFlags.IsTailCall)
6116     Chain = DAG.getStackArgumentTokenFactor(Chain);
6117 
6118   // Adjust the stack pointer for the new arguments...
6119   // These operations are automatically eliminated by the prolog/epilog pass
6120   if (!IsSibCall)
6121     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6122   SDValue CallSeqStart = Chain;
6123 
6124   // Load the return address and frame pointer so it can be move somewhere else
6125   // later.
6126   SDValue LROp, FPOp;
6127   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6128 
6129   // Set up a copy of the stack pointer for use loading and storing any
6130   // arguments that may not fit in the registers available for argument
6131   // passing.
6132   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6133 
6134   // Figure out which arguments are going to go in registers, and which in
6135   // memory.  Also, if this is a vararg function, floating point operations
6136   // must be stored to our stack, and loaded into integer regs as well, if
6137   // any integer regs are available for argument passing.
6138   unsigned ArgOffset = LinkageSize;
6139 
6140   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6141   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6142 
6143   SmallVector<SDValue, 8> MemOpChains;
6144   for (unsigned i = 0; i != NumOps; ++i) {
6145     SDValue Arg = OutVals[i];
6146     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6147     EVT ArgVT = Outs[i].VT;
6148     EVT OrigVT = Outs[i].ArgVT;
6149 
6150     // PtrOff will be used to store the current argument to the stack if a
6151     // register cannot be found for it.
6152     SDValue PtrOff;
6153 
6154     // We re-align the argument offset for each argument, except when using the
6155     // fast calling convention, when we need to make sure we do that only when
6156     // we'll actually use a stack slot.
6157     auto ComputePtrOff = [&]() {
6158       /* Respect alignment of argument on the stack.  */
6159       auto Alignment =
6160           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6161       ArgOffset = alignTo(ArgOffset, Alignment);
6162 
6163       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6164 
6165       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6166     };
6167 
6168     if (!IsFastCall) {
6169       ComputePtrOff();
6170 
6171       /* Compute GPR index associated with argument offset.  */
6172       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6173       GPR_idx = std::min(GPR_idx, NumGPRs);
6174     }
6175 
6176     // Promote integers to 64-bit values.
6177     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6178       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6179       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6180       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6181     }
6182 
6183     // FIXME memcpy is used way more than necessary.  Correctness first.
6184     // Note: "by value" is code for passing a structure by value, not
6185     // basic types.
6186     if (Flags.isByVal()) {
6187       // Note: Size includes alignment padding, so
6188       //   struct x { short a; char b; }
6189       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6190       // These are the proper values we need for right-justifying the
6191       // aggregate in a parameter register.
6192       unsigned Size = Flags.getByValSize();
6193 
6194       // An empty aggregate parameter takes up no storage and no
6195       // registers.
6196       if (Size == 0)
6197         continue;
6198 
6199       if (IsFastCall)
6200         ComputePtrOff();
6201 
6202       // All aggregates smaller than 8 bytes must be passed right-justified.
6203       if (Size==1 || Size==2 || Size==4) {
6204         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6205         if (GPR_idx != NumGPRs) {
6206           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6207                                         MachinePointerInfo(), VT);
6208           MemOpChains.push_back(Load.getValue(1));
6209           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6210 
6211           ArgOffset += PtrByteSize;
6212           continue;
6213         }
6214       }
6215 
6216       if (GPR_idx == NumGPRs && Size < 8) {
6217         SDValue AddPtr = PtrOff;
6218         if (!isLittleEndian) {
6219           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6220                                           PtrOff.getValueType());
6221           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6222         }
6223         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6224                                                           CallSeqStart,
6225                                                           Flags, DAG, dl);
6226         ArgOffset += PtrByteSize;
6227         continue;
6228       }
6229       // Copy entire object into memory.  There are cases where gcc-generated
6230       // code assumes it is there, even if it could be put entirely into
6231       // registers.  (This is not what the doc says.)
6232 
6233       // FIXME: The above statement is likely due to a misunderstanding of the
6234       // documents.  All arguments must be copied into the parameter area BY
6235       // THE CALLEE in the event that the callee takes the address of any
6236       // formal argument.  That has not yet been implemented.  However, it is
6237       // reasonable to use the stack area as a staging area for the register
6238       // load.
6239 
6240       // Skip this for small aggregates, as we will use the same slot for a
6241       // right-justified copy, below.
6242       if (Size >= 8)
6243         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6244                                                           CallSeqStart,
6245                                                           Flags, DAG, dl);
6246 
6247       // When a register is available, pass a small aggregate right-justified.
6248       if (Size < 8 && GPR_idx != NumGPRs) {
6249         // The easiest way to get this right-justified in a register
6250         // is to copy the structure into the rightmost portion of a
6251         // local variable slot, then load the whole slot into the
6252         // register.
6253         // FIXME: The memcpy seems to produce pretty awful code for
6254         // small aggregates, particularly for packed ones.
6255         // FIXME: It would be preferable to use the slot in the
6256         // parameter save area instead of a new local variable.
6257         SDValue AddPtr = PtrOff;
6258         if (!isLittleEndian) {
6259           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6260           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6261         }
6262         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6263                                                           CallSeqStart,
6264                                                           Flags, DAG, dl);
6265 
6266         // Load the slot into the register.
6267         SDValue Load =
6268             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6269         MemOpChains.push_back(Load.getValue(1));
6270         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6271 
6272         // Done with this argument.
6273         ArgOffset += PtrByteSize;
6274         continue;
6275       }
6276 
6277       // For aggregates larger than PtrByteSize, copy the pieces of the
6278       // object that fit into registers from the parameter save area.
6279       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6280         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6281         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6282         if (GPR_idx != NumGPRs) {
6283           SDValue Load =
6284               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6285           MemOpChains.push_back(Load.getValue(1));
6286           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6287           ArgOffset += PtrByteSize;
6288         } else {
6289           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6290           break;
6291         }
6292       }
6293       continue;
6294     }
6295 
6296     switch (Arg.getSimpleValueType().SimpleTy) {
6297     default: llvm_unreachable("Unexpected ValueType for argument!");
6298     case MVT::i1:
6299     case MVT::i32:
6300     case MVT::i64:
6301       if (Flags.isNest()) {
6302         // The 'nest' parameter, if any, is passed in R11.
6303         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6304         break;
6305       }
6306 
6307       // These can be scalar arguments or elements of an integer array type
6308       // passed directly.  Clang may use those instead of "byval" aggregate
6309       // types to avoid forcing arguments to memory unnecessarily.
6310       if (GPR_idx != NumGPRs) {
6311         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6312       } else {
6313         if (IsFastCall)
6314           ComputePtrOff();
6315 
6316         assert(HasParameterArea &&
6317                "Parameter area must exist to pass an argument in memory.");
6318         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6319                          true, CFlags.IsTailCall, false, MemOpChains,
6320                          TailCallArguments, dl);
6321         if (IsFastCall)
6322           ArgOffset += PtrByteSize;
6323       }
6324       if (!IsFastCall)
6325         ArgOffset += PtrByteSize;
6326       break;
6327     case MVT::f32:
6328     case MVT::f64: {
6329       // These can be scalar arguments or elements of a float array type
6330       // passed directly.  The latter are used to implement ELFv2 homogenous
6331       // float aggregates.
6332 
6333       // Named arguments go into FPRs first, and once they overflow, the
6334       // remaining arguments go into GPRs and then the parameter save area.
6335       // Unnamed arguments for vararg functions always go to GPRs and
6336       // then the parameter save area.  For now, put all arguments to vararg
6337       // routines always in both locations (FPR *and* GPR or stack slot).
6338       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6339       bool NeededLoad = false;
6340 
6341       // First load the argument into the next available FPR.
6342       if (FPR_idx != NumFPRs)
6343         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6344 
6345       // Next, load the argument into GPR or stack slot if needed.
6346       if (!NeedGPROrStack)
6347         ;
6348       else if (GPR_idx != NumGPRs && !IsFastCall) {
6349         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6350         // once we support fp <-> gpr moves.
6351 
6352         // In the non-vararg case, this can only ever happen in the
6353         // presence of f32 array types, since otherwise we never run
6354         // out of FPRs before running out of GPRs.
6355         SDValue ArgVal;
6356 
6357         // Double values are always passed in a single GPR.
6358         if (Arg.getValueType() != MVT::f32) {
6359           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6360 
6361         // Non-array float values are extended and passed in a GPR.
6362         } else if (!Flags.isInConsecutiveRegs()) {
6363           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6364           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6365 
6366         // If we have an array of floats, we collect every odd element
6367         // together with its predecessor into one GPR.
6368         } else if (ArgOffset % PtrByteSize != 0) {
6369           SDValue Lo, Hi;
6370           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6371           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6372           if (!isLittleEndian)
6373             std::swap(Lo, Hi);
6374           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6375 
6376         // The final element, if even, goes into the first half of a GPR.
6377         } else if (Flags.isInConsecutiveRegsLast()) {
6378           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6379           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6380           if (!isLittleEndian)
6381             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6382                                  DAG.getConstant(32, dl, MVT::i32));
6383 
6384         // Non-final even elements are skipped; they will be handled
6385         // together the with subsequent argument on the next go-around.
6386         } else
6387           ArgVal = SDValue();
6388 
6389         if (ArgVal.getNode())
6390           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6391       } else {
6392         if (IsFastCall)
6393           ComputePtrOff();
6394 
6395         // Single-precision floating-point values are mapped to the
6396         // second (rightmost) word of the stack doubleword.
6397         if (Arg.getValueType() == MVT::f32 &&
6398             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6399           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6400           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6401         }
6402 
6403         assert(HasParameterArea &&
6404                "Parameter area must exist to pass an argument in memory.");
6405         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6406                          true, CFlags.IsTailCall, false, MemOpChains,
6407                          TailCallArguments, dl);
6408 
6409         NeededLoad = true;
6410       }
6411       // When passing an array of floats, the array occupies consecutive
6412       // space in the argument area; only round up to the next doubleword
6413       // at the end of the array.  Otherwise, each float takes 8 bytes.
6414       if (!IsFastCall || NeededLoad) {
6415         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6416                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6417         if (Flags.isInConsecutiveRegsLast())
6418           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6419       }
6420       break;
6421     }
6422     case MVT::v4f32:
6423     case MVT::v4i32:
6424     case MVT::v8i16:
6425     case MVT::v16i8:
6426     case MVT::v2f64:
6427     case MVT::v2i64:
6428     case MVT::v1i128:
6429     case MVT::f128:
6430       // These can be scalar arguments or elements of a vector array type
6431       // passed directly.  The latter are used to implement ELFv2 homogenous
6432       // vector aggregates.
6433 
6434       // For a varargs call, named arguments go into VRs or on the stack as
6435       // usual; unnamed arguments always go to the stack or the corresponding
6436       // GPRs when within range.  For now, we always put the value in both
6437       // locations (or even all three).
6438       if (CFlags.IsVarArg) {
6439         assert(HasParameterArea &&
6440                "Parameter area must exist if we have a varargs call.");
6441         // We could elide this store in the case where the object fits
6442         // entirely in R registers.  Maybe later.
6443         SDValue Store =
6444             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6445         MemOpChains.push_back(Store);
6446         if (VR_idx != NumVRs) {
6447           SDValue Load =
6448               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6449           MemOpChains.push_back(Load.getValue(1));
6450           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6451         }
6452         ArgOffset += 16;
6453         for (unsigned i=0; i<16; i+=PtrByteSize) {
6454           if (GPR_idx == NumGPRs)
6455             break;
6456           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6457                                    DAG.getConstant(i, dl, PtrVT));
6458           SDValue Load =
6459               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6460           MemOpChains.push_back(Load.getValue(1));
6461           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6462         }
6463         break;
6464       }
6465 
6466       // Non-varargs Altivec params go into VRs or on the stack.
6467       if (VR_idx != NumVRs) {
6468         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6469       } else {
6470         if (IsFastCall)
6471           ComputePtrOff();
6472 
6473         assert(HasParameterArea &&
6474                "Parameter area must exist to pass an argument in memory.");
6475         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6476                          true, CFlags.IsTailCall, true, MemOpChains,
6477                          TailCallArguments, dl);
6478         if (IsFastCall)
6479           ArgOffset += 16;
6480       }
6481 
6482       if (!IsFastCall)
6483         ArgOffset += 16;
6484       break;
6485     }
6486   }
6487 
6488   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6489          "mismatch in size of parameter area");
6490   (void)NumBytesActuallyUsed;
6491 
6492   if (!MemOpChains.empty())
6493     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6494 
6495   // Check if this is an indirect call (MTCTR/BCTRL).
6496   // See prepareDescriptorIndirectCall and buildCallOperands for more
6497   // information about calls through function pointers in the 64-bit SVR4 ABI.
6498   if (CFlags.IsIndirect) {
6499     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6500     // caller in the TOC save area.
6501     if (isTOCSaveRestoreRequired(Subtarget)) {
6502       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6503       // Load r2 into a virtual register and store it to the TOC save area.
6504       setUsesTOCBasePtr(DAG);
6505       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6506       // TOC save area offset.
6507       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6508       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6509       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6510       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6511                            MachinePointerInfo::getStack(
6512                                DAG.getMachineFunction(), TOCSaveOffset));
6513     }
6514     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6515     // This does not mean the MTCTR instruction must use R12; it's easier
6516     // to model this as an extra parameter, so do that.
6517     if (isELFv2ABI && !CFlags.IsPatchPoint)
6518       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6519   }
6520 
6521   // Build a sequence of copy-to-reg nodes chained together with token chain
6522   // and flag operands which copy the outgoing args into the appropriate regs.
6523   SDValue InFlag;
6524   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6525     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6526                              RegsToPass[i].second, InFlag);
6527     InFlag = Chain.getValue(1);
6528   }
6529 
6530   if (CFlags.IsTailCall && !IsSibCall)
6531     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6532                     TailCallArguments);
6533 
6534   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6535                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6536 }
6537 
6538 SDValue PPCTargetLowering::LowerCall_Darwin(
6539     SDValue Chain, SDValue Callee, CallFlags CFlags,
6540     const SmallVectorImpl<ISD::OutputArg> &Outs,
6541     const SmallVectorImpl<SDValue> &OutVals,
6542     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6543     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6544     const CallBase *CB) const {
6545   unsigned NumOps = Outs.size();
6546 
6547   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6548   bool isPPC64 = PtrVT == MVT::i64;
6549   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6550 
6551   MachineFunction &MF = DAG.getMachineFunction();
6552 
6553   // Mark this function as potentially containing a function that contains a
6554   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6555   // and restoring the callers stack pointer in this functions epilog. This is
6556   // done because by tail calling the called function might overwrite the value
6557   // in this function's (MF) stack pointer stack slot 0(SP).
6558   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6559       CFlags.CallConv == CallingConv::Fast)
6560     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6561 
6562   // Count how many bytes are to be pushed on the stack, including the linkage
6563   // area, and parameter passing area.  We start with 24/48 bytes, which is
6564   // prereserved space for [SP][CR][LR][3 x unused].
6565   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6566   unsigned NumBytes = LinkageSize;
6567 
6568   // Add up all the space actually used.
6569   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6570   // they all go in registers, but we must reserve stack space for them for
6571   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6572   // assigned stack space in order, with padding so Altivec parameters are
6573   // 16-byte aligned.
6574   unsigned nAltivecParamsAtEnd = 0;
6575   for (unsigned i = 0; i != NumOps; ++i) {
6576     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6577     EVT ArgVT = Outs[i].VT;
6578     // Varargs Altivec parameters are padded to a 16 byte boundary.
6579     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6580         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6581         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6582       if (!CFlags.IsVarArg && !isPPC64) {
6583         // Non-varargs Altivec parameters go after all the non-Altivec
6584         // parameters; handle those later so we know how much padding we need.
6585         nAltivecParamsAtEnd++;
6586         continue;
6587       }
6588       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6589       NumBytes = ((NumBytes+15)/16)*16;
6590     }
6591     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6592   }
6593 
6594   // Allow for Altivec parameters at the end, if needed.
6595   if (nAltivecParamsAtEnd) {
6596     NumBytes = ((NumBytes+15)/16)*16;
6597     NumBytes += 16*nAltivecParamsAtEnd;
6598   }
6599 
6600   // The prolog code of the callee may store up to 8 GPR argument registers to
6601   // the stack, allowing va_start to index over them in memory if its varargs.
6602   // Because we cannot tell if this is needed on the caller side, we have to
6603   // conservatively assume that it is needed.  As such, make sure we have at
6604   // least enough stack space for the caller to store the 8 GPRs.
6605   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6606 
6607   // Tail call needs the stack to be aligned.
6608   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6609       CFlags.CallConv == CallingConv::Fast)
6610     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6611 
6612   // Calculate by how many bytes the stack has to be adjusted in case of tail
6613   // call optimization.
6614   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6615 
6616   // To protect arguments on the stack from being clobbered in a tail call,
6617   // force all the loads to happen before doing any other lowering.
6618   if (CFlags.IsTailCall)
6619     Chain = DAG.getStackArgumentTokenFactor(Chain);
6620 
6621   // Adjust the stack pointer for the new arguments...
6622   // These operations are automatically eliminated by the prolog/epilog pass
6623   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6624   SDValue CallSeqStart = Chain;
6625 
6626   // Load the return address and frame pointer so it can be move somewhere else
6627   // later.
6628   SDValue LROp, FPOp;
6629   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6630 
6631   // Set up a copy of the stack pointer for use loading and storing any
6632   // arguments that may not fit in the registers available for argument
6633   // passing.
6634   SDValue StackPtr;
6635   if (isPPC64)
6636     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6637   else
6638     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6639 
6640   // Figure out which arguments are going to go in registers, and which in
6641   // memory.  Also, if this is a vararg function, floating point operations
6642   // must be stored to our stack, and loaded into integer regs as well, if
6643   // any integer regs are available for argument passing.
6644   unsigned ArgOffset = LinkageSize;
6645   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6646 
6647   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6648     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6649     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6650   };
6651   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6652     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6653     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6654   };
6655   static const MCPhysReg VR[] = {
6656     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6657     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6658   };
6659   const unsigned NumGPRs = array_lengthof(GPR_32);
6660   const unsigned NumFPRs = 13;
6661   const unsigned NumVRs  = array_lengthof(VR);
6662 
6663   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6664 
6665   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6666   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6667 
6668   SmallVector<SDValue, 8> MemOpChains;
6669   for (unsigned i = 0; i != NumOps; ++i) {
6670     SDValue Arg = OutVals[i];
6671     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6672 
6673     // PtrOff will be used to store the current argument to the stack if a
6674     // register cannot be found for it.
6675     SDValue PtrOff;
6676 
6677     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6678 
6679     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6680 
6681     // On PPC64, promote integers to 64-bit values.
6682     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6683       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6684       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6685       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6686     }
6687 
6688     // FIXME memcpy is used way more than necessary.  Correctness first.
6689     // Note: "by value" is code for passing a structure by value, not
6690     // basic types.
6691     if (Flags.isByVal()) {
6692       unsigned Size = Flags.getByValSize();
6693       // Very small objects are passed right-justified.  Everything else is
6694       // passed left-justified.
6695       if (Size==1 || Size==2) {
6696         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6697         if (GPR_idx != NumGPRs) {
6698           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6699                                         MachinePointerInfo(), VT);
6700           MemOpChains.push_back(Load.getValue(1));
6701           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6702 
6703           ArgOffset += PtrByteSize;
6704         } else {
6705           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6706                                           PtrOff.getValueType());
6707           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6708           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6709                                                             CallSeqStart,
6710                                                             Flags, DAG, dl);
6711           ArgOffset += PtrByteSize;
6712         }
6713         continue;
6714       }
6715       // Copy entire object into memory.  There are cases where gcc-generated
6716       // code assumes it is there, even if it could be put entirely into
6717       // registers.  (This is not what the doc says.)
6718       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6719                                                         CallSeqStart,
6720                                                         Flags, DAG, dl);
6721 
6722       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6723       // copy the pieces of the object that fit into registers from the
6724       // parameter save area.
6725       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6726         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6727         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6728         if (GPR_idx != NumGPRs) {
6729           SDValue Load =
6730               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6731           MemOpChains.push_back(Load.getValue(1));
6732           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6733           ArgOffset += PtrByteSize;
6734         } else {
6735           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6736           break;
6737         }
6738       }
6739       continue;
6740     }
6741 
6742     switch (Arg.getSimpleValueType().SimpleTy) {
6743     default: llvm_unreachable("Unexpected ValueType for argument!");
6744     case MVT::i1:
6745     case MVT::i32:
6746     case MVT::i64:
6747       if (GPR_idx != NumGPRs) {
6748         if (Arg.getValueType() == MVT::i1)
6749           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6750 
6751         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6752       } else {
6753         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6754                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6755                          TailCallArguments, dl);
6756       }
6757       ArgOffset += PtrByteSize;
6758       break;
6759     case MVT::f32:
6760     case MVT::f64:
6761       if (FPR_idx != NumFPRs) {
6762         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6763 
6764         if (CFlags.IsVarArg) {
6765           SDValue Store =
6766               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6767           MemOpChains.push_back(Store);
6768 
6769           // Float varargs are always shadowed in available integer registers
6770           if (GPR_idx != NumGPRs) {
6771             SDValue Load =
6772                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6773             MemOpChains.push_back(Load.getValue(1));
6774             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6775           }
6776           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6777             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6778             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6779             SDValue Load =
6780                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6781             MemOpChains.push_back(Load.getValue(1));
6782             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6783           }
6784         } else {
6785           // If we have any FPRs remaining, we may also have GPRs remaining.
6786           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6787           // GPRs.
6788           if (GPR_idx != NumGPRs)
6789             ++GPR_idx;
6790           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6791               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6792             ++GPR_idx;
6793         }
6794       } else
6795         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6796                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6797                          TailCallArguments, dl);
6798       if (isPPC64)
6799         ArgOffset += 8;
6800       else
6801         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6802       break;
6803     case MVT::v4f32:
6804     case MVT::v4i32:
6805     case MVT::v8i16:
6806     case MVT::v16i8:
6807       if (CFlags.IsVarArg) {
6808         // These go aligned on the stack, or in the corresponding R registers
6809         // when within range.  The Darwin PPC ABI doc claims they also go in
6810         // V registers; in fact gcc does this only for arguments that are
6811         // prototyped, not for those that match the ...  We do it for all
6812         // arguments, seems to work.
6813         while (ArgOffset % 16 !=0) {
6814           ArgOffset += PtrByteSize;
6815           if (GPR_idx != NumGPRs)
6816             GPR_idx++;
6817         }
6818         // We could elide this store in the case where the object fits
6819         // entirely in R registers.  Maybe later.
6820         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6821                              DAG.getConstant(ArgOffset, dl, PtrVT));
6822         SDValue Store =
6823             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6824         MemOpChains.push_back(Store);
6825         if (VR_idx != NumVRs) {
6826           SDValue Load =
6827               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6828           MemOpChains.push_back(Load.getValue(1));
6829           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6830         }
6831         ArgOffset += 16;
6832         for (unsigned i=0; i<16; i+=PtrByteSize) {
6833           if (GPR_idx == NumGPRs)
6834             break;
6835           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6836                                    DAG.getConstant(i, dl, PtrVT));
6837           SDValue Load =
6838               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6839           MemOpChains.push_back(Load.getValue(1));
6840           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6841         }
6842         break;
6843       }
6844 
6845       // Non-varargs Altivec params generally go in registers, but have
6846       // stack space allocated at the end.
6847       if (VR_idx != NumVRs) {
6848         // Doesn't have GPR space allocated.
6849         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6850       } else if (nAltivecParamsAtEnd==0) {
6851         // We are emitting Altivec params in order.
6852         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6853                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6854                          TailCallArguments, dl);
6855         ArgOffset += 16;
6856       }
6857       break;
6858     }
6859   }
6860   // If all Altivec parameters fit in registers, as they usually do,
6861   // they get stack space following the non-Altivec parameters.  We
6862   // don't track this here because nobody below needs it.
6863   // If there are more Altivec parameters than fit in registers emit
6864   // the stores here.
6865   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6866     unsigned j = 0;
6867     // Offset is aligned; skip 1st 12 params which go in V registers.
6868     ArgOffset = ((ArgOffset+15)/16)*16;
6869     ArgOffset += 12*16;
6870     for (unsigned i = 0; i != NumOps; ++i) {
6871       SDValue Arg = OutVals[i];
6872       EVT ArgType = Outs[i].VT;
6873       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6874           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6875         if (++j > NumVRs) {
6876           SDValue PtrOff;
6877           // We are emitting Altivec params in order.
6878           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6879                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6880                            TailCallArguments, dl);
6881           ArgOffset += 16;
6882         }
6883       }
6884     }
6885   }
6886 
6887   if (!MemOpChains.empty())
6888     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6889 
6890   // On Darwin, R12 must contain the address of an indirect callee.  This does
6891   // not mean the MTCTR instruction must use R12; it's easier to model this as
6892   // an extra parameter, so do that.
6893   if (CFlags.IsIndirect) {
6894     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6895     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6896                                                    PPC::R12), Callee));
6897   }
6898 
6899   // Build a sequence of copy-to-reg nodes chained together with token chain
6900   // and flag operands which copy the outgoing args into the appropriate regs.
6901   SDValue InFlag;
6902   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6903     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6904                              RegsToPass[i].second, InFlag);
6905     InFlag = Chain.getValue(1);
6906   }
6907 
6908   if (CFlags.IsTailCall)
6909     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6910                     TailCallArguments);
6911 
6912   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6913                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6914 }
6915 
6916 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6917                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6918                    CCState &State) {
6919 
6920   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6921       State.getMachineFunction().getSubtarget());
6922   const bool IsPPC64 = Subtarget.isPPC64();
6923   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6924   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6925 
6926   assert((!ValVT.isInteger() ||
6927           (ValVT.getFixedSizeInBits() <= RegVT.getFixedSizeInBits())) &&
6928          "Integer argument exceeds register size: should have been legalized");
6929 
6930   if (ValVT == MVT::f128)
6931     report_fatal_error("f128 is unimplemented on AIX.");
6932 
6933   if (ArgFlags.isNest())
6934     report_fatal_error("Nest arguments are unimplemented.");
6935 
6936   if (ValVT.isVector() || LocVT.isVector())
6937     report_fatal_error("Vector arguments are unimplemented on AIX.");
6938 
6939   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6940                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6941                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6942   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6943                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6944                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6945 
6946   if (ArgFlags.isByVal()) {
6947     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6948       report_fatal_error("Pass-by-value arguments with alignment greater than "
6949                          "register width are not supported.");
6950 
6951     const unsigned ByValSize = ArgFlags.getByValSize();
6952 
6953     // An empty aggregate parameter takes up no storage and no registers,
6954     // but needs a MemLoc for a stack slot for the formal arguments side.
6955     if (ByValSize == 0) {
6956       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6957                                        State.getNextStackOffset(), RegVT,
6958                                        LocInfo));
6959       return false;
6960     }
6961 
6962     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6963     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6964     for (const unsigned E = Offset + StackSize; Offset < E;
6965          Offset += PtrAlign.value()) {
6966       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6967         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6968       else {
6969         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6970                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6971                                          LocInfo));
6972         break;
6973       }
6974     }
6975     return false;
6976   }
6977 
6978   // Arguments always reserve parameter save area.
6979   switch (ValVT.SimpleTy) {
6980   default:
6981     report_fatal_error("Unhandled value type for argument.");
6982   case MVT::i64:
6983     // i64 arguments should have been split to i32 for PPC32.
6984     assert(IsPPC64 && "PPC32 should have split i64 values.");
6985     LLVM_FALLTHROUGH;
6986   case MVT::i1:
6987   case MVT::i32: {
6988     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6989     // AIX integer arguments are always passed in register width.
6990     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6991       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6992                                   : CCValAssign::LocInfo::ZExt;
6993     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6994       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6995     else
6996       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6997 
6998     return false;
6999   }
7000   case MVT::f32:
7001   case MVT::f64: {
7002     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7003     const unsigned StoreSize = LocVT.getStoreSize();
7004     // Floats are always 4-byte aligned in the PSA on AIX.
7005     // This includes f64 in 64-bit mode for ABI compatibility.
7006     const unsigned Offset =
7007         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7008     unsigned FReg = State.AllocateReg(FPR);
7009     if (FReg)
7010       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7011 
7012     // Reserve and initialize GPRs or initialize the PSA as required.
7013     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7014       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7015         assert(FReg && "An FPR should be available when a GPR is reserved.");
7016         if (State.isVarArg()) {
7017           // Successfully reserved GPRs are only initialized for vararg calls.
7018           // Custom handling is required for:
7019           //   f64 in PPC32 needs to be split into 2 GPRs.
7020           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7021           State.addLoc(
7022               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7023         }
7024       } else {
7025         // If there are insufficient GPRs, the PSA needs to be initialized.
7026         // Initialization occurs even if an FPR was initialized for
7027         // compatibility with the AIX XL compiler. The full memory for the
7028         // argument will be initialized even if a prior word is saved in GPR.
7029         // A custom memLoc is used when the argument also passes in FPR so
7030         // that the callee handling can skip over it easily.
7031         State.addLoc(
7032             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7033                                              LocInfo)
7034                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7035         break;
7036       }
7037     }
7038 
7039     return false;
7040   }
7041   }
7042   return true;
7043 }
7044 
7045 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7046                                                     bool IsPPC64) {
7047   assert((IsPPC64 || SVT != MVT::i64) &&
7048          "i64 should have been split for 32-bit codegen.");
7049 
7050   switch (SVT) {
7051   default:
7052     report_fatal_error("Unexpected value type for formal argument");
7053   case MVT::i1:
7054   case MVT::i32:
7055   case MVT::i64:
7056     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7057   case MVT::f32:
7058     return &PPC::F4RCRegClass;
7059   case MVT::f64:
7060     return &PPC::F8RCRegClass;
7061   }
7062 }
7063 
7064 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7065                                         SelectionDAG &DAG, SDValue ArgValue,
7066                                         MVT LocVT, const SDLoc &dl) {
7067   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7068   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7069 
7070   if (Flags.isSExt())
7071     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7072                            DAG.getValueType(ValVT));
7073   else if (Flags.isZExt())
7074     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7075                            DAG.getValueType(ValVT));
7076 
7077   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7078 }
7079 
7080 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7081   const unsigned LASize = FL->getLinkageSize();
7082 
7083   if (PPC::GPRCRegClass.contains(Reg)) {
7084     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7085            "Reg must be a valid argument register!");
7086     return LASize + 4 * (Reg - PPC::R3);
7087   }
7088 
7089   if (PPC::G8RCRegClass.contains(Reg)) {
7090     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7091            "Reg must be a valid argument register!");
7092     return LASize + 8 * (Reg - PPC::X3);
7093   }
7094 
7095   llvm_unreachable("Only general purpose registers expected.");
7096 }
7097 
7098 //   AIX ABI Stack Frame Layout:
7099 //
7100 //   Low Memory +--------------------------------------------+
7101 //   SP   +---> | Back chain                                 | ---+
7102 //        |     +--------------------------------------------+    |
7103 //        |     | Saved Condition Register                   |    |
7104 //        |     +--------------------------------------------+    |
7105 //        |     | Saved Linkage Register                     |    |
7106 //        |     +--------------------------------------------+    | Linkage Area
7107 //        |     | Reserved for compilers                     |    |
7108 //        |     +--------------------------------------------+    |
7109 //        |     | Reserved for binders                       |    |
7110 //        |     +--------------------------------------------+    |
7111 //        |     | Saved TOC pointer                          | ---+
7112 //        |     +--------------------------------------------+
7113 //        |     | Parameter save area                        |
7114 //        |     +--------------------------------------------+
7115 //        |     | Alloca space                               |
7116 //        |     +--------------------------------------------+
7117 //        |     | Local variable space                       |
7118 //        |     +--------------------------------------------+
7119 //        |     | Float/int conversion temporary             |
7120 //        |     +--------------------------------------------+
7121 //        |     | Save area for AltiVec registers            |
7122 //        |     +--------------------------------------------+
7123 //        |     | AltiVec alignment padding                  |
7124 //        |     +--------------------------------------------+
7125 //        |     | Save area for VRSAVE register              |
7126 //        |     +--------------------------------------------+
7127 //        |     | Save area for General Purpose registers    |
7128 //        |     +--------------------------------------------+
7129 //        |     | Save area for Floating Point registers     |
7130 //        |     +--------------------------------------------+
7131 //        +---- | Back chain                                 |
7132 // High Memory  +--------------------------------------------+
7133 //
7134 //  Specifications:
7135 //  AIX 7.2 Assembler Language Reference
7136 //  Subroutine linkage convention
7137 
7138 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7139     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7140     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7141     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7142 
7143   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7144           CallConv == CallingConv::Fast) &&
7145          "Unexpected calling convention!");
7146 
7147   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7148     report_fatal_error("Tail call support is unimplemented on AIX.");
7149 
7150   if (useSoftFloat())
7151     report_fatal_error("Soft float support is unimplemented on AIX.");
7152 
7153   const PPCSubtarget &Subtarget =
7154       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7155 
7156   const bool IsPPC64 = Subtarget.isPPC64();
7157   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7158 
7159   // Assign locations to all of the incoming arguments.
7160   SmallVector<CCValAssign, 16> ArgLocs;
7161   MachineFunction &MF = DAG.getMachineFunction();
7162   MachineFrameInfo &MFI = MF.getFrameInfo();
7163   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7164 
7165   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7166   // Reserve space for the linkage area on the stack.
7167   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7168   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7169   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7170 
7171   SmallVector<SDValue, 8> MemOps;
7172 
7173   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7174     CCValAssign &VA = ArgLocs[I++];
7175     MVT LocVT = VA.getLocVT();
7176     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7177 
7178     // For compatibility with the AIX XL compiler, the float args in the
7179     // parameter save area are initialized even if the argument is available
7180     // in register.  The caller is required to initialize both the register
7181     // and memory, however, the callee can choose to expect it in either.
7182     // The memloc is dismissed here because the argument is retrieved from
7183     // the register.
7184     if (VA.isMemLoc() && VA.needsCustom())
7185       continue;
7186 
7187     if (Flags.isByVal() && VA.isMemLoc()) {
7188       const unsigned Size =
7189           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7190                   PtrByteSize);
7191       const int FI = MF.getFrameInfo().CreateFixedObject(
7192           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7193           /* IsAliased */ true);
7194       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7195       InVals.push_back(FIN);
7196 
7197       continue;
7198     }
7199 
7200     if (Flags.isByVal()) {
7201       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7202 
7203       const MCPhysReg ArgReg = VA.getLocReg();
7204       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7205 
7206       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7207         report_fatal_error("Over aligned byvals not supported yet.");
7208 
7209       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7210       const int FI = MF.getFrameInfo().CreateFixedObject(
7211           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7212           /* IsAliased */ true);
7213       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7214       InVals.push_back(FIN);
7215 
7216       // Add live ins for all the RegLocs for the same ByVal.
7217       const TargetRegisterClass *RegClass =
7218           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7219 
7220       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7221                                                unsigned Offset) {
7222         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7223         // Since the callers side has left justified the aggregate in the
7224         // register, we can simply store the entire register into the stack
7225         // slot.
7226         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7227         // The store to the fixedstack object is needed becuase accessing a
7228         // field of the ByVal will use a gep and load. Ideally we will optimize
7229         // to extracting the value from the register directly, and elide the
7230         // stores when the arguments address is not taken, but that will need to
7231         // be future work.
7232         SDValue Store = DAG.getStore(
7233             CopyFrom.getValue(1), dl, CopyFrom,
7234             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7235             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7236 
7237         MemOps.push_back(Store);
7238       };
7239 
7240       unsigned Offset = 0;
7241       HandleRegLoc(VA.getLocReg(), Offset);
7242       Offset += PtrByteSize;
7243       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7244            Offset += PtrByteSize) {
7245         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7246                "RegLocs should be for ByVal argument.");
7247 
7248         const CCValAssign RL = ArgLocs[I++];
7249         HandleRegLoc(RL.getLocReg(), Offset);
7250       }
7251 
7252       if (Offset != StackSize) {
7253         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7254                "Expected MemLoc for remaining bytes.");
7255         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7256         // Consume the MemLoc.The InVal has already been emitted, so nothing
7257         // more needs to be done.
7258         ++I;
7259       }
7260 
7261       continue;
7262     }
7263 
7264     EVT ValVT = VA.getValVT();
7265     if (VA.isRegLoc() && !VA.needsCustom()) {
7266       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7267       unsigned VReg =
7268           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7269       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7270       if (ValVT.isScalarInteger() &&
7271           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7272         ArgValue =
7273             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7274       }
7275       InVals.push_back(ArgValue);
7276       continue;
7277     }
7278     if (VA.isMemLoc()) {
7279       const unsigned LocSize = LocVT.getStoreSize();
7280       const unsigned ValSize = ValVT.getStoreSize();
7281       assert((ValSize <= LocSize) &&
7282              "Object size is larger than size of MemLoc");
7283       int CurArgOffset = VA.getLocMemOffset();
7284       // Objects are right-justified because AIX is big-endian.
7285       if (LocSize > ValSize)
7286         CurArgOffset += LocSize - ValSize;
7287       // Potential tail calls could cause overwriting of argument stack slots.
7288       const bool IsImmutable =
7289           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7290             (CallConv == CallingConv::Fast));
7291       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7292       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7293       SDValue ArgValue =
7294           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7295       InVals.push_back(ArgValue);
7296       continue;
7297     }
7298   }
7299 
7300   // On AIX a minimum of 8 words is saved to the parameter save area.
7301   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7302   // Area that is at least reserved in the caller of this function.
7303   unsigned CallerReservedArea =
7304       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7305 
7306   // Set the size that is at least reserved in caller of this function. Tail
7307   // call optimized function's reserved stack space needs to be aligned so
7308   // that taking the difference between two stack areas will result in an
7309   // aligned stack.
7310   CallerReservedArea =
7311       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7312   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7313   FuncInfo->setMinReservedArea(CallerReservedArea);
7314 
7315   if (isVarArg) {
7316     FuncInfo->setVarArgsFrameIndex(
7317         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7318     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7319 
7320     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7321                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7322 
7323     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7324                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7325     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7326 
7327     // The fixed integer arguments of a variadic function are stored to the
7328     // VarArgsFrameIndex on the stack so that they may be loaded by
7329     // dereferencing the result of va_next.
7330     for (unsigned GPRIndex =
7331              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7332          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7333 
7334       const unsigned VReg =
7335           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7336                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7337 
7338       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7339       SDValue Store =
7340           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7341       MemOps.push_back(Store);
7342       // Increment the address for the next argument to store.
7343       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7344       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7345     }
7346   }
7347 
7348   if (!MemOps.empty())
7349     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7350 
7351   return Chain;
7352 }
7353 
7354 SDValue PPCTargetLowering::LowerCall_AIX(
7355     SDValue Chain, SDValue Callee, CallFlags CFlags,
7356     const SmallVectorImpl<ISD::OutputArg> &Outs,
7357     const SmallVectorImpl<SDValue> &OutVals,
7358     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7359     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7360     const CallBase *CB) const {
7361   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7362   // AIX ABI stack frame layout.
7363 
7364   assert((CFlags.CallConv == CallingConv::C ||
7365           CFlags.CallConv == CallingConv::Cold ||
7366           CFlags.CallConv == CallingConv::Fast) &&
7367          "Unexpected calling convention!");
7368 
7369   if (CFlags.IsPatchPoint)
7370     report_fatal_error("This call type is unimplemented on AIX.");
7371 
7372   const PPCSubtarget& Subtarget =
7373       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7374   if (Subtarget.hasAltivec())
7375     report_fatal_error("Altivec support is unimplemented on AIX.");
7376 
7377   MachineFunction &MF = DAG.getMachineFunction();
7378   SmallVector<CCValAssign, 16> ArgLocs;
7379   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7380                  *DAG.getContext());
7381 
7382   // Reserve space for the linkage save area (LSA) on the stack.
7383   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7384   //   [SP][CR][LR][2 x reserved][TOC].
7385   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7386   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7387   const bool IsPPC64 = Subtarget.isPPC64();
7388   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7389   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7390   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7391   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7392 
7393   // The prolog code of the callee may store up to 8 GPR argument registers to
7394   // the stack, allowing va_start to index over them in memory if the callee
7395   // is variadic.
7396   // Because we cannot tell if this is needed on the caller side, we have to
7397   // conservatively assume that it is needed.  As such, make sure we have at
7398   // least enough stack space for the caller to store the 8 GPRs.
7399   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7400   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7401                                      CCInfo.getNextStackOffset());
7402 
7403   // Adjust the stack pointer for the new arguments...
7404   // These operations are automatically eliminated by the prolog/epilog pass.
7405   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7406   SDValue CallSeqStart = Chain;
7407 
7408   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7409   SmallVector<SDValue, 8> MemOpChains;
7410 
7411   // Set up a copy of the stack pointer for loading and storing any
7412   // arguments that may not fit in the registers available for argument
7413   // passing.
7414   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7415                                    : DAG.getRegister(PPC::R1, MVT::i32);
7416 
7417   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7418     const unsigned ValNo = ArgLocs[I].getValNo();
7419     SDValue Arg = OutVals[ValNo];
7420     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7421 
7422     if (Flags.isByVal()) {
7423       const unsigned ByValSize = Flags.getByValSize();
7424 
7425       // Nothing to do for zero-sized ByVals on the caller side.
7426       if (!ByValSize) {
7427         ++I;
7428         continue;
7429       }
7430 
7431       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7432         return DAG.getExtLoad(
7433             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7434             (LoadOffset != 0)
7435                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7436                 : Arg,
7437             MachinePointerInfo(), VT);
7438       };
7439 
7440       unsigned LoadOffset = 0;
7441 
7442       // Initialize registers, which are fully occupied by the by-val argument.
7443       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7444         SDValue Load = GetLoad(PtrVT, LoadOffset);
7445         MemOpChains.push_back(Load.getValue(1));
7446         LoadOffset += PtrByteSize;
7447         const CCValAssign &ByValVA = ArgLocs[I++];
7448         assert(ByValVA.getValNo() == ValNo &&
7449                "Unexpected location for pass-by-value argument.");
7450         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7451       }
7452 
7453       if (LoadOffset == ByValSize)
7454         continue;
7455 
7456       // There must be one more loc to handle the remainder.
7457       assert(ArgLocs[I].getValNo() == ValNo &&
7458              "Expected additional location for by-value argument.");
7459 
7460       if (ArgLocs[I].isMemLoc()) {
7461         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7462         const CCValAssign &ByValVA = ArgLocs[I++];
7463         ISD::ArgFlagsTy MemcpyFlags = Flags;
7464         // Only memcpy the bytes that don't pass in register.
7465         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7466         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7467             (LoadOffset != 0)
7468                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7469                 : Arg,
7470             DAG.getObjectPtrOffset(dl, StackPtr,
7471                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7472             CallSeqStart, MemcpyFlags, DAG, dl);
7473         continue;
7474       }
7475 
7476       // Initialize the final register residue.
7477       // Any residue that occupies the final by-val arg register must be
7478       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7479       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7480       // 2 and 1 byte loads.
7481       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7482       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7483              "Unexpected register residue for by-value argument.");
7484       SDValue ResidueVal;
7485       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7486         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7487         const MVT VT =
7488             N == 1 ? MVT::i8
7489                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7490         SDValue Load = GetLoad(VT, LoadOffset);
7491         MemOpChains.push_back(Load.getValue(1));
7492         LoadOffset += N;
7493         Bytes += N;
7494 
7495         // By-val arguments are passed left-justfied in register.
7496         // Every load here needs to be shifted, otherwise a full register load
7497         // should have been used.
7498         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7499                "Unexpected load emitted during handling of pass-by-value "
7500                "argument.");
7501         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7502         EVT ShiftAmountTy =
7503             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7504         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7505         SDValue ShiftedLoad =
7506             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7507         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7508                                               ShiftedLoad)
7509                                 : ShiftedLoad;
7510       }
7511 
7512       const CCValAssign &ByValVA = ArgLocs[I++];
7513       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7514       continue;
7515     }
7516 
7517     CCValAssign &VA = ArgLocs[I++];
7518     const MVT LocVT = VA.getLocVT();
7519     const MVT ValVT = VA.getValVT();
7520 
7521     switch (VA.getLocInfo()) {
7522     default:
7523       report_fatal_error("Unexpected argument extension type.");
7524     case CCValAssign::Full:
7525       break;
7526     case CCValAssign::ZExt:
7527       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7528       break;
7529     case CCValAssign::SExt:
7530       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7531       break;
7532     }
7533 
7534     if (VA.isRegLoc() && !VA.needsCustom()) {
7535       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7536       continue;
7537     }
7538 
7539     if (VA.isMemLoc()) {
7540       SDValue PtrOff =
7541           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7542       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7543       MemOpChains.push_back(
7544           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7545 
7546       continue;
7547     }
7548 
7549     // Custom handling is used for GPR initializations for vararg float
7550     // arguments.
7551     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7552            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7553            "Unexpected register handling for calling convention.");
7554 
7555     SDValue ArgAsInt =
7556         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7557 
7558     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7559       // f32 in 32-bit GPR
7560       // f64 in 64-bit GPR
7561       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7562     else if (Arg.getValueType().getFixedSizeInBits() <
7563              LocVT.getFixedSizeInBits())
7564       // f32 in 64-bit GPR.
7565       RegsToPass.push_back(std::make_pair(
7566           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7567     else {
7568       // f64 in two 32-bit GPRs
7569       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7570       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7571              "Unexpected custom register for argument!");
7572       CCValAssign &GPR1 = VA;
7573       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7574                                      DAG.getConstant(32, dl, MVT::i8));
7575       RegsToPass.push_back(std::make_pair(
7576           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7577 
7578       if (I != E) {
7579         // If only 1 GPR was available, there will only be one custom GPR and
7580         // the argument will also pass in memory.
7581         CCValAssign &PeekArg = ArgLocs[I];
7582         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7583           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7584           CCValAssign &GPR2 = ArgLocs[I++];
7585           RegsToPass.push_back(std::make_pair(
7586               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7587         }
7588       }
7589     }
7590   }
7591 
7592   if (!MemOpChains.empty())
7593     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7594 
7595   // For indirect calls, we need to save the TOC base to the stack for
7596   // restoration after the call.
7597   if (CFlags.IsIndirect) {
7598     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7599     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7600     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7601     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7602     const unsigned TOCSaveOffset =
7603         Subtarget.getFrameLowering()->getTOCSaveOffset();
7604 
7605     setUsesTOCBasePtr(DAG);
7606     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7607     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7608     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7609     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7610     Chain = DAG.getStore(
7611         Val.getValue(1), dl, Val, AddPtr,
7612         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7613   }
7614 
7615   // Build a sequence of copy-to-reg nodes chained together with token chain
7616   // and flag operands which copy the outgoing args into the appropriate regs.
7617   SDValue InFlag;
7618   for (auto Reg : RegsToPass) {
7619     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7620     InFlag = Chain.getValue(1);
7621   }
7622 
7623   const int SPDiff = 0;
7624   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7625                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7626 }
7627 
7628 bool
7629 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7630                                   MachineFunction &MF, bool isVarArg,
7631                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7632                                   LLVMContext &Context) const {
7633   SmallVector<CCValAssign, 16> RVLocs;
7634   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7635   return CCInfo.CheckReturn(
7636       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7637                 ? RetCC_PPC_Cold
7638                 : RetCC_PPC);
7639 }
7640 
7641 SDValue
7642 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7643                                bool isVarArg,
7644                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7645                                const SmallVectorImpl<SDValue> &OutVals,
7646                                const SDLoc &dl, SelectionDAG &DAG) const {
7647   SmallVector<CCValAssign, 16> RVLocs;
7648   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7649                  *DAG.getContext());
7650   CCInfo.AnalyzeReturn(Outs,
7651                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7652                            ? RetCC_PPC_Cold
7653                            : RetCC_PPC);
7654 
7655   SDValue Flag;
7656   SmallVector<SDValue, 4> RetOps(1, Chain);
7657 
7658   // Copy the result values into the output registers.
7659   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7660     CCValAssign &VA = RVLocs[i];
7661     assert(VA.isRegLoc() && "Can only return in registers!");
7662 
7663     SDValue Arg = OutVals[RealResIdx];
7664 
7665     if (Subtarget.isAIXABI() &&
7666         (VA.getLocVT().isVector() || VA.getValVT().isVector()))
7667       report_fatal_error("Returning vector types not yet supported on AIX.");
7668 
7669     switch (VA.getLocInfo()) {
7670     default: llvm_unreachable("Unknown loc info!");
7671     case CCValAssign::Full: break;
7672     case CCValAssign::AExt:
7673       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7674       break;
7675     case CCValAssign::ZExt:
7676       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7677       break;
7678     case CCValAssign::SExt:
7679       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7680       break;
7681     }
7682     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7683       bool isLittleEndian = Subtarget.isLittleEndian();
7684       // Legalize ret f64 -> ret 2 x i32.
7685       SDValue SVal =
7686           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7687                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7688       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7689       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7690       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7691                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7692       Flag = Chain.getValue(1);
7693       VA = RVLocs[++i]; // skip ahead to next loc
7694       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7695     } else
7696       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7697     Flag = Chain.getValue(1);
7698     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7699   }
7700 
7701   RetOps[0] = Chain;  // Update chain.
7702 
7703   // Add the flag if we have it.
7704   if (Flag.getNode())
7705     RetOps.push_back(Flag);
7706 
7707   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7708 }
7709 
7710 SDValue
7711 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7712                                                 SelectionDAG &DAG) const {
7713   SDLoc dl(Op);
7714 
7715   // Get the correct type for integers.
7716   EVT IntVT = Op.getValueType();
7717 
7718   // Get the inputs.
7719   SDValue Chain = Op.getOperand(0);
7720   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7721   // Build a DYNAREAOFFSET node.
7722   SDValue Ops[2] = {Chain, FPSIdx};
7723   SDVTList VTs = DAG.getVTList(IntVT);
7724   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7725 }
7726 
7727 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7728                                              SelectionDAG &DAG) const {
7729   // When we pop the dynamic allocation we need to restore the SP link.
7730   SDLoc dl(Op);
7731 
7732   // Get the correct type for pointers.
7733   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7734 
7735   // Construct the stack pointer operand.
7736   bool isPPC64 = Subtarget.isPPC64();
7737   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7738   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7739 
7740   // Get the operands for the STACKRESTORE.
7741   SDValue Chain = Op.getOperand(0);
7742   SDValue SaveSP = Op.getOperand(1);
7743 
7744   // Load the old link SP.
7745   SDValue LoadLinkSP =
7746       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7747 
7748   // Restore the stack pointer.
7749   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7750 
7751   // Store the old link SP.
7752   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7753 }
7754 
7755 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7756   MachineFunction &MF = DAG.getMachineFunction();
7757   bool isPPC64 = Subtarget.isPPC64();
7758   EVT PtrVT = getPointerTy(MF.getDataLayout());
7759 
7760   // Get current frame pointer save index.  The users of this index will be
7761   // primarily DYNALLOC instructions.
7762   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7763   int RASI = FI->getReturnAddrSaveIndex();
7764 
7765   // If the frame pointer save index hasn't been defined yet.
7766   if (!RASI) {
7767     // Find out what the fix offset of the frame pointer save area.
7768     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7769     // Allocate the frame index for frame pointer save area.
7770     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7771     // Save the result.
7772     FI->setReturnAddrSaveIndex(RASI);
7773   }
7774   return DAG.getFrameIndex(RASI, PtrVT);
7775 }
7776 
7777 SDValue
7778 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7779   MachineFunction &MF = DAG.getMachineFunction();
7780   bool isPPC64 = Subtarget.isPPC64();
7781   EVT PtrVT = getPointerTy(MF.getDataLayout());
7782 
7783   // Get current frame pointer save index.  The users of this index will be
7784   // primarily DYNALLOC instructions.
7785   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7786   int FPSI = FI->getFramePointerSaveIndex();
7787 
7788   // If the frame pointer save index hasn't been defined yet.
7789   if (!FPSI) {
7790     // Find out what the fix offset of the frame pointer save area.
7791     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7792     // Allocate the frame index for frame pointer save area.
7793     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7794     // Save the result.
7795     FI->setFramePointerSaveIndex(FPSI);
7796   }
7797   return DAG.getFrameIndex(FPSI, PtrVT);
7798 }
7799 
7800 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7801                                                    SelectionDAG &DAG) const {
7802   MachineFunction &MF = DAG.getMachineFunction();
7803   // Get the inputs.
7804   SDValue Chain = Op.getOperand(0);
7805   SDValue Size  = Op.getOperand(1);
7806   SDLoc dl(Op);
7807 
7808   // Get the correct type for pointers.
7809   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7810   // Negate the size.
7811   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7812                                 DAG.getConstant(0, dl, PtrVT), Size);
7813   // Construct a node for the frame pointer save index.
7814   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7815   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7816   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7817   if (hasInlineStackProbe(MF))
7818     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7819   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7820 }
7821 
7822 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7823                                                      SelectionDAG &DAG) const {
7824   MachineFunction &MF = DAG.getMachineFunction();
7825 
7826   bool isPPC64 = Subtarget.isPPC64();
7827   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7828 
7829   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7830   return DAG.getFrameIndex(FI, PtrVT);
7831 }
7832 
7833 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7834                                                SelectionDAG &DAG) const {
7835   SDLoc DL(Op);
7836   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7837                      DAG.getVTList(MVT::i32, MVT::Other),
7838                      Op.getOperand(0), Op.getOperand(1));
7839 }
7840 
7841 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7842                                                 SelectionDAG &DAG) const {
7843   SDLoc DL(Op);
7844   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7845                      Op.getOperand(0), Op.getOperand(1));
7846 }
7847 
7848 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7849   if (Op.getValueType().isVector())
7850     return LowerVectorLoad(Op, DAG);
7851 
7852   assert(Op.getValueType() == MVT::i1 &&
7853          "Custom lowering only for i1 loads");
7854 
7855   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7856 
7857   SDLoc dl(Op);
7858   LoadSDNode *LD = cast<LoadSDNode>(Op);
7859 
7860   SDValue Chain = LD->getChain();
7861   SDValue BasePtr = LD->getBasePtr();
7862   MachineMemOperand *MMO = LD->getMemOperand();
7863 
7864   SDValue NewLD =
7865       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7866                      BasePtr, MVT::i8, MMO);
7867   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7868 
7869   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7870   return DAG.getMergeValues(Ops, dl);
7871 }
7872 
7873 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7874   if (Op.getOperand(1).getValueType().isVector())
7875     return LowerVectorStore(Op, DAG);
7876 
7877   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7878          "Custom lowering only for i1 stores");
7879 
7880   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7881 
7882   SDLoc dl(Op);
7883   StoreSDNode *ST = cast<StoreSDNode>(Op);
7884 
7885   SDValue Chain = ST->getChain();
7886   SDValue BasePtr = ST->getBasePtr();
7887   SDValue Value = ST->getValue();
7888   MachineMemOperand *MMO = ST->getMemOperand();
7889 
7890   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7891                       Value);
7892   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7893 }
7894 
7895 // FIXME: Remove this once the ANDI glue bug is fixed:
7896 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7897   assert(Op.getValueType() == MVT::i1 &&
7898          "Custom lowering only for i1 results");
7899 
7900   SDLoc DL(Op);
7901   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7902 }
7903 
7904 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7905                                                SelectionDAG &DAG) const {
7906 
7907   // Implements a vector truncate that fits in a vector register as a shuffle.
7908   // We want to legalize vector truncates down to where the source fits in
7909   // a vector register (and target is therefore smaller than vector register
7910   // size).  At that point legalization will try to custom lower the sub-legal
7911   // result and get here - where we can contain the truncate as a single target
7912   // operation.
7913 
7914   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7915   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7916   //
7917   // We will implement it for big-endian ordering as this (where x denotes
7918   // undefined):
7919   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7920   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7921   //
7922   // The same operation in little-endian ordering will be:
7923   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7924   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7925 
7926   EVT TrgVT = Op.getValueType();
7927   assert(TrgVT.isVector() && "Vector type expected.");
7928   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7929   EVT EltVT = TrgVT.getVectorElementType();
7930   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7931       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7932       !isPowerOf2_32(EltVT.getSizeInBits()))
7933     return SDValue();
7934 
7935   SDValue N1 = Op.getOperand(0);
7936   EVT SrcVT = N1.getValueType();
7937   unsigned SrcSize = SrcVT.getSizeInBits();
7938   if (SrcSize > 256 ||
7939       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7940       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7941     return SDValue();
7942   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7943     return SDValue();
7944 
7945   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7946   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7947 
7948   SDLoc DL(Op);
7949   SDValue Op1, Op2;
7950   if (SrcSize == 256) {
7951     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7952     EVT SplitVT =
7953         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7954     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7955     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7956                       DAG.getConstant(0, DL, VecIdxTy));
7957     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7958                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7959   }
7960   else {
7961     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7962     Op2 = DAG.getUNDEF(WideVT);
7963   }
7964 
7965   // First list the elements we want to keep.
7966   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7967   SmallVector<int, 16> ShuffV;
7968   if (Subtarget.isLittleEndian())
7969     for (unsigned i = 0; i < TrgNumElts; ++i)
7970       ShuffV.push_back(i * SizeMult);
7971   else
7972     for (unsigned i = 1; i <= TrgNumElts; ++i)
7973       ShuffV.push_back(i * SizeMult - 1);
7974 
7975   // Populate the remaining elements with undefs.
7976   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7977     // ShuffV.push_back(i + WideNumElts);
7978     ShuffV.push_back(WideNumElts + 1);
7979 
7980   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7981   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7982   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7983 }
7984 
7985 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7986 /// possible.
7987 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7988   // Not FP, or using SPE? Not a fsel.
7989   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7990       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7991     return Op;
7992 
7993   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7994 
7995   EVT ResVT = Op.getValueType();
7996   EVT CmpVT = Op.getOperand(0).getValueType();
7997   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7998   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7999   SDLoc dl(Op);
8000   SDNodeFlags Flags = Op.getNode()->getFlags();
8001 
8002   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
8003   // presence of infinities.
8004   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8005     switch (CC) {
8006     default:
8007       break;
8008     case ISD::SETOGT:
8009     case ISD::SETGT:
8010       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8011     case ISD::SETOLT:
8012     case ISD::SETLT:
8013       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8014     }
8015   }
8016 
8017   // We might be able to do better than this under some circumstances, but in
8018   // general, fsel-based lowering of select is a finite-math-only optimization.
8019   // For more information, see section F.3 of the 2.06 ISA specification.
8020   // With ISA 3.0
8021   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8022       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8023     return Op;
8024 
8025   // If the RHS of the comparison is a 0.0, we don't need to do the
8026   // subtraction at all.
8027   SDValue Sel1;
8028   if (isFloatingPointZero(RHS))
8029     switch (CC) {
8030     default: break;       // SETUO etc aren't handled by fsel.
8031     case ISD::SETNE:
8032       std::swap(TV, FV);
8033       LLVM_FALLTHROUGH;
8034     case ISD::SETEQ:
8035       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8036         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8037       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8038       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8039         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8040       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8041                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8042     case ISD::SETULT:
8043     case ISD::SETLT:
8044       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8045       LLVM_FALLTHROUGH;
8046     case ISD::SETOGE:
8047     case ISD::SETGE:
8048       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8049         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8050       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8051     case ISD::SETUGT:
8052     case ISD::SETGT:
8053       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8054       LLVM_FALLTHROUGH;
8055     case ISD::SETOLE:
8056     case ISD::SETLE:
8057       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8058         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8059       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8060                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8061     }
8062 
8063   SDValue Cmp;
8064   switch (CC) {
8065   default: break;       // SETUO etc aren't handled by fsel.
8066   case ISD::SETNE:
8067     std::swap(TV, FV);
8068     LLVM_FALLTHROUGH;
8069   case ISD::SETEQ:
8070     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8071     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8072       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8073     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8074     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8075       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8076     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8077                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8078   case ISD::SETULT:
8079   case ISD::SETLT:
8080     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8081     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8082       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8083     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8084   case ISD::SETOGE:
8085   case ISD::SETGE:
8086     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8087     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8088       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8089     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8090   case ISD::SETUGT:
8091   case ISD::SETGT:
8092     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8093     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8094       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8095     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8096   case ISD::SETOLE:
8097   case ISD::SETLE:
8098     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8099     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8100       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8101     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8102   }
8103   return Op;
8104 }
8105 
8106 static unsigned getPPCStrictOpcode(unsigned Opc) {
8107   switch (Opc) {
8108   default:
8109     llvm_unreachable("No strict version of this opcode!");
8110   case PPCISD::FCTIDZ:
8111     return PPCISD::STRICT_FCTIDZ;
8112   case PPCISD::FCTIWZ:
8113     return PPCISD::STRICT_FCTIWZ;
8114   case PPCISD::FCTIDUZ:
8115     return PPCISD::STRICT_FCTIDUZ;
8116   case PPCISD::FCTIWUZ:
8117     return PPCISD::STRICT_FCTIWUZ;
8118   case PPCISD::FCFID:
8119     return PPCISD::STRICT_FCFID;
8120   case PPCISD::FCFIDU:
8121     return PPCISD::STRICT_FCFIDU;
8122   case PPCISD::FCFIDS:
8123     return PPCISD::STRICT_FCFIDS;
8124   case PPCISD::FCFIDUS:
8125     return PPCISD::STRICT_FCFIDUS;
8126   }
8127 }
8128 
8129 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8130                               const PPCSubtarget &Subtarget) {
8131   SDLoc dl(Op);
8132   bool IsStrict = Op->isStrictFPOpcode();
8133   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8134                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8135 
8136   // TODO: Any other flags to propagate?
8137   SDNodeFlags Flags;
8138   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8139 
8140   // For strict nodes, source is the second operand.
8141   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8142   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8143   assert(Src.getValueType().isFloatingPoint());
8144   if (Src.getValueType() == MVT::f32) {
8145     if (IsStrict) {
8146       Src =
8147           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8148                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8149       Chain = Src.getValue(1);
8150     } else
8151       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8152   }
8153   SDValue Conv;
8154   unsigned Opc = ISD::DELETED_NODE;
8155   switch (Op.getSimpleValueType().SimpleTy) {
8156   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8157   case MVT::i32:
8158     Opc = IsSigned ? PPCISD::FCTIWZ
8159                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8160     break;
8161   case MVT::i64:
8162     assert((IsSigned || Subtarget.hasFPCVT()) &&
8163            "i64 FP_TO_UINT is supported only with FPCVT");
8164     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8165   }
8166   if (IsStrict) {
8167     Opc = getPPCStrictOpcode(Opc);
8168     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8169                        {Chain, Src}, Flags);
8170   } else {
8171     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8172   }
8173   return Conv;
8174 }
8175 
8176 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8177                                                SelectionDAG &DAG,
8178                                                const SDLoc &dl) const {
8179   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8180   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8181                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8182   bool IsStrict = Op->isStrictFPOpcode();
8183 
8184   // Convert the FP value to an int value through memory.
8185   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8186                   (IsSigned || Subtarget.hasFPCVT());
8187   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8188   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8189   MachinePointerInfo MPI =
8190       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8191 
8192   // Emit a store to the stack slot.
8193   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8194   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8195   if (i32Stack) {
8196     MachineFunction &MF = DAG.getMachineFunction();
8197     Alignment = Align(4);
8198     MachineMemOperand *MMO =
8199         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8200     SDValue Ops[] = { Chain, Tmp, FIPtr };
8201     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8202               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8203   } else
8204     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8205 
8206   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8207   // add in a bias on big endian.
8208   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8209     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8210                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8211     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8212   }
8213 
8214   RLI.Chain = Chain;
8215   RLI.Ptr = FIPtr;
8216   RLI.MPI = MPI;
8217   RLI.Alignment = Alignment;
8218 }
8219 
8220 /// Custom lowers floating point to integer conversions to use
8221 /// the direct move instructions available in ISA 2.07 to avoid the
8222 /// need for load/store combinations.
8223 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8224                                                     SelectionDAG &DAG,
8225                                                     const SDLoc &dl) const {
8226   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8227   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8228   if (Op->isStrictFPOpcode())
8229     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8230   else
8231     return Mov;
8232 }
8233 
8234 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8235                                           const SDLoc &dl) const {
8236   bool IsStrict = Op->isStrictFPOpcode();
8237   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8238                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8239   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8240   EVT SrcVT = Src.getValueType();
8241   EVT DstVT = Op.getValueType();
8242 
8243   // FP to INT conversions are legal for f128.
8244   if (SrcVT == MVT::f128)
8245     return Op;
8246 
8247   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8248   // PPC (the libcall is not available).
8249   if (SrcVT == MVT::ppcf128) {
8250     if (DstVT == MVT::i32) {
8251       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8252       // set other fast-math flags to FP operations in both strict and
8253       // non-strict cases. (FP_TO_SINT, FSUB)
8254       SDNodeFlags Flags;
8255       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8256 
8257       if (IsSigned) {
8258         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8259                                  DAG.getIntPtrConstant(0, dl));
8260         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8261                                  DAG.getIntPtrConstant(1, dl));
8262 
8263         // Add the two halves of the long double in round-to-zero mode, and use
8264         // a smaller FP_TO_SINT.
8265         if (IsStrict) {
8266           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8267                                     DAG.getVTList(MVT::f64, MVT::Other),
8268                                     {Op.getOperand(0), Lo, Hi}, Flags);
8269           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8270                              DAG.getVTList(MVT::i32, MVT::Other),
8271                              {Res.getValue(1), Res}, Flags);
8272         } else {
8273           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8274           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8275         }
8276       } else {
8277         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8278         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8279         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8280         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8281         if (IsStrict) {
8282           // Sel = Src < 0x80000000
8283           // FltOfs = select Sel, 0.0, 0x80000000
8284           // IntOfs = select Sel, 0, 0x80000000
8285           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8286           SDValue Chain = Op.getOperand(0);
8287           EVT SetCCVT =
8288               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8289           EVT DstSetCCVT =
8290               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8291           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8292                                      Chain, true);
8293           Chain = Sel.getValue(1);
8294 
8295           SDValue FltOfs = DAG.getSelect(
8296               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8297           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8298 
8299           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8300                                     DAG.getVTList(SrcVT, MVT::Other),
8301                                     {Chain, Src, FltOfs}, Flags);
8302           Chain = Val.getValue(1);
8303           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8304                                      DAG.getVTList(DstVT, MVT::Other),
8305                                      {Chain, Val}, Flags);
8306           Chain = SInt.getValue(1);
8307           SDValue IntOfs = DAG.getSelect(
8308               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8309           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8310           return DAG.getMergeValues({Result, Chain}, dl);
8311         } else {
8312           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8313           // FIXME: generated code sucks.
8314           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8315           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8316           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8317           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8318           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8319         }
8320       }
8321     }
8322 
8323     return SDValue();
8324   }
8325 
8326   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8327     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8328 
8329   ReuseLoadInfo RLI;
8330   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8331 
8332   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8333                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8334 }
8335 
8336 // We're trying to insert a regular store, S, and then a load, L. If the
8337 // incoming value, O, is a load, we might just be able to have our load use the
8338 // address used by O. However, we don't know if anything else will store to
8339 // that address before we can load from it. To prevent this situation, we need
8340 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8341 // the same chain operand as O, we create a token factor from the chain results
8342 // of O and L, and we replace all uses of O's chain result with that token
8343 // factor (see spliceIntoChain below for this last part).
8344 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8345                                             ReuseLoadInfo &RLI,
8346                                             SelectionDAG &DAG,
8347                                             ISD::LoadExtType ET) const {
8348   // Conservatively skip reusing for constrained FP nodes.
8349   if (Op->isStrictFPOpcode())
8350     return false;
8351 
8352   SDLoc dl(Op);
8353   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8354                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8355   if (ET == ISD::NON_EXTLOAD &&
8356       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8357       isOperationLegalOrCustom(Op.getOpcode(),
8358                                Op.getOperand(0).getValueType())) {
8359 
8360     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8361     return true;
8362   }
8363 
8364   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8365   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8366       LD->isNonTemporal())
8367     return false;
8368   if (LD->getMemoryVT() != MemVT)
8369     return false;
8370 
8371   RLI.Ptr = LD->getBasePtr();
8372   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8373     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8374            "Non-pre-inc AM on PPC?");
8375     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8376                           LD->getOffset());
8377   }
8378 
8379   RLI.Chain = LD->getChain();
8380   RLI.MPI = LD->getPointerInfo();
8381   RLI.IsDereferenceable = LD->isDereferenceable();
8382   RLI.IsInvariant = LD->isInvariant();
8383   RLI.Alignment = LD->getAlign();
8384   RLI.AAInfo = LD->getAAInfo();
8385   RLI.Ranges = LD->getRanges();
8386 
8387   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8388   return true;
8389 }
8390 
8391 // Given the head of the old chain, ResChain, insert a token factor containing
8392 // it and NewResChain, and make users of ResChain now be users of that token
8393 // factor.
8394 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8395 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8396                                         SDValue NewResChain,
8397                                         SelectionDAG &DAG) const {
8398   if (!ResChain)
8399     return;
8400 
8401   SDLoc dl(NewResChain);
8402 
8403   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8404                            NewResChain, DAG.getUNDEF(MVT::Other));
8405   assert(TF.getNode() != NewResChain.getNode() &&
8406          "A new TF really is required here");
8407 
8408   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8409   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8410 }
8411 
8412 /// Analyze profitability of direct move
8413 /// prefer float load to int load plus direct move
8414 /// when there is no integer use of int load
8415 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8416   SDNode *Origin = Op.getOperand(0).getNode();
8417   if (Origin->getOpcode() != ISD::LOAD)
8418     return true;
8419 
8420   // If there is no LXSIBZX/LXSIHZX, like Power8,
8421   // prefer direct move if the memory size is 1 or 2 bytes.
8422   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8423   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8424     return true;
8425 
8426   for (SDNode::use_iterator UI = Origin->use_begin(),
8427                             UE = Origin->use_end();
8428        UI != UE; ++UI) {
8429 
8430     // Only look at the users of the loaded value.
8431     if (UI.getUse().get().getResNo() != 0)
8432       continue;
8433 
8434     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8435         UI->getOpcode() != ISD::UINT_TO_FP &&
8436         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8437         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8438       return true;
8439   }
8440 
8441   return false;
8442 }
8443 
8444 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8445                               const PPCSubtarget &Subtarget,
8446                               SDValue Chain = SDValue()) {
8447   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8448                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8449   SDLoc dl(Op);
8450 
8451   // TODO: Any other flags to propagate?
8452   SDNodeFlags Flags;
8453   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8454 
8455   // If we have FCFIDS, then use it when converting to single-precision.
8456   // Otherwise, convert to double-precision and then round.
8457   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8458   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8459                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8460   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8461   if (Op->isStrictFPOpcode()) {
8462     if (!Chain)
8463       Chain = Op.getOperand(0);
8464     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8465                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8466   } else
8467     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8468 }
8469 
8470 /// Custom lowers integer to floating point conversions to use
8471 /// the direct move instructions available in ISA 2.07 to avoid the
8472 /// need for load/store combinations.
8473 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8474                                                     SelectionDAG &DAG,
8475                                                     const SDLoc &dl) const {
8476   assert((Op.getValueType() == MVT::f32 ||
8477           Op.getValueType() == MVT::f64) &&
8478          "Invalid floating point type as target of conversion");
8479   assert(Subtarget.hasFPCVT() &&
8480          "Int to FP conversions with direct moves require FPCVT");
8481   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8482   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8483   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8484                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8485   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8486   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8487   return convertIntToFP(Op, Mov, DAG, Subtarget);
8488 }
8489 
8490 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8491 
8492   EVT VecVT = Vec.getValueType();
8493   assert(VecVT.isVector() && "Expected a vector type.");
8494   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8495 
8496   EVT EltVT = VecVT.getVectorElementType();
8497   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8498   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8499 
8500   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8501   SmallVector<SDValue, 16> Ops(NumConcat);
8502   Ops[0] = Vec;
8503   SDValue UndefVec = DAG.getUNDEF(VecVT);
8504   for (unsigned i = 1; i < NumConcat; ++i)
8505     Ops[i] = UndefVec;
8506 
8507   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8508 }
8509 
8510 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8511                                                 const SDLoc &dl) const {
8512   bool IsStrict = Op->isStrictFPOpcode();
8513   unsigned Opc = Op.getOpcode();
8514   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8515   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8516           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8517          "Unexpected conversion type");
8518   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8519          "Supports conversions to v2f64/v4f32 only.");
8520 
8521   // TODO: Any other flags to propagate?
8522   SDNodeFlags Flags;
8523   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8524 
8525   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8526   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8527 
8528   SDValue Wide = widenVec(DAG, Src, dl);
8529   EVT WideVT = Wide.getValueType();
8530   unsigned WideNumElts = WideVT.getVectorNumElements();
8531   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8532 
8533   SmallVector<int, 16> ShuffV;
8534   for (unsigned i = 0; i < WideNumElts; ++i)
8535     ShuffV.push_back(i + WideNumElts);
8536 
8537   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8538   int SaveElts = FourEltRes ? 4 : 2;
8539   if (Subtarget.isLittleEndian())
8540     for (int i = 0; i < SaveElts; i++)
8541       ShuffV[i * Stride] = i;
8542   else
8543     for (int i = 1; i <= SaveElts; i++)
8544       ShuffV[i * Stride - 1] = i - 1;
8545 
8546   SDValue ShuffleSrc2 =
8547       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8548   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8549 
8550   SDValue Extend;
8551   if (SignedConv) {
8552     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8553     EVT ExtVT = Src.getValueType();
8554     if (Subtarget.hasP9Altivec())
8555       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8556                                IntermediateVT.getVectorNumElements());
8557 
8558     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8559                          DAG.getValueType(ExtVT));
8560   } else
8561     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8562 
8563   if (IsStrict)
8564     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8565                        {Op.getOperand(0), Extend}, Flags);
8566 
8567   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8568 }
8569 
8570 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8571                                           SelectionDAG &DAG) const {
8572   SDLoc dl(Op);
8573   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8574                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8575   bool IsStrict = Op->isStrictFPOpcode();
8576   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8577   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8578 
8579   // TODO: Any other flags to propagate?
8580   SDNodeFlags Flags;
8581   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8582 
8583   EVT InVT = Src.getValueType();
8584   EVT OutVT = Op.getValueType();
8585   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8586       isOperationCustom(Op.getOpcode(), InVT))
8587     return LowerINT_TO_FPVector(Op, DAG, dl);
8588 
8589   // Conversions to f128 are legal.
8590   if (Op.getValueType() == MVT::f128)
8591     return Op;
8592 
8593   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8594   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8595     return SDValue();
8596 
8597   if (Src.getValueType() == MVT::i1)
8598     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8599                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8600                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8601 
8602   // If we have direct moves, we can do all the conversion, skip the store/load
8603   // however, without FPCVT we can't do most conversions.
8604   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8605       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8606     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8607 
8608   assert((IsSigned || Subtarget.hasFPCVT()) &&
8609          "UINT_TO_FP is supported only with FPCVT");
8610 
8611   if (Src.getValueType() == MVT::i64) {
8612     SDValue SINT = Src;
8613     // When converting to single-precision, we actually need to convert
8614     // to double-precision first and then round to single-precision.
8615     // To avoid double-rounding effects during that operation, we have
8616     // to prepare the input operand.  Bits that might be truncated when
8617     // converting to double-precision are replaced by a bit that won't
8618     // be lost at this stage, but is below the single-precision rounding
8619     // position.
8620     //
8621     // However, if -enable-unsafe-fp-math is in effect, accept double
8622     // rounding to avoid the extra overhead.
8623     if (Op.getValueType() == MVT::f32 &&
8624         !Subtarget.hasFPCVT() &&
8625         !DAG.getTarget().Options.UnsafeFPMath) {
8626 
8627       // Twiddle input to make sure the low 11 bits are zero.  (If this
8628       // is the case, we are guaranteed the value will fit into the 53 bit
8629       // mantissa of an IEEE double-precision value without rounding.)
8630       // If any of those low 11 bits were not zero originally, make sure
8631       // bit 12 (value 2048) is set instead, so that the final rounding
8632       // to single-precision gets the correct result.
8633       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8634                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8635       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8636                           Round, DAG.getConstant(2047, dl, MVT::i64));
8637       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8638       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8639                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8640 
8641       // However, we cannot use that value unconditionally: if the magnitude
8642       // of the input value is small, the bit-twiddling we did above might
8643       // end up visibly changing the output.  Fortunately, in that case, we
8644       // don't need to twiddle bits since the original input will convert
8645       // exactly to double-precision floating-point already.  Therefore,
8646       // construct a conditional to use the original value if the top 11
8647       // bits are all sign-bit copies, and use the rounded value computed
8648       // above otherwise.
8649       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8650                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8651       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8652                          Cond, DAG.getConstant(1, dl, MVT::i64));
8653       Cond = DAG.getSetCC(
8654           dl,
8655           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8656           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8657 
8658       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8659     }
8660 
8661     ReuseLoadInfo RLI;
8662     SDValue Bits;
8663 
8664     MachineFunction &MF = DAG.getMachineFunction();
8665     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8666       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8667                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8668       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8669     } else if (Subtarget.hasLFIWAX() &&
8670                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8671       MachineMemOperand *MMO =
8672         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8673                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8674       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8675       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8676                                      DAG.getVTList(MVT::f64, MVT::Other),
8677                                      Ops, MVT::i32, MMO);
8678       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8679     } else if (Subtarget.hasFPCVT() &&
8680                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8681       MachineMemOperand *MMO =
8682         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8683                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8684       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8685       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8686                                      DAG.getVTList(MVT::f64, MVT::Other),
8687                                      Ops, MVT::i32, MMO);
8688       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8689     } else if (((Subtarget.hasLFIWAX() &&
8690                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8691                 (Subtarget.hasFPCVT() &&
8692                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8693                SINT.getOperand(0).getValueType() == MVT::i32) {
8694       MachineFrameInfo &MFI = MF.getFrameInfo();
8695       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8696 
8697       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8698       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8699 
8700       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8701                                    MachinePointerInfo::getFixedStack(
8702                                        DAG.getMachineFunction(), FrameIdx));
8703       Chain = Store;
8704 
8705       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8706              "Expected an i32 store");
8707 
8708       RLI.Ptr = FIdx;
8709       RLI.Chain = Chain;
8710       RLI.MPI =
8711           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8712       RLI.Alignment = Align(4);
8713 
8714       MachineMemOperand *MMO =
8715         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8716                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8717       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8718       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8719                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8720                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8721                                      Ops, MVT::i32, MMO);
8722       Chain = Bits.getValue(1);
8723     } else
8724       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8725 
8726     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8727     if (IsStrict)
8728       Chain = FP.getValue(1);
8729 
8730     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8731       if (IsStrict)
8732         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8733                          DAG.getVTList(MVT::f32, MVT::Other),
8734                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8735       else
8736         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8737                          DAG.getIntPtrConstant(0, dl));
8738     }
8739     return FP;
8740   }
8741 
8742   assert(Src.getValueType() == MVT::i32 &&
8743          "Unhandled INT_TO_FP type in custom expander!");
8744   // Since we only generate this in 64-bit mode, we can take advantage of
8745   // 64-bit registers.  In particular, sign extend the input value into the
8746   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8747   // then lfd it and fcfid it.
8748   MachineFunction &MF = DAG.getMachineFunction();
8749   MachineFrameInfo &MFI = MF.getFrameInfo();
8750   EVT PtrVT = getPointerTy(MF.getDataLayout());
8751 
8752   SDValue Ld;
8753   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8754     ReuseLoadInfo RLI;
8755     bool ReusingLoad;
8756     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8757       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8758       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8759 
8760       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8761                                    MachinePointerInfo::getFixedStack(
8762                                        DAG.getMachineFunction(), FrameIdx));
8763       Chain = Store;
8764 
8765       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8766              "Expected an i32 store");
8767 
8768       RLI.Ptr = FIdx;
8769       RLI.Chain = Chain;
8770       RLI.MPI =
8771           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8772       RLI.Alignment = Align(4);
8773     }
8774 
8775     MachineMemOperand *MMO =
8776       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8777                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8778     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8779     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8780                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8781                                  MVT::i32, MMO);
8782     Chain = Ld.getValue(1);
8783     if (ReusingLoad)
8784       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8785   } else {
8786     assert(Subtarget.isPPC64() &&
8787            "i32->FP without LFIWAX supported only on PPC64");
8788 
8789     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8790     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8791 
8792     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8793 
8794     // STD the extended value into the stack slot.
8795     SDValue Store = DAG.getStore(
8796         Chain, dl, Ext64, FIdx,
8797         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8798     Chain = Store;
8799 
8800     // Load the value as a double.
8801     Ld = DAG.getLoad(
8802         MVT::f64, dl, Chain, FIdx,
8803         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8804     Chain = Ld.getValue(1);
8805   }
8806 
8807   // FCFID it and return it.
8808   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8809   if (IsStrict)
8810     Chain = FP.getValue(1);
8811   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8812     if (IsStrict)
8813       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8814                        DAG.getVTList(MVT::f32, MVT::Other),
8815                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8816     else
8817       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8818                        DAG.getIntPtrConstant(0, dl));
8819   }
8820   return FP;
8821 }
8822 
8823 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8824                                             SelectionDAG &DAG) const {
8825   SDLoc dl(Op);
8826   /*
8827    The rounding mode is in bits 30:31 of FPSR, and has the following
8828    settings:
8829      00 Round to nearest
8830      01 Round to 0
8831      10 Round to +inf
8832      11 Round to -inf
8833 
8834   FLT_ROUNDS, on the other hand, expects the following:
8835     -1 Undefined
8836      0 Round to 0
8837      1 Round to nearest
8838      2 Round to +inf
8839      3 Round to -inf
8840 
8841   To perform the conversion, we do:
8842     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8843   */
8844 
8845   MachineFunction &MF = DAG.getMachineFunction();
8846   EVT VT = Op.getValueType();
8847   EVT PtrVT = getPointerTy(MF.getDataLayout());
8848 
8849   // Save FP Control Word to register
8850   SDValue Chain = Op.getOperand(0);
8851   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8852   Chain = MFFS.getValue(1);
8853 
8854   // Save FP register to stack slot
8855   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8856   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8857   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8858 
8859   // Load FP Control Word from low 32 bits of stack slot.
8860   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8861   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8862   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8863   Chain = CWD.getValue(1);
8864 
8865   // Transform as necessary
8866   SDValue CWD1 =
8867     DAG.getNode(ISD::AND, dl, MVT::i32,
8868                 CWD, DAG.getConstant(3, dl, MVT::i32));
8869   SDValue CWD2 =
8870     DAG.getNode(ISD::SRL, dl, MVT::i32,
8871                 DAG.getNode(ISD::AND, dl, MVT::i32,
8872                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8873                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8874                             DAG.getConstant(3, dl, MVT::i32)),
8875                 DAG.getConstant(1, dl, MVT::i32));
8876 
8877   SDValue RetVal =
8878     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8879 
8880   RetVal =
8881       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8882                   dl, VT, RetVal);
8883 
8884   return DAG.getMergeValues({RetVal, Chain}, dl);
8885 }
8886 
8887 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8888   EVT VT = Op.getValueType();
8889   unsigned BitWidth = VT.getSizeInBits();
8890   SDLoc dl(Op);
8891   assert(Op.getNumOperands() == 3 &&
8892          VT == Op.getOperand(1).getValueType() &&
8893          "Unexpected SHL!");
8894 
8895   // Expand into a bunch of logical ops.  Note that these ops
8896   // depend on the PPC behavior for oversized shift amounts.
8897   SDValue Lo = Op.getOperand(0);
8898   SDValue Hi = Op.getOperand(1);
8899   SDValue Amt = Op.getOperand(2);
8900   EVT AmtVT = Amt.getValueType();
8901 
8902   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8903                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8904   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8905   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8906   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8907   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8908                              DAG.getConstant(-BitWidth, dl, AmtVT));
8909   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8910   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8911   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8912   SDValue OutOps[] = { OutLo, OutHi };
8913   return DAG.getMergeValues(OutOps, dl);
8914 }
8915 
8916 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8917   EVT VT = Op.getValueType();
8918   SDLoc dl(Op);
8919   unsigned BitWidth = VT.getSizeInBits();
8920   assert(Op.getNumOperands() == 3 &&
8921          VT == Op.getOperand(1).getValueType() &&
8922          "Unexpected SRL!");
8923 
8924   // Expand into a bunch of logical ops.  Note that these ops
8925   // depend on the PPC behavior for oversized shift amounts.
8926   SDValue Lo = Op.getOperand(0);
8927   SDValue Hi = Op.getOperand(1);
8928   SDValue Amt = Op.getOperand(2);
8929   EVT AmtVT = Amt.getValueType();
8930 
8931   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8932                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8933   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8934   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8935   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8936   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8937                              DAG.getConstant(-BitWidth, dl, AmtVT));
8938   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8939   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8940   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8941   SDValue OutOps[] = { OutLo, OutHi };
8942   return DAG.getMergeValues(OutOps, dl);
8943 }
8944 
8945 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8946   SDLoc dl(Op);
8947   EVT VT = Op.getValueType();
8948   unsigned BitWidth = VT.getSizeInBits();
8949   assert(Op.getNumOperands() == 3 &&
8950          VT == Op.getOperand(1).getValueType() &&
8951          "Unexpected SRA!");
8952 
8953   // Expand into a bunch of logical ops, followed by a select_cc.
8954   SDValue Lo = Op.getOperand(0);
8955   SDValue Hi = Op.getOperand(1);
8956   SDValue Amt = Op.getOperand(2);
8957   EVT AmtVT = Amt.getValueType();
8958 
8959   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8960                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8961   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8962   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8963   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8964   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8965                              DAG.getConstant(-BitWidth, dl, AmtVT));
8966   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8967   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8968   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8969                                   Tmp4, Tmp6, ISD::SETLE);
8970   SDValue OutOps[] = { OutLo, OutHi };
8971   return DAG.getMergeValues(OutOps, dl);
8972 }
8973 
8974 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8975                                             SelectionDAG &DAG) const {
8976   SDLoc dl(Op);
8977   EVT VT = Op.getValueType();
8978   unsigned BitWidth = VT.getSizeInBits();
8979 
8980   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8981   SDValue X = Op.getOperand(0);
8982   SDValue Y = Op.getOperand(1);
8983   SDValue Z = Op.getOperand(2);
8984   EVT AmtVT = Z.getValueType();
8985 
8986   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8987   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8988   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8989   // on PowerPC shift by BW being well defined.
8990   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8991                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8992   SDValue SubZ =
8993       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8994   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8995   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8996   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8997 }
8998 
8999 //===----------------------------------------------------------------------===//
9000 // Vector related lowering.
9001 //
9002 
9003 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
9004 /// element size of SplatSize. Cast the result to VT.
9005 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9006                                       SelectionDAG &DAG, const SDLoc &dl) {
9007   static const MVT VTys[] = { // canonical VT to use for each size.
9008     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9009   };
9010 
9011   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9012 
9013   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9014   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
9015     SplatSize = 1;
9016     Val = 0xFF;
9017   }
9018 
9019   EVT CanonicalVT = VTys[SplatSize-1];
9020 
9021   // Build a canonical splat for this value.
9022   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
9023 }
9024 
9025 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9026 /// specified intrinsic ID.
9027 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
9028                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
9029   if (DestVT == MVT::Other) DestVT = Op.getValueType();
9030   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9031                      DAG.getConstant(IID, dl, MVT::i32), Op);
9032 }
9033 
9034 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9035 /// specified intrinsic ID.
9036 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
9037                                 SelectionDAG &DAG, const SDLoc &dl,
9038                                 EVT DestVT = MVT::Other) {
9039   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9040   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9041                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9042 }
9043 
9044 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9045 /// specified intrinsic ID.
9046 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9047                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9048                                 EVT DestVT = MVT::Other) {
9049   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9050   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9051                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9052 }
9053 
9054 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9055 /// amount.  The result has the specified value type.
9056 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9057                            SelectionDAG &DAG, const SDLoc &dl) {
9058   // Force LHS/RHS to be the right type.
9059   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9060   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9061 
9062   int Ops[16];
9063   for (unsigned i = 0; i != 16; ++i)
9064     Ops[i] = i + Amt;
9065   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9066   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9067 }
9068 
9069 /// Do we have an efficient pattern in a .td file for this node?
9070 ///
9071 /// \param V - pointer to the BuildVectorSDNode being matched
9072 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9073 ///
9074 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9075 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9076 /// the opposite is true (expansion is beneficial) are:
9077 /// - The node builds a vector out of integers that are not 32 or 64-bits
9078 /// - The node builds a vector out of constants
9079 /// - The node is a "load-and-splat"
9080 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9081 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9082                                             bool HasDirectMove,
9083                                             bool HasP8Vector) {
9084   EVT VecVT = V->getValueType(0);
9085   bool RightType = VecVT == MVT::v2f64 ||
9086     (HasP8Vector && VecVT == MVT::v4f32) ||
9087     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9088   if (!RightType)
9089     return false;
9090 
9091   bool IsSplat = true;
9092   bool IsLoad = false;
9093   SDValue Op0 = V->getOperand(0);
9094 
9095   // This function is called in a block that confirms the node is not a constant
9096   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9097   // different constants.
9098   if (V->isConstant())
9099     return false;
9100   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9101     if (V->getOperand(i).isUndef())
9102       return false;
9103     // We want to expand nodes that represent load-and-splat even if the
9104     // loaded value is a floating point truncation or conversion to int.
9105     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9106         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9107          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9108         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9109          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9110         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9111          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9112       IsLoad = true;
9113     // If the operands are different or the input is not a load and has more
9114     // uses than just this BV node, then it isn't a splat.
9115     if (V->getOperand(i) != Op0 ||
9116         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9117       IsSplat = false;
9118   }
9119   return !(IsSplat && IsLoad);
9120 }
9121 
9122 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9123 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9124 
9125   SDLoc dl(Op);
9126   SDValue Op0 = Op->getOperand(0);
9127 
9128   if ((Op.getValueType() != MVT::f128) ||
9129       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9130       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9131       (Op0.getOperand(1).getValueType() != MVT::i64))
9132     return SDValue();
9133 
9134   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9135                      Op0.getOperand(1));
9136 }
9137 
9138 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9139   const SDValue *InputLoad = &Op;
9140   if (InputLoad->getOpcode() == ISD::BITCAST)
9141     InputLoad = &InputLoad->getOperand(0);
9142   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9143       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9144     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9145     InputLoad = &InputLoad->getOperand(0);
9146   }
9147   if (InputLoad->getOpcode() != ISD::LOAD)
9148     return nullptr;
9149   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9150   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9151 }
9152 
9153 // Convert the argument APFloat to a single precision APFloat if there is no
9154 // loss in information during the conversion to single precision APFloat and the
9155 // resulting number is not a denormal number. Return true if successful.
9156 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9157   APFloat APFloatToConvert = ArgAPFloat;
9158   bool LosesInfo = true;
9159   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9160                            &LosesInfo);
9161   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9162   if (Success)
9163     ArgAPFloat = APFloatToConvert;
9164   return Success;
9165 }
9166 
9167 // Bitcast the argument APInt to a double and convert it to a single precision
9168 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9169 // argument if there is no loss in information during the conversion from
9170 // double to single precision APFloat and the resulting number is not a denormal
9171 // number. Return true if successful.
9172 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9173   double DpValue = ArgAPInt.bitsToDouble();
9174   APFloat APFloatDp(DpValue);
9175   bool Success = convertToNonDenormSingle(APFloatDp);
9176   if (Success)
9177     ArgAPInt = APFloatDp.bitcastToAPInt();
9178   return Success;
9179 }
9180 
9181 // If this is a case we can't handle, return null and let the default
9182 // expansion code take care of it.  If we CAN select this case, and if it
9183 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9184 // this case more efficiently than a constant pool load, lower it to the
9185 // sequence of ops that should be used.
9186 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9187                                              SelectionDAG &DAG) const {
9188   SDLoc dl(Op);
9189   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9190   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9191 
9192   // Check if this is a splat of a constant value.
9193   APInt APSplatBits, APSplatUndef;
9194   unsigned SplatBitSize;
9195   bool HasAnyUndefs;
9196   bool BVNIsConstantSplat =
9197       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9198                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9199 
9200   // If it is a splat of a double, check if we can shrink it to a 32 bit
9201   // non-denormal float which when converted back to double gives us the same
9202   // double. This is to exploit the XXSPLTIDP instruction.
9203   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9204       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9205       convertToNonDenormSingle(APSplatBits)) {
9206     SDValue SplatNode = DAG.getNode(
9207         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9208         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9209     return DAG.getBitcast(Op.getValueType(), SplatNode);
9210   }
9211 
9212   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9213 
9214     bool IsPermutedLoad = false;
9215     const SDValue *InputLoad =
9216         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9217     // Handle load-and-splat patterns as we have instructions that will do this
9218     // in one go.
9219     if (InputLoad && DAG.isSplatValue(Op, true)) {
9220       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9221 
9222       // We have handling for 4 and 8 byte elements.
9223       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9224 
9225       // Checking for a single use of this load, we have to check for vector
9226       // width (128 bits) / ElementSize uses (since each operand of the
9227       // BUILD_VECTOR is a separate use of the value.
9228       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9229           ((Subtarget.hasVSX() && ElementSize == 64) ||
9230            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9231         SDValue Ops[] = {
9232           LD->getChain(),    // Chain
9233           LD->getBasePtr(),  // Ptr
9234           DAG.getValueType(Op.getValueType()) // VT
9235         };
9236         return
9237           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9238                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9239                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9240       }
9241     }
9242 
9243     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9244     // lowered to VSX instructions under certain conditions.
9245     // Without VSX, there is no pattern more efficient than expanding the node.
9246     if (Subtarget.hasVSX() &&
9247         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9248                                         Subtarget.hasP8Vector()))
9249       return Op;
9250     return SDValue();
9251   }
9252 
9253   uint64_t SplatBits = APSplatBits.getZExtValue();
9254   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9255   unsigned SplatSize = SplatBitSize / 8;
9256 
9257   // First, handle single instruction cases.
9258 
9259   // All zeros?
9260   if (SplatBits == 0) {
9261     // Canonicalize all zero vectors to be v4i32.
9262     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9263       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9264       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9265     }
9266     return Op;
9267   }
9268 
9269   // We have XXSPLTIW for constant splats four bytes wide.
9270   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9271   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9272   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9273   // turned into a 4-byte splat of 0xABABABAB.
9274   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9275     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
9276                                   Op.getValueType(), DAG, dl);
9277 
9278   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9279     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9280                                   dl);
9281 
9282   // We have XXSPLTIB for constant splats one byte wide.
9283   if (Subtarget.hasP9Vector() && SplatSize == 1)
9284     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9285                                   dl);
9286 
9287   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9288   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9289                     (32-SplatBitSize));
9290   if (SextVal >= -16 && SextVal <= 15)
9291     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9292                                   dl);
9293 
9294   // Two instruction sequences.
9295 
9296   // If this value is in the range [-32,30] and is even, use:
9297   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9298   // If this value is in the range [17,31] and is odd, use:
9299   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9300   // If this value is in the range [-31,-17] and is odd, use:
9301   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9302   // Note the last two are three-instruction sequences.
9303   if (SextVal >= -32 && SextVal <= 31) {
9304     // To avoid having these optimizations undone by constant folding,
9305     // we convert to a pseudo that will be expanded later into one of
9306     // the above forms.
9307     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9308     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9309               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9310     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9311     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9312     if (VT == Op.getValueType())
9313       return RetVal;
9314     else
9315       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9316   }
9317 
9318   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9319   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9320   // for fneg/fabs.
9321   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9322     // Make -1 and vspltisw -1:
9323     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9324 
9325     // Make the VSLW intrinsic, computing 0x8000_0000.
9326     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9327                                    OnesV, DAG, dl);
9328 
9329     // xor by OnesV to invert it.
9330     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9331     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9332   }
9333 
9334   // Check to see if this is a wide variety of vsplti*, binop self cases.
9335   static const signed char SplatCsts[] = {
9336     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9337     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9338   };
9339 
9340   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9341     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9342     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9343     int i = SplatCsts[idx];
9344 
9345     // Figure out what shift amount will be used by altivec if shifted by i in
9346     // this splat size.
9347     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9348 
9349     // vsplti + shl self.
9350     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9351       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9352       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9353         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9354         Intrinsic::ppc_altivec_vslw
9355       };
9356       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9357       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9358     }
9359 
9360     // vsplti + srl self.
9361     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9362       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9363       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9364         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9365         Intrinsic::ppc_altivec_vsrw
9366       };
9367       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9368       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9369     }
9370 
9371     // vsplti + sra self.
9372     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9373       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9374       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9375         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9376         Intrinsic::ppc_altivec_vsraw
9377       };
9378       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9379       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9380     }
9381 
9382     // vsplti + rol self.
9383     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9384                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9385       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9386       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9387         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9388         Intrinsic::ppc_altivec_vrlw
9389       };
9390       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9391       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9392     }
9393 
9394     // t = vsplti c, result = vsldoi t, t, 1
9395     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9396       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9397       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9398       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9399     }
9400     // t = vsplti c, result = vsldoi t, t, 2
9401     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9402       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9403       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9404       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9405     }
9406     // t = vsplti c, result = vsldoi t, t, 3
9407     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9408       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9409       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9410       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9411     }
9412   }
9413 
9414   return SDValue();
9415 }
9416 
9417 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9418 /// the specified operations to build the shuffle.
9419 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9420                                       SDValue RHS, SelectionDAG &DAG,
9421                                       const SDLoc &dl) {
9422   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9423   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9424   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9425 
9426   enum {
9427     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9428     OP_VMRGHW,
9429     OP_VMRGLW,
9430     OP_VSPLTISW0,
9431     OP_VSPLTISW1,
9432     OP_VSPLTISW2,
9433     OP_VSPLTISW3,
9434     OP_VSLDOI4,
9435     OP_VSLDOI8,
9436     OP_VSLDOI12
9437   };
9438 
9439   if (OpNum == OP_COPY) {
9440     if (LHSID == (1*9+2)*9+3) return LHS;
9441     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9442     return RHS;
9443   }
9444 
9445   SDValue OpLHS, OpRHS;
9446   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9447   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9448 
9449   int ShufIdxs[16];
9450   switch (OpNum) {
9451   default: llvm_unreachable("Unknown i32 permute!");
9452   case OP_VMRGHW:
9453     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9454     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9455     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9456     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9457     break;
9458   case OP_VMRGLW:
9459     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9460     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9461     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9462     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9463     break;
9464   case OP_VSPLTISW0:
9465     for (unsigned i = 0; i != 16; ++i)
9466       ShufIdxs[i] = (i&3)+0;
9467     break;
9468   case OP_VSPLTISW1:
9469     for (unsigned i = 0; i != 16; ++i)
9470       ShufIdxs[i] = (i&3)+4;
9471     break;
9472   case OP_VSPLTISW2:
9473     for (unsigned i = 0; i != 16; ++i)
9474       ShufIdxs[i] = (i&3)+8;
9475     break;
9476   case OP_VSPLTISW3:
9477     for (unsigned i = 0; i != 16; ++i)
9478       ShufIdxs[i] = (i&3)+12;
9479     break;
9480   case OP_VSLDOI4:
9481     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9482   case OP_VSLDOI8:
9483     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9484   case OP_VSLDOI12:
9485     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9486   }
9487   EVT VT = OpLHS.getValueType();
9488   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9489   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9490   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9491   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9492 }
9493 
9494 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9495 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9496 /// SDValue.
9497 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9498                                            SelectionDAG &DAG) const {
9499   const unsigned BytesInVector = 16;
9500   bool IsLE = Subtarget.isLittleEndian();
9501   SDLoc dl(N);
9502   SDValue V1 = N->getOperand(0);
9503   SDValue V2 = N->getOperand(1);
9504   unsigned ShiftElts = 0, InsertAtByte = 0;
9505   bool Swap = false;
9506 
9507   // Shifts required to get the byte we want at element 7.
9508   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9509                                    0, 15, 14, 13, 12, 11, 10, 9};
9510   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9511                                 1, 2,  3,  4,  5,  6,  7,  8};
9512 
9513   ArrayRef<int> Mask = N->getMask();
9514   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9515 
9516   // For each mask element, find out if we're just inserting something
9517   // from V2 into V1 or vice versa.
9518   // Possible permutations inserting an element from V2 into V1:
9519   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9520   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9521   //   ...
9522   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9523   // Inserting from V1 into V2 will be similar, except mask range will be
9524   // [16,31].
9525 
9526   bool FoundCandidate = false;
9527   // If both vector operands for the shuffle are the same vector, the mask
9528   // will contain only elements from the first one and the second one will be
9529   // undef.
9530   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9531   // Go through the mask of half-words to find an element that's being moved
9532   // from one vector to the other.
9533   for (unsigned i = 0; i < BytesInVector; ++i) {
9534     unsigned CurrentElement = Mask[i];
9535     // If 2nd operand is undefined, we should only look for element 7 in the
9536     // Mask.
9537     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9538       continue;
9539 
9540     bool OtherElementsInOrder = true;
9541     // Examine the other elements in the Mask to see if they're in original
9542     // order.
9543     for (unsigned j = 0; j < BytesInVector; ++j) {
9544       if (j == i)
9545         continue;
9546       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9547       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9548       // in which we always assume we're always picking from the 1st operand.
9549       int MaskOffset =
9550           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9551       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9552         OtherElementsInOrder = false;
9553         break;
9554       }
9555     }
9556     // If other elements are in original order, we record the number of shifts
9557     // we need to get the element we want into element 7. Also record which byte
9558     // in the vector we should insert into.
9559     if (OtherElementsInOrder) {
9560       // If 2nd operand is undefined, we assume no shifts and no swapping.
9561       if (V2.isUndef()) {
9562         ShiftElts = 0;
9563         Swap = false;
9564       } else {
9565         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9566         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9567                          : BigEndianShifts[CurrentElement & 0xF];
9568         Swap = CurrentElement < BytesInVector;
9569       }
9570       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9571       FoundCandidate = true;
9572       break;
9573     }
9574   }
9575 
9576   if (!FoundCandidate)
9577     return SDValue();
9578 
9579   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9580   // optionally with VECSHL if shift is required.
9581   if (Swap)
9582     std::swap(V1, V2);
9583   if (V2.isUndef())
9584     V2 = V1;
9585   if (ShiftElts) {
9586     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9587                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9588     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9589                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9590   }
9591   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9592                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9593 }
9594 
9595 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9596 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9597 /// SDValue.
9598 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9599                                            SelectionDAG &DAG) const {
9600   const unsigned NumHalfWords = 8;
9601   const unsigned BytesInVector = NumHalfWords * 2;
9602   // Check that the shuffle is on half-words.
9603   if (!isNByteElemShuffleMask(N, 2, 1))
9604     return SDValue();
9605 
9606   bool IsLE = Subtarget.isLittleEndian();
9607   SDLoc dl(N);
9608   SDValue V1 = N->getOperand(0);
9609   SDValue V2 = N->getOperand(1);
9610   unsigned ShiftElts = 0, InsertAtByte = 0;
9611   bool Swap = false;
9612 
9613   // Shifts required to get the half-word we want at element 3.
9614   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9615   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9616 
9617   uint32_t Mask = 0;
9618   uint32_t OriginalOrderLow = 0x1234567;
9619   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9620   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9621   // 32-bit space, only need 4-bit nibbles per element.
9622   for (unsigned i = 0; i < NumHalfWords; ++i) {
9623     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9624     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9625   }
9626 
9627   // For each mask element, find out if we're just inserting something
9628   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9629   // from V2 into V1:
9630   //   X, 1, 2, 3, 4, 5, 6, 7
9631   //   0, X, 2, 3, 4, 5, 6, 7
9632   //   0, 1, X, 3, 4, 5, 6, 7
9633   //   0, 1, 2, X, 4, 5, 6, 7
9634   //   0, 1, 2, 3, X, 5, 6, 7
9635   //   0, 1, 2, 3, 4, X, 6, 7
9636   //   0, 1, 2, 3, 4, 5, X, 7
9637   //   0, 1, 2, 3, 4, 5, 6, X
9638   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9639 
9640   bool FoundCandidate = false;
9641   // Go through the mask of half-words to find an element that's being moved
9642   // from one vector to the other.
9643   for (unsigned i = 0; i < NumHalfWords; ++i) {
9644     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9645     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9646     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9647     uint32_t TargetOrder = 0x0;
9648 
9649     // If both vector operands for the shuffle are the same vector, the mask
9650     // will contain only elements from the first one and the second one will be
9651     // undef.
9652     if (V2.isUndef()) {
9653       ShiftElts = 0;
9654       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9655       TargetOrder = OriginalOrderLow;
9656       Swap = false;
9657       // Skip if not the correct element or mask of other elements don't equal
9658       // to our expected order.
9659       if (MaskOneElt == VINSERTHSrcElem &&
9660           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9661         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9662         FoundCandidate = true;
9663         break;
9664       }
9665     } else { // If both operands are defined.
9666       // Target order is [8,15] if the current mask is between [0,7].
9667       TargetOrder =
9668           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9669       // Skip if mask of other elements don't equal our expected order.
9670       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9671         // We only need the last 3 bits for the number of shifts.
9672         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9673                          : BigEndianShifts[MaskOneElt & 0x7];
9674         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9675         Swap = MaskOneElt < NumHalfWords;
9676         FoundCandidate = true;
9677         break;
9678       }
9679     }
9680   }
9681 
9682   if (!FoundCandidate)
9683     return SDValue();
9684 
9685   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9686   // optionally with VECSHL if shift is required.
9687   if (Swap)
9688     std::swap(V1, V2);
9689   if (V2.isUndef())
9690     V2 = V1;
9691   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9692   if (ShiftElts) {
9693     // Double ShiftElts because we're left shifting on v16i8 type.
9694     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9695                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9696     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9697     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9698                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9699     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9700   }
9701   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9702   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9703                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9704   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9705 }
9706 
9707 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9708 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9709 /// return the default SDValue.
9710 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9711                                               SelectionDAG &DAG) const {
9712   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9713   // to v16i8. Peek through the bitcasts to get the actual operands.
9714   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9715   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9716 
9717   auto ShuffleMask = SVN->getMask();
9718   SDValue VecShuffle(SVN, 0);
9719   SDLoc DL(SVN);
9720 
9721   // Check that we have a four byte shuffle.
9722   if (!isNByteElemShuffleMask(SVN, 4, 1))
9723     return SDValue();
9724 
9725   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9726   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9727     std::swap(LHS, RHS);
9728     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9729     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9730   }
9731 
9732   // Ensure that the RHS is a vector of constants.
9733   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9734   if (!BVN)
9735     return SDValue();
9736 
9737   // Check if RHS is a splat of 4-bytes (or smaller).
9738   APInt APSplatValue, APSplatUndef;
9739   unsigned SplatBitSize;
9740   bool HasAnyUndefs;
9741   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9742                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9743       SplatBitSize > 32)
9744     return SDValue();
9745 
9746   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9747   // The instruction splats a constant C into two words of the source vector
9748   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9749   // Thus we check that the shuffle mask is the equivalent  of
9750   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9751   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9752   // within each word are consecutive, so we only need to check the first byte.
9753   SDValue Index;
9754   bool IsLE = Subtarget.isLittleEndian();
9755   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9756       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9757        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9758     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9759   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9760            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9761             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9762     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9763   else
9764     return SDValue();
9765 
9766   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9767   // for XXSPLTI32DX.
9768   unsigned SplatVal = APSplatValue.getZExtValue();
9769   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9770     SplatVal |= (SplatVal << SplatBitSize);
9771 
9772   SDValue SplatNode = DAG.getNode(
9773       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9774       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9775   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9776 }
9777 
9778 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9779 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9780 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9781 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9782 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9783   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9784   assert(Op.getValueType() == MVT::v1i128 &&
9785          "Only set v1i128 as custom, other type shouldn't reach here!");
9786   SDLoc dl(Op);
9787   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9788   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9789   unsigned SHLAmt = N1.getConstantOperandVal(0);
9790   if (SHLAmt % 8 == 0) {
9791     SmallVector<int, 16> Mask(16, 0);
9792     std::iota(Mask.begin(), Mask.end(), 0);
9793     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9794     if (SDValue Shuffle =
9795             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9796                                  DAG.getUNDEF(MVT::v16i8), Mask))
9797       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9798   }
9799   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9800   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9801                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9802   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9803                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9804   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9805   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9806 }
9807 
9808 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9809 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9810 /// return the code it can be lowered into.  Worst case, it can always be
9811 /// lowered into a vperm.
9812 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9813                                                SelectionDAG &DAG) const {
9814   SDLoc dl(Op);
9815   SDValue V1 = Op.getOperand(0);
9816   SDValue V2 = Op.getOperand(1);
9817   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9818 
9819   // Any nodes that were combined in the target-independent combiner prior
9820   // to vector legalization will not be sent to the target combine. Try to
9821   // combine it here.
9822   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9823     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9824       return NewShuffle;
9825     Op = NewShuffle;
9826     SVOp = cast<ShuffleVectorSDNode>(Op);
9827     V1 = Op.getOperand(0);
9828     V2 = Op.getOperand(1);
9829   }
9830   EVT VT = Op.getValueType();
9831   bool isLittleEndian = Subtarget.isLittleEndian();
9832 
9833   unsigned ShiftElts, InsertAtByte;
9834   bool Swap = false;
9835 
9836   // If this is a load-and-splat, we can do that with a single instruction
9837   // in some cases. However if the load has multiple uses, we don't want to
9838   // combine it because that will just produce multiple loads.
9839   bool IsPermutedLoad = false;
9840   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9841   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9842       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9843       InputLoad->hasOneUse()) {
9844     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9845     int SplatIdx =
9846       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9847 
9848     // The splat index for permuted loads will be in the left half of the vector
9849     // which is strictly wider than the loaded value by 8 bytes. So we need to
9850     // adjust the splat index to point to the correct address in memory.
9851     if (IsPermutedLoad) {
9852       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9853       SplatIdx += IsFourByte ? 2 : 1;
9854       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9855              "Splat of a value outside of the loaded memory");
9856     }
9857 
9858     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9859     // For 4-byte load-and-splat, we need Power9.
9860     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9861       uint64_t Offset = 0;
9862       if (IsFourByte)
9863         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9864       else
9865         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9866 
9867       SDValue BasePtr = LD->getBasePtr();
9868       if (Offset != 0)
9869         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9870                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9871       SDValue Ops[] = {
9872         LD->getChain(),    // Chain
9873         BasePtr,           // BasePtr
9874         DAG.getValueType(Op.getValueType()) // VT
9875       };
9876       SDVTList VTL =
9877         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9878       SDValue LdSplt =
9879         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9880                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9881       if (LdSplt.getValueType() != SVOp->getValueType(0))
9882         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9883       return LdSplt;
9884     }
9885   }
9886   if (Subtarget.hasP9Vector() &&
9887       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9888                            isLittleEndian)) {
9889     if (Swap)
9890       std::swap(V1, V2);
9891     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9892     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9893     if (ShiftElts) {
9894       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9895                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9896       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9897                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9898       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9899     }
9900     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9901                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9902     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9903   }
9904 
9905   if (Subtarget.hasPrefixInstrs()) {
9906     SDValue SplatInsertNode;
9907     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9908       return SplatInsertNode;
9909   }
9910 
9911   if (Subtarget.hasP9Altivec()) {
9912     SDValue NewISDNode;
9913     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9914       return NewISDNode;
9915 
9916     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9917       return NewISDNode;
9918   }
9919 
9920   if (Subtarget.hasVSX() &&
9921       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9922     if (Swap)
9923       std::swap(V1, V2);
9924     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9925     SDValue Conv2 =
9926         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9927 
9928     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9929                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9930     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9931   }
9932 
9933   if (Subtarget.hasVSX() &&
9934     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9935     if (Swap)
9936       std::swap(V1, V2);
9937     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9938     SDValue Conv2 =
9939         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9940 
9941     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9942                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9943     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9944   }
9945 
9946   if (Subtarget.hasP9Vector()) {
9947      if (PPC::isXXBRHShuffleMask(SVOp)) {
9948       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9949       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9950       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9951     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9952       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9953       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9954       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9955     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9956       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9957       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9958       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9959     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9960       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9961       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9962       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9963     }
9964   }
9965 
9966   if (Subtarget.hasVSX()) {
9967     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9968       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9969 
9970       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9971       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9972                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9973       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9974     }
9975 
9976     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9977     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9978       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9979       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9980       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9981     }
9982   }
9983 
9984   // Cases that are handled by instructions that take permute immediates
9985   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9986   // selected by the instruction selector.
9987   if (V2.isUndef()) {
9988     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9989         PPC::isSplatShuffleMask(SVOp, 2) ||
9990         PPC::isSplatShuffleMask(SVOp, 4) ||
9991         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9992         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9993         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9994         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9995         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9996         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9997         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9998         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9999         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10000         (Subtarget.hasP8Altivec() && (
10001          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10002          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10003          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10004       return Op;
10005     }
10006   }
10007 
10008   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10009   // and produce a fixed permutation.  If any of these match, do not lower to
10010   // VPERM.
10011   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10012   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10013       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10014       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10015       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10016       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10017       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10018       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10019       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10020       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10021       (Subtarget.hasP8Altivec() && (
10022        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10023        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10024        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10025     return Op;
10026 
10027   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10028   // perfect shuffle table to emit an optimal matching sequence.
10029   ArrayRef<int> PermMask = SVOp->getMask();
10030 
10031   unsigned PFIndexes[4];
10032   bool isFourElementShuffle = true;
10033   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
10034     unsigned EltNo = 8;   // Start out undef.
10035     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
10036       if (PermMask[i*4+j] < 0)
10037         continue;   // Undef, ignore it.
10038 
10039       unsigned ByteSource = PermMask[i*4+j];
10040       if ((ByteSource & 3) != j) {
10041         isFourElementShuffle = false;
10042         break;
10043       }
10044 
10045       if (EltNo == 8) {
10046         EltNo = ByteSource/4;
10047       } else if (EltNo != ByteSource/4) {
10048         isFourElementShuffle = false;
10049         break;
10050       }
10051     }
10052     PFIndexes[i] = EltNo;
10053   }
10054 
10055   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10056   // perfect shuffle vector to determine if it is cost effective to do this as
10057   // discrete instructions, or whether we should use a vperm.
10058   // For now, we skip this for little endian until such time as we have a
10059   // little-endian perfect shuffle table.
10060   if (isFourElementShuffle && !isLittleEndian) {
10061     // Compute the index in the perfect shuffle table.
10062     unsigned PFTableIndex =
10063       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10064 
10065     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10066     unsigned Cost  = (PFEntry >> 30);
10067 
10068     // Determining when to avoid vperm is tricky.  Many things affect the cost
10069     // of vperm, particularly how many times the perm mask needs to be computed.
10070     // For example, if the perm mask can be hoisted out of a loop or is already
10071     // used (perhaps because there are multiple permutes with the same shuffle
10072     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10073     // the loop requires an extra register.
10074     //
10075     // As a compromise, we only emit discrete instructions if the shuffle can be
10076     // generated in 3 or fewer operations.  When we have loop information
10077     // available, if this block is within a loop, we should avoid using vperm
10078     // for 3-operation perms and use a constant pool load instead.
10079     if (Cost < 3)
10080       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10081   }
10082 
10083   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10084   // vector that will get spilled to the constant pool.
10085   if (V2.isUndef()) V2 = V1;
10086 
10087   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10088   // that it is in input element units, not in bytes.  Convert now.
10089 
10090   // For little endian, the order of the input vectors is reversed, and
10091   // the permutation mask is complemented with respect to 31.  This is
10092   // necessary to produce proper semantics with the big-endian-biased vperm
10093   // instruction.
10094   EVT EltVT = V1.getValueType().getVectorElementType();
10095   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10096 
10097   SmallVector<SDValue, 16> ResultMask;
10098   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10099     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10100 
10101     for (unsigned j = 0; j != BytesPerElement; ++j)
10102       if (isLittleEndian)
10103         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10104                                              dl, MVT::i32));
10105       else
10106         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10107                                              MVT::i32));
10108   }
10109 
10110   ShufflesHandledWithVPERM++;
10111   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10112   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10113   LLVM_DEBUG(SVOp->dump());
10114   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10115   LLVM_DEBUG(VPermMask.dump());
10116 
10117   if (isLittleEndian)
10118     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10119                        V2, V1, VPermMask);
10120   else
10121     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10122                        V1, V2, VPermMask);
10123 }
10124 
10125 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10126 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10127 /// information about the intrinsic.
10128 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10129                                  bool &isDot, const PPCSubtarget &Subtarget) {
10130   unsigned IntrinsicID =
10131       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10132   CompareOpc = -1;
10133   isDot = false;
10134   switch (IntrinsicID) {
10135   default:
10136     return false;
10137   // Comparison predicates.
10138   case Intrinsic::ppc_altivec_vcmpbfp_p:
10139     CompareOpc = 966;
10140     isDot = true;
10141     break;
10142   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10143     CompareOpc = 198;
10144     isDot = true;
10145     break;
10146   case Intrinsic::ppc_altivec_vcmpequb_p:
10147     CompareOpc = 6;
10148     isDot = true;
10149     break;
10150   case Intrinsic::ppc_altivec_vcmpequh_p:
10151     CompareOpc = 70;
10152     isDot = true;
10153     break;
10154   case Intrinsic::ppc_altivec_vcmpequw_p:
10155     CompareOpc = 134;
10156     isDot = true;
10157     break;
10158   case Intrinsic::ppc_altivec_vcmpequd_p:
10159     if (Subtarget.hasP8Altivec()) {
10160       CompareOpc = 199;
10161       isDot = true;
10162     } else
10163       return false;
10164     break;
10165   case Intrinsic::ppc_altivec_vcmpneb_p:
10166   case Intrinsic::ppc_altivec_vcmpneh_p:
10167   case Intrinsic::ppc_altivec_vcmpnew_p:
10168   case Intrinsic::ppc_altivec_vcmpnezb_p:
10169   case Intrinsic::ppc_altivec_vcmpnezh_p:
10170   case Intrinsic::ppc_altivec_vcmpnezw_p:
10171     if (Subtarget.hasP9Altivec()) {
10172       switch (IntrinsicID) {
10173       default:
10174         llvm_unreachable("Unknown comparison intrinsic.");
10175       case Intrinsic::ppc_altivec_vcmpneb_p:
10176         CompareOpc = 7;
10177         break;
10178       case Intrinsic::ppc_altivec_vcmpneh_p:
10179         CompareOpc = 71;
10180         break;
10181       case Intrinsic::ppc_altivec_vcmpnew_p:
10182         CompareOpc = 135;
10183         break;
10184       case Intrinsic::ppc_altivec_vcmpnezb_p:
10185         CompareOpc = 263;
10186         break;
10187       case Intrinsic::ppc_altivec_vcmpnezh_p:
10188         CompareOpc = 327;
10189         break;
10190       case Intrinsic::ppc_altivec_vcmpnezw_p:
10191         CompareOpc = 391;
10192         break;
10193       }
10194       isDot = true;
10195     } else
10196       return false;
10197     break;
10198   case Intrinsic::ppc_altivec_vcmpgefp_p:
10199     CompareOpc = 454;
10200     isDot = true;
10201     break;
10202   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10203     CompareOpc = 710;
10204     isDot = true;
10205     break;
10206   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10207     CompareOpc = 774;
10208     isDot = true;
10209     break;
10210   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10211     CompareOpc = 838;
10212     isDot = true;
10213     break;
10214   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10215     CompareOpc = 902;
10216     isDot = true;
10217     break;
10218   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10219     if (Subtarget.hasP8Altivec()) {
10220       CompareOpc = 967;
10221       isDot = true;
10222     } else
10223       return false;
10224     break;
10225   case Intrinsic::ppc_altivec_vcmpgtub_p:
10226     CompareOpc = 518;
10227     isDot = true;
10228     break;
10229   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10230     CompareOpc = 582;
10231     isDot = true;
10232     break;
10233   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10234     CompareOpc = 646;
10235     isDot = true;
10236     break;
10237   case Intrinsic::ppc_altivec_vcmpgtud_p:
10238     if (Subtarget.hasP8Altivec()) {
10239       CompareOpc = 711;
10240       isDot = true;
10241     } else
10242       return false;
10243     break;
10244 
10245   case Intrinsic::ppc_altivec_vcmpequq:
10246   case Intrinsic::ppc_altivec_vcmpgtsq:
10247   case Intrinsic::ppc_altivec_vcmpgtuq:
10248     if (!Subtarget.isISA3_1())
10249       return false;
10250     switch (IntrinsicID) {
10251     default:
10252       llvm_unreachable("Unknown comparison intrinsic.");
10253     case Intrinsic::ppc_altivec_vcmpequq:
10254       CompareOpc = 455;
10255       break;
10256     case Intrinsic::ppc_altivec_vcmpgtsq:
10257       CompareOpc = 903;
10258       break;
10259     case Intrinsic::ppc_altivec_vcmpgtuq:
10260       CompareOpc = 647;
10261       break;
10262     }
10263     break;
10264 
10265   // VSX predicate comparisons use the same infrastructure
10266   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10267   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10268   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10269   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10270   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10271   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10272     if (Subtarget.hasVSX()) {
10273       switch (IntrinsicID) {
10274       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10275         CompareOpc = 99;
10276         break;
10277       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10278         CompareOpc = 115;
10279         break;
10280       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10281         CompareOpc = 107;
10282         break;
10283       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10284         CompareOpc = 67;
10285         break;
10286       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10287         CompareOpc = 83;
10288         break;
10289       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10290         CompareOpc = 75;
10291         break;
10292       }
10293       isDot = true;
10294     } else
10295       return false;
10296     break;
10297 
10298   // Normal Comparisons.
10299   case Intrinsic::ppc_altivec_vcmpbfp:
10300     CompareOpc = 966;
10301     break;
10302   case Intrinsic::ppc_altivec_vcmpeqfp:
10303     CompareOpc = 198;
10304     break;
10305   case Intrinsic::ppc_altivec_vcmpequb:
10306     CompareOpc = 6;
10307     break;
10308   case Intrinsic::ppc_altivec_vcmpequh:
10309     CompareOpc = 70;
10310     break;
10311   case Intrinsic::ppc_altivec_vcmpequw:
10312     CompareOpc = 134;
10313     break;
10314   case Intrinsic::ppc_altivec_vcmpequd:
10315     if (Subtarget.hasP8Altivec())
10316       CompareOpc = 199;
10317     else
10318       return false;
10319     break;
10320   case Intrinsic::ppc_altivec_vcmpneb:
10321   case Intrinsic::ppc_altivec_vcmpneh:
10322   case Intrinsic::ppc_altivec_vcmpnew:
10323   case Intrinsic::ppc_altivec_vcmpnezb:
10324   case Intrinsic::ppc_altivec_vcmpnezh:
10325   case Intrinsic::ppc_altivec_vcmpnezw:
10326     if (Subtarget.hasP9Altivec())
10327       switch (IntrinsicID) {
10328       default:
10329         llvm_unreachable("Unknown comparison intrinsic.");
10330       case Intrinsic::ppc_altivec_vcmpneb:
10331         CompareOpc = 7;
10332         break;
10333       case Intrinsic::ppc_altivec_vcmpneh:
10334         CompareOpc = 71;
10335         break;
10336       case Intrinsic::ppc_altivec_vcmpnew:
10337         CompareOpc = 135;
10338         break;
10339       case Intrinsic::ppc_altivec_vcmpnezb:
10340         CompareOpc = 263;
10341         break;
10342       case Intrinsic::ppc_altivec_vcmpnezh:
10343         CompareOpc = 327;
10344         break;
10345       case Intrinsic::ppc_altivec_vcmpnezw:
10346         CompareOpc = 391;
10347         break;
10348       }
10349     else
10350       return false;
10351     break;
10352   case Intrinsic::ppc_altivec_vcmpgefp:
10353     CompareOpc = 454;
10354     break;
10355   case Intrinsic::ppc_altivec_vcmpgtfp:
10356     CompareOpc = 710;
10357     break;
10358   case Intrinsic::ppc_altivec_vcmpgtsb:
10359     CompareOpc = 774;
10360     break;
10361   case Intrinsic::ppc_altivec_vcmpgtsh:
10362     CompareOpc = 838;
10363     break;
10364   case Intrinsic::ppc_altivec_vcmpgtsw:
10365     CompareOpc = 902;
10366     break;
10367   case Intrinsic::ppc_altivec_vcmpgtsd:
10368     if (Subtarget.hasP8Altivec())
10369       CompareOpc = 967;
10370     else
10371       return false;
10372     break;
10373   case Intrinsic::ppc_altivec_vcmpgtub:
10374     CompareOpc = 518;
10375     break;
10376   case Intrinsic::ppc_altivec_vcmpgtuh:
10377     CompareOpc = 582;
10378     break;
10379   case Intrinsic::ppc_altivec_vcmpgtuw:
10380     CompareOpc = 646;
10381     break;
10382   case Intrinsic::ppc_altivec_vcmpgtud:
10383     if (Subtarget.hasP8Altivec())
10384       CompareOpc = 711;
10385     else
10386       return false;
10387     break;
10388   case Intrinsic::ppc_altivec_vcmpequq_p:
10389   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10390   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10391     if (!Subtarget.isISA3_1())
10392       return false;
10393     switch (IntrinsicID) {
10394     default:
10395       llvm_unreachable("Unknown comparison intrinsic.");
10396     case Intrinsic::ppc_altivec_vcmpequq_p:
10397       CompareOpc = 455;
10398       break;
10399     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10400       CompareOpc = 903;
10401       break;
10402     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10403       CompareOpc = 647;
10404       break;
10405     }
10406     isDot = true;
10407     break;
10408   }
10409   return true;
10410 }
10411 
10412 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10413 /// lower, do it, otherwise return null.
10414 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10415                                                    SelectionDAG &DAG) const {
10416   unsigned IntrinsicID =
10417     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10418 
10419   SDLoc dl(Op);
10420 
10421   switch (IntrinsicID) {
10422   case Intrinsic::thread_pointer:
10423     // Reads the thread pointer register, used for __builtin_thread_pointer.
10424     if (Subtarget.isPPC64())
10425       return DAG.getRegister(PPC::X13, MVT::i64);
10426     return DAG.getRegister(PPC::R2, MVT::i32);
10427 
10428   case Intrinsic::ppc_mma_disassemble_acc:
10429   case Intrinsic::ppc_mma_disassemble_pair: {
10430     int NumVecs = 2;
10431     SDValue WideVec = Op.getOperand(1);
10432     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10433       NumVecs = 4;
10434       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10435     }
10436     SmallVector<SDValue, 4> RetOps;
10437     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10438       SDValue Extract = DAG.getNode(
10439           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10440           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10441                                                      : VecNo,
10442                           dl, MVT::i64));
10443       RetOps.push_back(Extract);
10444     }
10445     return DAG.getMergeValues(RetOps, dl);
10446   }
10447   }
10448 
10449   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10450   // opcode number of the comparison.
10451   int CompareOpc;
10452   bool isDot;
10453   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10454     return SDValue();    // Don't custom lower most intrinsics.
10455 
10456   // If this is a non-dot comparison, make the VCMP node and we are done.
10457   if (!isDot) {
10458     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10459                               Op.getOperand(1), Op.getOperand(2),
10460                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10461     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10462   }
10463 
10464   // Create the PPCISD altivec 'dot' comparison node.
10465   SDValue Ops[] = {
10466     Op.getOperand(2),  // LHS
10467     Op.getOperand(3),  // RHS
10468     DAG.getConstant(CompareOpc, dl, MVT::i32)
10469   };
10470   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10471   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10472 
10473   // Now that we have the comparison, emit a copy from the CR to a GPR.
10474   // This is flagged to the above dot comparison.
10475   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10476                                 DAG.getRegister(PPC::CR6, MVT::i32),
10477                                 CompNode.getValue(1));
10478 
10479   // Unpack the result based on how the target uses it.
10480   unsigned BitNo;   // Bit # of CR6.
10481   bool InvertBit;   // Invert result?
10482   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10483   default:  // Can't happen, don't crash on invalid number though.
10484   case 0:   // Return the value of the EQ bit of CR6.
10485     BitNo = 0; InvertBit = false;
10486     break;
10487   case 1:   // Return the inverted value of the EQ bit of CR6.
10488     BitNo = 0; InvertBit = true;
10489     break;
10490   case 2:   // Return the value of the LT bit of CR6.
10491     BitNo = 2; InvertBit = false;
10492     break;
10493   case 3:   // Return the inverted value of the LT bit of CR6.
10494     BitNo = 2; InvertBit = true;
10495     break;
10496   }
10497 
10498   // Shift the bit into the low position.
10499   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10500                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10501   // Isolate the bit.
10502   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10503                       DAG.getConstant(1, dl, MVT::i32));
10504 
10505   // If we are supposed to, toggle the bit.
10506   if (InvertBit)
10507     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10508                         DAG.getConstant(1, dl, MVT::i32));
10509   return Flags;
10510 }
10511 
10512 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10513                                                SelectionDAG &DAG) const {
10514   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10515   // the beginning of the argument list.
10516   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10517   SDLoc DL(Op);
10518   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10519   case Intrinsic::ppc_cfence: {
10520     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10521     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10522     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10523                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10524                                                   Op.getOperand(ArgStart + 1)),
10525                                       Op.getOperand(0)),
10526                    0);
10527   }
10528   default:
10529     break;
10530   }
10531   return SDValue();
10532 }
10533 
10534 // Lower scalar BSWAP64 to xxbrd.
10535 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10536   SDLoc dl(Op);
10537   // MTVSRDD
10538   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10539                    Op.getOperand(0));
10540   // XXBRD
10541   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10542   // MFVSRD
10543   int VectorIndex = 0;
10544   if (Subtarget.isLittleEndian())
10545     VectorIndex = 1;
10546   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10547                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10548   return Op;
10549 }
10550 
10551 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10552 // compared to a value that is atomically loaded (atomic loads zero-extend).
10553 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10554                                                 SelectionDAG &DAG) const {
10555   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10556          "Expecting an atomic compare-and-swap here.");
10557   SDLoc dl(Op);
10558   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10559   EVT MemVT = AtomicNode->getMemoryVT();
10560   if (MemVT.getSizeInBits() >= 32)
10561     return Op;
10562 
10563   SDValue CmpOp = Op.getOperand(2);
10564   // If this is already correctly zero-extended, leave it alone.
10565   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10566   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10567     return Op;
10568 
10569   // Clear the high bits of the compare operand.
10570   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10571   SDValue NewCmpOp =
10572     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10573                 DAG.getConstant(MaskVal, dl, MVT::i32));
10574 
10575   // Replace the existing compare operand with the properly zero-extended one.
10576   SmallVector<SDValue, 4> Ops;
10577   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10578     Ops.push_back(AtomicNode->getOperand(i));
10579   Ops[2] = NewCmpOp;
10580   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10581   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10582   auto NodeTy =
10583     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10584   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10585 }
10586 
10587 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10588                                                  SelectionDAG &DAG) const {
10589   SDLoc dl(Op);
10590   // Create a stack slot that is 16-byte aligned.
10591   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10592   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10593   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10594   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10595 
10596   // Store the input value into Value#0 of the stack slot.
10597   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10598                                MachinePointerInfo());
10599   // Load it out.
10600   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10601 }
10602 
10603 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10604                                                   SelectionDAG &DAG) const {
10605   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10606          "Should only be called for ISD::INSERT_VECTOR_ELT");
10607 
10608   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10609   // We have legal lowering for constant indices but not for variable ones.
10610   if (!C)
10611     return SDValue();
10612 
10613   EVT VT = Op.getValueType();
10614   SDLoc dl(Op);
10615   SDValue V1 = Op.getOperand(0);
10616   SDValue V2 = Op.getOperand(1);
10617   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10618   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10619     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10620     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10621     unsigned InsertAtElement = C->getZExtValue();
10622     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10623     if (Subtarget.isLittleEndian()) {
10624       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10625     }
10626     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10627                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10628   }
10629   return Op;
10630 }
10631 
10632 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10633                                            SelectionDAG &DAG) const {
10634   SDLoc dl(Op);
10635   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10636   SDValue LoadChain = LN->getChain();
10637   SDValue BasePtr = LN->getBasePtr();
10638   EVT VT = Op.getValueType();
10639 
10640   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10641     return Op;
10642 
10643   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10644   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10645   // 2 or 4 vsx registers.
10646   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10647          "Type unsupported without MMA");
10648   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10649          "Type unsupported without paired vector support");
10650   Align Alignment = LN->getAlign();
10651   SmallVector<SDValue, 4> Loads;
10652   SmallVector<SDValue, 4> LoadChains;
10653   unsigned NumVecs = VT.getSizeInBits() / 128;
10654   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10655     SDValue Load =
10656         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10657                     LN->getPointerInfo().getWithOffset(Idx * 16),
10658                     commonAlignment(Alignment, Idx * 16),
10659                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10660     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10661                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10662     Loads.push_back(Load);
10663     LoadChains.push_back(Load.getValue(1));
10664   }
10665   if (Subtarget.isLittleEndian()) {
10666     std::reverse(Loads.begin(), Loads.end());
10667     std::reverse(LoadChains.begin(), LoadChains.end());
10668   }
10669   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10670   SDValue Value =
10671       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10672                   dl, VT, Loads);
10673   SDValue RetOps[] = {Value, TF};
10674   return DAG.getMergeValues(RetOps, dl);
10675 }
10676 
10677 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10678                                             SelectionDAG &DAG) const {
10679   SDLoc dl(Op);
10680   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10681   SDValue StoreChain = SN->getChain();
10682   SDValue BasePtr = SN->getBasePtr();
10683   SDValue Value = SN->getValue();
10684   EVT StoreVT = Value.getValueType();
10685 
10686   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10687     return Op;
10688 
10689   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10690   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10691   // underlying registers individually.
10692   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10693          "Type unsupported without MMA");
10694   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10695          "Type unsupported without paired vector support");
10696   Align Alignment = SN->getAlign();
10697   SmallVector<SDValue, 4> Stores;
10698   unsigned NumVecs = 2;
10699   if (StoreVT == MVT::v512i1) {
10700     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10701     NumVecs = 4;
10702   }
10703   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10704     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10705     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10706                               DAG.getConstant(VecNum, dl, MVT::i64));
10707     SDValue Store =
10708         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10709                      SN->getPointerInfo().getWithOffset(Idx * 16),
10710                      commonAlignment(Alignment, Idx * 16),
10711                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10712     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10713                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10714     Stores.push_back(Store);
10715   }
10716   SDValue TF = DAG.getTokenFactor(dl, Stores);
10717   return TF;
10718 }
10719 
10720 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10721   SDLoc dl(Op);
10722   if (Op.getValueType() == MVT::v4i32) {
10723     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10724 
10725     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10726     // +16 as shift amt.
10727     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10728     SDValue RHSSwap =   // = vrlw RHS, 16
10729       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10730 
10731     // Shrinkify inputs to v8i16.
10732     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10733     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10734     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10735 
10736     // Low parts multiplied together, generating 32-bit results (we ignore the
10737     // top parts).
10738     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10739                                         LHS, RHS, DAG, dl, MVT::v4i32);
10740 
10741     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10742                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10743     // Shift the high parts up 16 bits.
10744     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10745                               Neg16, DAG, dl);
10746     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10747   } else if (Op.getValueType() == MVT::v16i8) {
10748     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10749     bool isLittleEndian = Subtarget.isLittleEndian();
10750 
10751     // Multiply the even 8-bit parts, producing 16-bit sums.
10752     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10753                                            LHS, RHS, DAG, dl, MVT::v8i16);
10754     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10755 
10756     // Multiply the odd 8-bit parts, producing 16-bit sums.
10757     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10758                                           LHS, RHS, DAG, dl, MVT::v8i16);
10759     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10760 
10761     // Merge the results together.  Because vmuleub and vmuloub are
10762     // instructions with a big-endian bias, we must reverse the
10763     // element numbering and reverse the meaning of "odd" and "even"
10764     // when generating little endian code.
10765     int Ops[16];
10766     for (unsigned i = 0; i != 8; ++i) {
10767       if (isLittleEndian) {
10768         Ops[i*2  ] = 2*i;
10769         Ops[i*2+1] = 2*i+16;
10770       } else {
10771         Ops[i*2  ] = 2*i+1;
10772         Ops[i*2+1] = 2*i+1+16;
10773       }
10774     }
10775     if (isLittleEndian)
10776       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10777     else
10778       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10779   } else {
10780     llvm_unreachable("Unknown mul to lower!");
10781   }
10782 }
10783 
10784 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10785 
10786   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10787 
10788   EVT VT = Op.getValueType();
10789   assert(VT.isVector() &&
10790          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10791   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10792           VT == MVT::v16i8) &&
10793          "Unexpected vector element type!");
10794   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10795          "Current subtarget doesn't support smax v2i64!");
10796 
10797   // For vector abs, it can be lowered to:
10798   // abs x
10799   // ==>
10800   // y = -x
10801   // smax(x, y)
10802 
10803   SDLoc dl(Op);
10804   SDValue X = Op.getOperand(0);
10805   SDValue Zero = DAG.getConstant(0, dl, VT);
10806   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10807 
10808   // SMAX patch https://reviews.llvm.org/D47332
10809   // hasn't landed yet, so use intrinsic first here.
10810   // TODO: Should use SMAX directly once SMAX patch landed
10811   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10812   if (VT == MVT::v2i64)
10813     BifID = Intrinsic::ppc_altivec_vmaxsd;
10814   else if (VT == MVT::v8i16)
10815     BifID = Intrinsic::ppc_altivec_vmaxsh;
10816   else if (VT == MVT::v16i8)
10817     BifID = Intrinsic::ppc_altivec_vmaxsb;
10818 
10819   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10820 }
10821 
10822 // Custom lowering for fpext vf32 to v2f64
10823 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10824 
10825   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10826          "Should only be called for ISD::FP_EXTEND");
10827 
10828   // FIXME: handle extends from half precision float vectors on P9.
10829   // We only want to custom lower an extend from v2f32 to v2f64.
10830   if (Op.getValueType() != MVT::v2f64 ||
10831       Op.getOperand(0).getValueType() != MVT::v2f32)
10832     return SDValue();
10833 
10834   SDLoc dl(Op);
10835   SDValue Op0 = Op.getOperand(0);
10836 
10837   switch (Op0.getOpcode()) {
10838   default:
10839     return SDValue();
10840   case ISD::EXTRACT_SUBVECTOR: {
10841     assert(Op0.getNumOperands() == 2 &&
10842            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10843            "Node should have 2 operands with second one being a constant!");
10844 
10845     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10846       return SDValue();
10847 
10848     // Custom lower is only done for high or low doubleword.
10849     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10850     if (Idx % 2 != 0)
10851       return SDValue();
10852 
10853     // Since input is v4f32, at this point Idx is either 0 or 2.
10854     // Shift to get the doubleword position we want.
10855     int DWord = Idx >> 1;
10856 
10857     // High and low word positions are different on little endian.
10858     if (Subtarget.isLittleEndian())
10859       DWord ^= 0x1;
10860 
10861     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10862                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10863   }
10864   case ISD::FADD:
10865   case ISD::FMUL:
10866   case ISD::FSUB: {
10867     SDValue NewLoad[2];
10868     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10869       // Ensure both input are loads.
10870       SDValue LdOp = Op0.getOperand(i);
10871       if (LdOp.getOpcode() != ISD::LOAD)
10872         return SDValue();
10873       // Generate new load node.
10874       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10875       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10876       NewLoad[i] = DAG.getMemIntrinsicNode(
10877           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10878           LD->getMemoryVT(), LD->getMemOperand());
10879     }
10880     SDValue NewOp =
10881         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10882                     NewLoad[1], Op0.getNode()->getFlags());
10883     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10884                        DAG.getConstant(0, dl, MVT::i32));
10885   }
10886   case ISD::LOAD: {
10887     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10888     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10889     SDValue NewLd = DAG.getMemIntrinsicNode(
10890         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10891         LD->getMemoryVT(), LD->getMemOperand());
10892     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10893                        DAG.getConstant(0, dl, MVT::i32));
10894   }
10895   }
10896   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10897 }
10898 
10899 /// LowerOperation - Provide custom lowering hooks for some operations.
10900 ///
10901 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10902   switch (Op.getOpcode()) {
10903   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10904   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10905   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10906   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10907   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10908   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10909   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10910   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10911   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10912 
10913   // Variable argument lowering.
10914   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10915   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10916   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10917 
10918   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10919   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10920   case ISD::GET_DYNAMIC_AREA_OFFSET:
10921     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10922 
10923   // Exception handling lowering.
10924   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10925   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10926   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10927 
10928   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10929   case ISD::STORE:              return LowerSTORE(Op, DAG);
10930   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10931   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10932   case ISD::STRICT_FP_TO_UINT:
10933   case ISD::STRICT_FP_TO_SINT:
10934   case ISD::FP_TO_UINT:
10935   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10936   case ISD::STRICT_UINT_TO_FP:
10937   case ISD::STRICT_SINT_TO_FP:
10938   case ISD::UINT_TO_FP:
10939   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10940   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10941 
10942   // Lower 64-bit shifts.
10943   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10944   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10945   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10946 
10947   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10948   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10949 
10950   // Vector-related lowering.
10951   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10952   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10953   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10954   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10955   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10956   case ISD::MUL:                return LowerMUL(Op, DAG);
10957   case ISD::ABS:                return LowerABS(Op, DAG);
10958   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10959   case ISD::ROTL:               return LowerROTL(Op, DAG);
10960 
10961   // For counter-based loop handling.
10962   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10963 
10964   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10965 
10966   // Frame & Return address.
10967   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10968   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10969 
10970   case ISD::INTRINSIC_VOID:
10971     return LowerINTRINSIC_VOID(Op, DAG);
10972   case ISD::BSWAP:
10973     return LowerBSWAP(Op, DAG);
10974   case ISD::ATOMIC_CMP_SWAP:
10975     return LowerATOMIC_CMP_SWAP(Op, DAG);
10976   }
10977 }
10978 
10979 void PPCTargetLowering::LowerOperationWrapper(SDNode *N,
10980                                               SmallVectorImpl<SDValue> &Results,
10981                                               SelectionDAG &DAG) const {
10982   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10983 
10984   if (!Res.getNode())
10985     return;
10986 
10987   // Take the return value as-is if original node has only one result.
10988   if (N->getNumValues() == 1) {
10989     Results.push_back(Res);
10990     return;
10991   }
10992 
10993   // New node should have the same number of results.
10994   assert((N->getNumValues() == Res->getNumValues()) &&
10995       "Lowering returned the wrong number of results!");
10996 
10997   for (unsigned i = 0; i < N->getNumValues(); ++i)
10998     Results.push_back(Res.getValue(i));
10999 }
11000 
11001 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11002                                            SmallVectorImpl<SDValue>&Results,
11003                                            SelectionDAG &DAG) const {
11004   SDLoc dl(N);
11005   switch (N->getOpcode()) {
11006   default:
11007     llvm_unreachable("Do not know how to custom type legalize this operation!");
11008   case ISD::READCYCLECOUNTER: {
11009     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11010     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11011 
11012     Results.push_back(
11013         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11014     Results.push_back(RTB.getValue(2));
11015     break;
11016   }
11017   case ISD::INTRINSIC_W_CHAIN: {
11018     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11019         Intrinsic::loop_decrement)
11020       break;
11021 
11022     assert(N->getValueType(0) == MVT::i1 &&
11023            "Unexpected result type for CTR decrement intrinsic");
11024     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11025                                  N->getValueType(0));
11026     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11027     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11028                                  N->getOperand(1));
11029 
11030     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11031     Results.push_back(NewInt.getValue(1));
11032     break;
11033   }
11034   case ISD::VAARG: {
11035     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11036       return;
11037 
11038     EVT VT = N->getValueType(0);
11039 
11040     if (VT == MVT::i64) {
11041       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11042 
11043       Results.push_back(NewNode);
11044       Results.push_back(NewNode.getValue(1));
11045     }
11046     return;
11047   }
11048   case ISD::STRICT_FP_TO_SINT:
11049   case ISD::STRICT_FP_TO_UINT:
11050   case ISD::FP_TO_SINT:
11051   case ISD::FP_TO_UINT:
11052     // LowerFP_TO_INT() can only handle f32 and f64.
11053     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11054         MVT::ppcf128)
11055       return;
11056     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
11057     return;
11058   case ISD::TRUNCATE: {
11059     if (!N->getValueType(0).isVector())
11060       return;
11061     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11062     if (Lowered)
11063       Results.push_back(Lowered);
11064     return;
11065   }
11066   case ISD::FSHL:
11067   case ISD::FSHR:
11068     // Don't handle funnel shifts here.
11069     return;
11070   case ISD::BITCAST:
11071     // Don't handle bitcast here.
11072     return;
11073   case ISD::FP_EXTEND:
11074     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11075     if (Lowered)
11076       Results.push_back(Lowered);
11077     return;
11078   }
11079 }
11080 
11081 //===----------------------------------------------------------------------===//
11082 //  Other Lowering Code
11083 //===----------------------------------------------------------------------===//
11084 
11085 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11086   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11087   Function *Func = Intrinsic::getDeclaration(M, Id);
11088   return Builder.CreateCall(Func, {});
11089 }
11090 
11091 // The mappings for emitLeading/TrailingFence is taken from
11092 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11093 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11094                                                  Instruction *Inst,
11095                                                  AtomicOrdering Ord) const {
11096   if (Ord == AtomicOrdering::SequentiallyConsistent)
11097     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11098   if (isReleaseOrStronger(Ord))
11099     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11100   return nullptr;
11101 }
11102 
11103 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11104                                                   Instruction *Inst,
11105                                                   AtomicOrdering Ord) const {
11106   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11107     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11108     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11109     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11110     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11111       return Builder.CreateCall(
11112           Intrinsic::getDeclaration(
11113               Builder.GetInsertBlock()->getParent()->getParent(),
11114               Intrinsic::ppc_cfence, {Inst->getType()}),
11115           {Inst});
11116     // FIXME: Can use isync for rmw operation.
11117     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11118   }
11119   return nullptr;
11120 }
11121 
11122 MachineBasicBlock *
11123 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11124                                     unsigned AtomicSize,
11125                                     unsigned BinOpcode,
11126                                     unsigned CmpOpcode,
11127                                     unsigned CmpPred) const {
11128   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11129   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11130 
11131   auto LoadMnemonic = PPC::LDARX;
11132   auto StoreMnemonic = PPC::STDCX;
11133   switch (AtomicSize) {
11134   default:
11135     llvm_unreachable("Unexpected size of atomic entity");
11136   case 1:
11137     LoadMnemonic = PPC::LBARX;
11138     StoreMnemonic = PPC::STBCX;
11139     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11140     break;
11141   case 2:
11142     LoadMnemonic = PPC::LHARX;
11143     StoreMnemonic = PPC::STHCX;
11144     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11145     break;
11146   case 4:
11147     LoadMnemonic = PPC::LWARX;
11148     StoreMnemonic = PPC::STWCX;
11149     break;
11150   case 8:
11151     LoadMnemonic = PPC::LDARX;
11152     StoreMnemonic = PPC::STDCX;
11153     break;
11154   }
11155 
11156   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11157   MachineFunction *F = BB->getParent();
11158   MachineFunction::iterator It = ++BB->getIterator();
11159 
11160   Register dest = MI.getOperand(0).getReg();
11161   Register ptrA = MI.getOperand(1).getReg();
11162   Register ptrB = MI.getOperand(2).getReg();
11163   Register incr = MI.getOperand(3).getReg();
11164   DebugLoc dl = MI.getDebugLoc();
11165 
11166   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11167   MachineBasicBlock *loop2MBB =
11168     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11169   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11170   F->insert(It, loopMBB);
11171   if (CmpOpcode)
11172     F->insert(It, loop2MBB);
11173   F->insert(It, exitMBB);
11174   exitMBB->splice(exitMBB->begin(), BB,
11175                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11176   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11177 
11178   MachineRegisterInfo &RegInfo = F->getRegInfo();
11179   Register TmpReg = (!BinOpcode) ? incr :
11180     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11181                                            : &PPC::GPRCRegClass);
11182 
11183   //  thisMBB:
11184   //   ...
11185   //   fallthrough --> loopMBB
11186   BB->addSuccessor(loopMBB);
11187 
11188   //  loopMBB:
11189   //   l[wd]arx dest, ptr
11190   //   add r0, dest, incr
11191   //   st[wd]cx. r0, ptr
11192   //   bne- loopMBB
11193   //   fallthrough --> exitMBB
11194 
11195   // For max/min...
11196   //  loopMBB:
11197   //   l[wd]arx dest, ptr
11198   //   cmpl?[wd] incr, dest
11199   //   bgt exitMBB
11200   //  loop2MBB:
11201   //   st[wd]cx. dest, ptr
11202   //   bne- loopMBB
11203   //   fallthrough --> exitMBB
11204 
11205   BB = loopMBB;
11206   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11207     .addReg(ptrA).addReg(ptrB);
11208   if (BinOpcode)
11209     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11210   if (CmpOpcode) {
11211     // Signed comparisons of byte or halfword values must be sign-extended.
11212     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11213       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11214       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11215               ExtReg).addReg(dest);
11216       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11217         .addReg(incr).addReg(ExtReg);
11218     } else
11219       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11220         .addReg(incr).addReg(dest);
11221 
11222     BuildMI(BB, dl, TII->get(PPC::BCC))
11223       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11224     BB->addSuccessor(loop2MBB);
11225     BB->addSuccessor(exitMBB);
11226     BB = loop2MBB;
11227   }
11228   BuildMI(BB, dl, TII->get(StoreMnemonic))
11229     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11230   BuildMI(BB, dl, TII->get(PPC::BCC))
11231     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11232   BB->addSuccessor(loopMBB);
11233   BB->addSuccessor(exitMBB);
11234 
11235   //  exitMBB:
11236   //   ...
11237   BB = exitMBB;
11238   return BB;
11239 }
11240 
11241 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11242     MachineInstr &MI, MachineBasicBlock *BB,
11243     bool is8bit, // operation
11244     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11245   // If we support part-word atomic mnemonics, just use them
11246   if (Subtarget.hasPartwordAtomics())
11247     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11248                             CmpPred);
11249 
11250   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11251   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11252   // In 64 bit mode we have to use 64 bits for addresses, even though the
11253   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11254   // registers without caring whether they're 32 or 64, but here we're
11255   // doing actual arithmetic on the addresses.
11256   bool is64bit = Subtarget.isPPC64();
11257   bool isLittleEndian = Subtarget.isLittleEndian();
11258   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11259 
11260   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11261   MachineFunction *F = BB->getParent();
11262   MachineFunction::iterator It = ++BB->getIterator();
11263 
11264   Register dest = MI.getOperand(0).getReg();
11265   Register ptrA = MI.getOperand(1).getReg();
11266   Register ptrB = MI.getOperand(2).getReg();
11267   Register incr = MI.getOperand(3).getReg();
11268   DebugLoc dl = MI.getDebugLoc();
11269 
11270   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11271   MachineBasicBlock *loop2MBB =
11272       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11273   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11274   F->insert(It, loopMBB);
11275   if (CmpOpcode)
11276     F->insert(It, loop2MBB);
11277   F->insert(It, exitMBB);
11278   exitMBB->splice(exitMBB->begin(), BB,
11279                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11280   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11281 
11282   MachineRegisterInfo &RegInfo = F->getRegInfo();
11283   const TargetRegisterClass *RC =
11284       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11285   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11286 
11287   Register PtrReg = RegInfo.createVirtualRegister(RC);
11288   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11289   Register ShiftReg =
11290       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11291   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11292   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11293   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11294   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11295   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11296   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11297   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11298   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11299   Register Ptr1Reg;
11300   Register TmpReg =
11301       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11302 
11303   //  thisMBB:
11304   //   ...
11305   //   fallthrough --> loopMBB
11306   BB->addSuccessor(loopMBB);
11307 
11308   // The 4-byte load must be aligned, while a char or short may be
11309   // anywhere in the word.  Hence all this nasty bookkeeping code.
11310   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11311   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11312   //   xori shift, shift1, 24 [16]
11313   //   rlwinm ptr, ptr1, 0, 0, 29
11314   //   slw incr2, incr, shift
11315   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11316   //   slw mask, mask2, shift
11317   //  loopMBB:
11318   //   lwarx tmpDest, ptr
11319   //   add tmp, tmpDest, incr2
11320   //   andc tmp2, tmpDest, mask
11321   //   and tmp3, tmp, mask
11322   //   or tmp4, tmp3, tmp2
11323   //   stwcx. tmp4, ptr
11324   //   bne- loopMBB
11325   //   fallthrough --> exitMBB
11326   //   srw dest, tmpDest, shift
11327   if (ptrA != ZeroReg) {
11328     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11329     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11330         .addReg(ptrA)
11331         .addReg(ptrB);
11332   } else {
11333     Ptr1Reg = ptrB;
11334   }
11335   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11336   // mode.
11337   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11338       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11339       .addImm(3)
11340       .addImm(27)
11341       .addImm(is8bit ? 28 : 27);
11342   if (!isLittleEndian)
11343     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11344         .addReg(Shift1Reg)
11345         .addImm(is8bit ? 24 : 16);
11346   if (is64bit)
11347     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11348         .addReg(Ptr1Reg)
11349         .addImm(0)
11350         .addImm(61);
11351   else
11352     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11353         .addReg(Ptr1Reg)
11354         .addImm(0)
11355         .addImm(0)
11356         .addImm(29);
11357   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11358   if (is8bit)
11359     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11360   else {
11361     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11362     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11363         .addReg(Mask3Reg)
11364         .addImm(65535);
11365   }
11366   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11367       .addReg(Mask2Reg)
11368       .addReg(ShiftReg);
11369 
11370   BB = loopMBB;
11371   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11372       .addReg(ZeroReg)
11373       .addReg(PtrReg);
11374   if (BinOpcode)
11375     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11376         .addReg(Incr2Reg)
11377         .addReg(TmpDestReg);
11378   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11379       .addReg(TmpDestReg)
11380       .addReg(MaskReg);
11381   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11382   if (CmpOpcode) {
11383     // For unsigned comparisons, we can directly compare the shifted values.
11384     // For signed comparisons we shift and sign extend.
11385     Register SReg = RegInfo.createVirtualRegister(GPRC);
11386     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11387         .addReg(TmpDestReg)
11388         .addReg(MaskReg);
11389     unsigned ValueReg = SReg;
11390     unsigned CmpReg = Incr2Reg;
11391     if (CmpOpcode == PPC::CMPW) {
11392       ValueReg = RegInfo.createVirtualRegister(GPRC);
11393       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11394           .addReg(SReg)
11395           .addReg(ShiftReg);
11396       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11397       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11398           .addReg(ValueReg);
11399       ValueReg = ValueSReg;
11400       CmpReg = incr;
11401     }
11402     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11403         .addReg(CmpReg)
11404         .addReg(ValueReg);
11405     BuildMI(BB, dl, TII->get(PPC::BCC))
11406         .addImm(CmpPred)
11407         .addReg(PPC::CR0)
11408         .addMBB(exitMBB);
11409     BB->addSuccessor(loop2MBB);
11410     BB->addSuccessor(exitMBB);
11411     BB = loop2MBB;
11412   }
11413   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11414   BuildMI(BB, dl, TII->get(PPC::STWCX))
11415       .addReg(Tmp4Reg)
11416       .addReg(ZeroReg)
11417       .addReg(PtrReg);
11418   BuildMI(BB, dl, TII->get(PPC::BCC))
11419       .addImm(PPC::PRED_NE)
11420       .addReg(PPC::CR0)
11421       .addMBB(loopMBB);
11422   BB->addSuccessor(loopMBB);
11423   BB->addSuccessor(exitMBB);
11424 
11425   //  exitMBB:
11426   //   ...
11427   BB = exitMBB;
11428   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11429       .addReg(TmpDestReg)
11430       .addReg(ShiftReg);
11431   return BB;
11432 }
11433 
11434 llvm::MachineBasicBlock *
11435 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11436                                     MachineBasicBlock *MBB) const {
11437   DebugLoc DL = MI.getDebugLoc();
11438   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11439   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11440 
11441   MachineFunction *MF = MBB->getParent();
11442   MachineRegisterInfo &MRI = MF->getRegInfo();
11443 
11444   const BasicBlock *BB = MBB->getBasicBlock();
11445   MachineFunction::iterator I = ++MBB->getIterator();
11446 
11447   Register DstReg = MI.getOperand(0).getReg();
11448   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11449   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11450   Register mainDstReg = MRI.createVirtualRegister(RC);
11451   Register restoreDstReg = MRI.createVirtualRegister(RC);
11452 
11453   MVT PVT = getPointerTy(MF->getDataLayout());
11454   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11455          "Invalid Pointer Size!");
11456   // For v = setjmp(buf), we generate
11457   //
11458   // thisMBB:
11459   //  SjLjSetup mainMBB
11460   //  bl mainMBB
11461   //  v_restore = 1
11462   //  b sinkMBB
11463   //
11464   // mainMBB:
11465   //  buf[LabelOffset] = LR
11466   //  v_main = 0
11467   //
11468   // sinkMBB:
11469   //  v = phi(main, restore)
11470   //
11471 
11472   MachineBasicBlock *thisMBB = MBB;
11473   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11474   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11475   MF->insert(I, mainMBB);
11476   MF->insert(I, sinkMBB);
11477 
11478   MachineInstrBuilder MIB;
11479 
11480   // Transfer the remainder of BB and its successor edges to sinkMBB.
11481   sinkMBB->splice(sinkMBB->begin(), MBB,
11482                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11483   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11484 
11485   // Note that the structure of the jmp_buf used here is not compatible
11486   // with that used by libc, and is not designed to be. Specifically, it
11487   // stores only those 'reserved' registers that LLVM does not otherwise
11488   // understand how to spill. Also, by convention, by the time this
11489   // intrinsic is called, Clang has already stored the frame address in the
11490   // first slot of the buffer and stack address in the third. Following the
11491   // X86 target code, we'll store the jump address in the second slot. We also
11492   // need to save the TOC pointer (R2) to handle jumps between shared
11493   // libraries, and that will be stored in the fourth slot. The thread
11494   // identifier (R13) is not affected.
11495 
11496   // thisMBB:
11497   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11498   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11499   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11500 
11501   // Prepare IP either in reg.
11502   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11503   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11504   Register BufReg = MI.getOperand(1).getReg();
11505 
11506   if (Subtarget.is64BitELFABI()) {
11507     setUsesTOCBasePtr(*MBB->getParent());
11508     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11509               .addReg(PPC::X2)
11510               .addImm(TOCOffset)
11511               .addReg(BufReg)
11512               .cloneMemRefs(MI);
11513   }
11514 
11515   // Naked functions never have a base pointer, and so we use r1. For all
11516   // other functions, this decision must be delayed until during PEI.
11517   unsigned BaseReg;
11518   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11519     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11520   else
11521     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11522 
11523   MIB = BuildMI(*thisMBB, MI, DL,
11524                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11525             .addReg(BaseReg)
11526             .addImm(BPOffset)
11527             .addReg(BufReg)
11528             .cloneMemRefs(MI);
11529 
11530   // Setup
11531   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11532   MIB.addRegMask(TRI->getNoPreservedMask());
11533 
11534   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11535 
11536   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11537           .addMBB(mainMBB);
11538   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11539 
11540   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11541   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11542 
11543   // mainMBB:
11544   //  mainDstReg = 0
11545   MIB =
11546       BuildMI(mainMBB, DL,
11547               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11548 
11549   // Store IP
11550   if (Subtarget.isPPC64()) {
11551     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11552             .addReg(LabelReg)
11553             .addImm(LabelOffset)
11554             .addReg(BufReg);
11555   } else {
11556     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11557             .addReg(LabelReg)
11558             .addImm(LabelOffset)
11559             .addReg(BufReg);
11560   }
11561   MIB.cloneMemRefs(MI);
11562 
11563   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11564   mainMBB->addSuccessor(sinkMBB);
11565 
11566   // sinkMBB:
11567   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11568           TII->get(PPC::PHI), DstReg)
11569     .addReg(mainDstReg).addMBB(mainMBB)
11570     .addReg(restoreDstReg).addMBB(thisMBB);
11571 
11572   MI.eraseFromParent();
11573   return sinkMBB;
11574 }
11575 
11576 MachineBasicBlock *
11577 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11578                                      MachineBasicBlock *MBB) const {
11579   DebugLoc DL = MI.getDebugLoc();
11580   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11581 
11582   MachineFunction *MF = MBB->getParent();
11583   MachineRegisterInfo &MRI = MF->getRegInfo();
11584 
11585   MVT PVT = getPointerTy(MF->getDataLayout());
11586   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11587          "Invalid Pointer Size!");
11588 
11589   const TargetRegisterClass *RC =
11590     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11591   Register Tmp = MRI.createVirtualRegister(RC);
11592   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11593   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11594   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11595   unsigned BP =
11596       (PVT == MVT::i64)
11597           ? PPC::X30
11598           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11599                                                               : PPC::R30);
11600 
11601   MachineInstrBuilder MIB;
11602 
11603   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11604   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11605   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11606   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11607 
11608   Register BufReg = MI.getOperand(0).getReg();
11609 
11610   // Reload FP (the jumped-to function may not have had a
11611   // frame pointer, and if so, then its r31 will be restored
11612   // as necessary).
11613   if (PVT == MVT::i64) {
11614     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11615             .addImm(0)
11616             .addReg(BufReg);
11617   } else {
11618     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11619             .addImm(0)
11620             .addReg(BufReg);
11621   }
11622   MIB.cloneMemRefs(MI);
11623 
11624   // Reload IP
11625   if (PVT == MVT::i64) {
11626     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11627             .addImm(LabelOffset)
11628             .addReg(BufReg);
11629   } else {
11630     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11631             .addImm(LabelOffset)
11632             .addReg(BufReg);
11633   }
11634   MIB.cloneMemRefs(MI);
11635 
11636   // Reload SP
11637   if (PVT == MVT::i64) {
11638     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11639             .addImm(SPOffset)
11640             .addReg(BufReg);
11641   } else {
11642     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11643             .addImm(SPOffset)
11644             .addReg(BufReg);
11645   }
11646   MIB.cloneMemRefs(MI);
11647 
11648   // Reload BP
11649   if (PVT == MVT::i64) {
11650     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11651             .addImm(BPOffset)
11652             .addReg(BufReg);
11653   } else {
11654     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11655             .addImm(BPOffset)
11656             .addReg(BufReg);
11657   }
11658   MIB.cloneMemRefs(MI);
11659 
11660   // Reload TOC
11661   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11662     setUsesTOCBasePtr(*MBB->getParent());
11663     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11664               .addImm(TOCOffset)
11665               .addReg(BufReg)
11666               .cloneMemRefs(MI);
11667   }
11668 
11669   // Jump
11670   BuildMI(*MBB, MI, DL,
11671           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11672   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11673 
11674   MI.eraseFromParent();
11675   return MBB;
11676 }
11677 
11678 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11679   // If the function specifically requests inline stack probes, emit them.
11680   if (MF.getFunction().hasFnAttribute("probe-stack"))
11681     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11682            "inline-asm";
11683   return false;
11684 }
11685 
11686 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11687   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11688   unsigned StackAlign = TFI->getStackAlignment();
11689   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11690          "Unexpected stack alignment");
11691   // The default stack probe size is 4096 if the function has no
11692   // stack-probe-size attribute.
11693   unsigned StackProbeSize = 4096;
11694   const Function &Fn = MF.getFunction();
11695   if (Fn.hasFnAttribute("stack-probe-size"))
11696     Fn.getFnAttribute("stack-probe-size")
11697         .getValueAsString()
11698         .getAsInteger(0, StackProbeSize);
11699   // Round down to the stack alignment.
11700   StackProbeSize &= ~(StackAlign - 1);
11701   return StackProbeSize ? StackProbeSize : StackAlign;
11702 }
11703 
11704 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11705 // into three phases. In the first phase, it uses pseudo instruction
11706 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11707 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11708 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11709 // MaxCallFrameSize so that it can calculate correct data area pointer.
11710 MachineBasicBlock *
11711 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11712                                     MachineBasicBlock *MBB) const {
11713   const bool isPPC64 = Subtarget.isPPC64();
11714   MachineFunction *MF = MBB->getParent();
11715   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11716   DebugLoc DL = MI.getDebugLoc();
11717   const unsigned ProbeSize = getStackProbeSize(*MF);
11718   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11719   MachineRegisterInfo &MRI = MF->getRegInfo();
11720   // The CFG of probing stack looks as
11721   //         +-----+
11722   //         | MBB |
11723   //         +--+--+
11724   //            |
11725   //       +----v----+
11726   //  +--->+ TestMBB +---+
11727   //  |    +----+----+   |
11728   //  |         |        |
11729   //  |   +-----v----+   |
11730   //  +---+ BlockMBB |   |
11731   //      +----------+   |
11732   //                     |
11733   //       +---------+   |
11734   //       | TailMBB +<--+
11735   //       +---------+
11736   // In MBB, calculate previous frame pointer and final stack pointer.
11737   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11738   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11739   // TailMBB is spliced via \p MI.
11740   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11741   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11742   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11743 
11744   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11745   MF->insert(MBBIter, TestMBB);
11746   MF->insert(MBBIter, BlockMBB);
11747   MF->insert(MBBIter, TailMBB);
11748 
11749   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11750   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11751 
11752   Register DstReg = MI.getOperand(0).getReg();
11753   Register NegSizeReg = MI.getOperand(1).getReg();
11754   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11755   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11756   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11757   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11758 
11759   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11760   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11761   // NegSize.
11762   unsigned ProbeOpc;
11763   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11764     ProbeOpc =
11765         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11766   else
11767     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11768     // and NegSizeReg will be allocated in the same phyreg to avoid
11769     // redundant copy when NegSizeReg has only one use which is current MI and
11770     // will be replaced by PREPARE_PROBED_ALLOCA then.
11771     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11772                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11773   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11774       .addDef(ActualNegSizeReg)
11775       .addReg(NegSizeReg)
11776       .add(MI.getOperand(2))
11777       .add(MI.getOperand(3));
11778 
11779   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11780   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11781           FinalStackPtr)
11782       .addReg(SPReg)
11783       .addReg(ActualNegSizeReg);
11784 
11785   // Materialize a scratch register for update.
11786   int64_t NegProbeSize = -(int64_t)ProbeSize;
11787   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11788   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11789   if (!isInt<16>(NegProbeSize)) {
11790     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11791     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11792         .addImm(NegProbeSize >> 16);
11793     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11794             ScratchReg)
11795         .addReg(TempReg)
11796         .addImm(NegProbeSize & 0xFFFF);
11797   } else
11798     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11799         .addImm(NegProbeSize);
11800 
11801   {
11802     // Probing leading residual part.
11803     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11804     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11805         .addReg(ActualNegSizeReg)
11806         .addReg(ScratchReg);
11807     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11808     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11809         .addReg(Div)
11810         .addReg(ScratchReg);
11811     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11812     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11813         .addReg(Mul)
11814         .addReg(ActualNegSizeReg);
11815     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11816         .addReg(FramePointer)
11817         .addReg(SPReg)
11818         .addReg(NegMod);
11819   }
11820 
11821   {
11822     // Remaining part should be multiple of ProbeSize.
11823     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11824     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11825         .addReg(SPReg)
11826         .addReg(FinalStackPtr);
11827     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11828         .addImm(PPC::PRED_EQ)
11829         .addReg(CmpResult)
11830         .addMBB(TailMBB);
11831     TestMBB->addSuccessor(BlockMBB);
11832     TestMBB->addSuccessor(TailMBB);
11833   }
11834 
11835   {
11836     // Touch the block.
11837     // |P...|P...|P...
11838     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11839         .addReg(FramePointer)
11840         .addReg(SPReg)
11841         .addReg(ScratchReg);
11842     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11843     BlockMBB->addSuccessor(TestMBB);
11844   }
11845 
11846   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11847   // DYNAREAOFFSET pseudo instruction to get the future result.
11848   Register MaxCallFrameSizeReg =
11849       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11850   BuildMI(TailMBB, DL,
11851           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11852           MaxCallFrameSizeReg)
11853       .add(MI.getOperand(2))
11854       .add(MI.getOperand(3));
11855   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11856       .addReg(SPReg)
11857       .addReg(MaxCallFrameSizeReg);
11858 
11859   // Splice instructions after MI to TailMBB.
11860   TailMBB->splice(TailMBB->end(), MBB,
11861                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11862   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11863   MBB->addSuccessor(TestMBB);
11864 
11865   // Delete the pseudo instruction.
11866   MI.eraseFromParent();
11867 
11868   ++NumDynamicAllocaProbed;
11869   return TailMBB;
11870 }
11871 
11872 MachineBasicBlock *
11873 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11874                                                MachineBasicBlock *BB) const {
11875   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11876       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11877     if (Subtarget.is64BitELFABI() &&
11878         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11879         !Subtarget.isUsingPCRelativeCalls()) {
11880       // Call lowering should have added an r2 operand to indicate a dependence
11881       // on the TOC base pointer value. It can't however, because there is no
11882       // way to mark the dependence as implicit there, and so the stackmap code
11883       // will confuse it with a regular operand. Instead, add the dependence
11884       // here.
11885       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11886     }
11887 
11888     return emitPatchPoint(MI, BB);
11889   }
11890 
11891   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11892       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11893     return emitEHSjLjSetJmp(MI, BB);
11894   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11895              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11896     return emitEHSjLjLongJmp(MI, BB);
11897   }
11898 
11899   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11900 
11901   // To "insert" these instructions we actually have to insert their
11902   // control-flow patterns.
11903   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11904   MachineFunction::iterator It = ++BB->getIterator();
11905 
11906   MachineFunction *F = BB->getParent();
11907 
11908   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11909       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11910       MI.getOpcode() == PPC::SELECT_I8) {
11911     SmallVector<MachineOperand, 2> Cond;
11912     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11913         MI.getOpcode() == PPC::SELECT_CC_I8)
11914       Cond.push_back(MI.getOperand(4));
11915     else
11916       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11917     Cond.push_back(MI.getOperand(1));
11918 
11919     DebugLoc dl = MI.getDebugLoc();
11920     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11921                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11922   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11923              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11924              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11925              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11926              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11927              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11928              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11929              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11930              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11931              MI.getOpcode() == PPC::SELECT_F4 ||
11932              MI.getOpcode() == PPC::SELECT_F8 ||
11933              MI.getOpcode() == PPC::SELECT_F16 ||
11934              MI.getOpcode() == PPC::SELECT_SPE ||
11935              MI.getOpcode() == PPC::SELECT_SPE4 ||
11936              MI.getOpcode() == PPC::SELECT_VRRC ||
11937              MI.getOpcode() == PPC::SELECT_VSFRC ||
11938              MI.getOpcode() == PPC::SELECT_VSSRC ||
11939              MI.getOpcode() == PPC::SELECT_VSRC) {
11940     // The incoming instruction knows the destination vreg to set, the
11941     // condition code register to branch on, the true/false values to
11942     // select between, and a branch opcode to use.
11943 
11944     //  thisMBB:
11945     //  ...
11946     //   TrueVal = ...
11947     //   cmpTY ccX, r1, r2
11948     //   bCC copy1MBB
11949     //   fallthrough --> copy0MBB
11950     MachineBasicBlock *thisMBB = BB;
11951     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11952     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11953     DebugLoc dl = MI.getDebugLoc();
11954     F->insert(It, copy0MBB);
11955     F->insert(It, sinkMBB);
11956 
11957     // Transfer the remainder of BB and its successor edges to sinkMBB.
11958     sinkMBB->splice(sinkMBB->begin(), BB,
11959                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11960     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11961 
11962     // Next, add the true and fallthrough blocks as its successors.
11963     BB->addSuccessor(copy0MBB);
11964     BB->addSuccessor(sinkMBB);
11965 
11966     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11967         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11968         MI.getOpcode() == PPC::SELECT_F16 ||
11969         MI.getOpcode() == PPC::SELECT_SPE4 ||
11970         MI.getOpcode() == PPC::SELECT_SPE ||
11971         MI.getOpcode() == PPC::SELECT_VRRC ||
11972         MI.getOpcode() == PPC::SELECT_VSFRC ||
11973         MI.getOpcode() == PPC::SELECT_VSSRC ||
11974         MI.getOpcode() == PPC::SELECT_VSRC) {
11975       BuildMI(BB, dl, TII->get(PPC::BC))
11976           .addReg(MI.getOperand(1).getReg())
11977           .addMBB(sinkMBB);
11978     } else {
11979       unsigned SelectPred = MI.getOperand(4).getImm();
11980       BuildMI(BB, dl, TII->get(PPC::BCC))
11981           .addImm(SelectPred)
11982           .addReg(MI.getOperand(1).getReg())
11983           .addMBB(sinkMBB);
11984     }
11985 
11986     //  copy0MBB:
11987     //   %FalseValue = ...
11988     //   # fallthrough to sinkMBB
11989     BB = copy0MBB;
11990 
11991     // Update machine-CFG edges
11992     BB->addSuccessor(sinkMBB);
11993 
11994     //  sinkMBB:
11995     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11996     //  ...
11997     BB = sinkMBB;
11998     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11999         .addReg(MI.getOperand(3).getReg())
12000         .addMBB(copy0MBB)
12001         .addReg(MI.getOperand(2).getReg())
12002         .addMBB(thisMBB);
12003   } else if (MI.getOpcode() == PPC::ReadTB) {
12004     // To read the 64-bit time-base register on a 32-bit target, we read the
12005     // two halves. Should the counter have wrapped while it was being read, we
12006     // need to try again.
12007     // ...
12008     // readLoop:
12009     // mfspr Rx,TBU # load from TBU
12010     // mfspr Ry,TB  # load from TB
12011     // mfspr Rz,TBU # load from TBU
12012     // cmpw crX,Rx,Rz # check if 'old'='new'
12013     // bne readLoop   # branch if they're not equal
12014     // ...
12015 
12016     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12017     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12018     DebugLoc dl = MI.getDebugLoc();
12019     F->insert(It, readMBB);
12020     F->insert(It, sinkMBB);
12021 
12022     // Transfer the remainder of BB and its successor edges to sinkMBB.
12023     sinkMBB->splice(sinkMBB->begin(), BB,
12024                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12025     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12026 
12027     BB->addSuccessor(readMBB);
12028     BB = readMBB;
12029 
12030     MachineRegisterInfo &RegInfo = F->getRegInfo();
12031     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12032     Register LoReg = MI.getOperand(0).getReg();
12033     Register HiReg = MI.getOperand(1).getReg();
12034 
12035     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12036     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12037     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12038 
12039     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12040 
12041     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12042         .addReg(HiReg)
12043         .addReg(ReadAgainReg);
12044     BuildMI(BB, dl, TII->get(PPC::BCC))
12045         .addImm(PPC::PRED_NE)
12046         .addReg(CmpReg)
12047         .addMBB(readMBB);
12048 
12049     BB->addSuccessor(readMBB);
12050     BB->addSuccessor(sinkMBB);
12051   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12052     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12053   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12054     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12055   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12056     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12057   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12058     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12059 
12060   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12061     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12062   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12063     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12064   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12065     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12066   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12067     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12068 
12069   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12070     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12071   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12072     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12073   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12074     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12075   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12076     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12077 
12078   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12079     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12080   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12081     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12082   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12083     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12084   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12085     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12086 
12087   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12088     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12089   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12090     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12091   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12092     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12093   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12094     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12095 
12096   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12097     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12098   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12099     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12100   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12101     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12102   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12103     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12104 
12105   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12106     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12107   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12108     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12109   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12110     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12111   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12112     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12113 
12114   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12115     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12116   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12117     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12118   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12119     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12120   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12121     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12122 
12123   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12124     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12125   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12126     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12127   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12128     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12129   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12130     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12131 
12132   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12133     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12134   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12135     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12136   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12137     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12138   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12139     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12140 
12141   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12142     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12143   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12144     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12145   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12146     BB = EmitAtomicBinary(MI, BB, 4, 0);
12147   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12148     BB = EmitAtomicBinary(MI, BB, 8, 0);
12149   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12150            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12151            (Subtarget.hasPartwordAtomics() &&
12152             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12153            (Subtarget.hasPartwordAtomics() &&
12154             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12155     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12156 
12157     auto LoadMnemonic = PPC::LDARX;
12158     auto StoreMnemonic = PPC::STDCX;
12159     switch (MI.getOpcode()) {
12160     default:
12161       llvm_unreachable("Compare and swap of unknown size");
12162     case PPC::ATOMIC_CMP_SWAP_I8:
12163       LoadMnemonic = PPC::LBARX;
12164       StoreMnemonic = PPC::STBCX;
12165       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12166       break;
12167     case PPC::ATOMIC_CMP_SWAP_I16:
12168       LoadMnemonic = PPC::LHARX;
12169       StoreMnemonic = PPC::STHCX;
12170       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12171       break;
12172     case PPC::ATOMIC_CMP_SWAP_I32:
12173       LoadMnemonic = PPC::LWARX;
12174       StoreMnemonic = PPC::STWCX;
12175       break;
12176     case PPC::ATOMIC_CMP_SWAP_I64:
12177       LoadMnemonic = PPC::LDARX;
12178       StoreMnemonic = PPC::STDCX;
12179       break;
12180     }
12181     Register dest = MI.getOperand(0).getReg();
12182     Register ptrA = MI.getOperand(1).getReg();
12183     Register ptrB = MI.getOperand(2).getReg();
12184     Register oldval = MI.getOperand(3).getReg();
12185     Register newval = MI.getOperand(4).getReg();
12186     DebugLoc dl = MI.getDebugLoc();
12187 
12188     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12189     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12190     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12191     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12192     F->insert(It, loop1MBB);
12193     F->insert(It, loop2MBB);
12194     F->insert(It, midMBB);
12195     F->insert(It, exitMBB);
12196     exitMBB->splice(exitMBB->begin(), BB,
12197                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12198     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12199 
12200     //  thisMBB:
12201     //   ...
12202     //   fallthrough --> loopMBB
12203     BB->addSuccessor(loop1MBB);
12204 
12205     // loop1MBB:
12206     //   l[bhwd]arx dest, ptr
12207     //   cmp[wd] dest, oldval
12208     //   bne- midMBB
12209     // loop2MBB:
12210     //   st[bhwd]cx. newval, ptr
12211     //   bne- loopMBB
12212     //   b exitBB
12213     // midMBB:
12214     //   st[bhwd]cx. dest, ptr
12215     // exitBB:
12216     BB = loop1MBB;
12217     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12218     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12219         .addReg(oldval)
12220         .addReg(dest);
12221     BuildMI(BB, dl, TII->get(PPC::BCC))
12222         .addImm(PPC::PRED_NE)
12223         .addReg(PPC::CR0)
12224         .addMBB(midMBB);
12225     BB->addSuccessor(loop2MBB);
12226     BB->addSuccessor(midMBB);
12227 
12228     BB = loop2MBB;
12229     BuildMI(BB, dl, TII->get(StoreMnemonic))
12230         .addReg(newval)
12231         .addReg(ptrA)
12232         .addReg(ptrB);
12233     BuildMI(BB, dl, TII->get(PPC::BCC))
12234         .addImm(PPC::PRED_NE)
12235         .addReg(PPC::CR0)
12236         .addMBB(loop1MBB);
12237     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12238     BB->addSuccessor(loop1MBB);
12239     BB->addSuccessor(exitMBB);
12240 
12241     BB = midMBB;
12242     BuildMI(BB, dl, TII->get(StoreMnemonic))
12243         .addReg(dest)
12244         .addReg(ptrA)
12245         .addReg(ptrB);
12246     BB->addSuccessor(exitMBB);
12247 
12248     //  exitMBB:
12249     //   ...
12250     BB = exitMBB;
12251   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12252              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12253     // We must use 64-bit registers for addresses when targeting 64-bit,
12254     // since we're actually doing arithmetic on them.  Other registers
12255     // can be 32-bit.
12256     bool is64bit = Subtarget.isPPC64();
12257     bool isLittleEndian = Subtarget.isLittleEndian();
12258     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12259 
12260     Register dest = MI.getOperand(0).getReg();
12261     Register ptrA = MI.getOperand(1).getReg();
12262     Register ptrB = MI.getOperand(2).getReg();
12263     Register oldval = MI.getOperand(3).getReg();
12264     Register newval = MI.getOperand(4).getReg();
12265     DebugLoc dl = MI.getDebugLoc();
12266 
12267     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12268     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12269     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12270     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12271     F->insert(It, loop1MBB);
12272     F->insert(It, loop2MBB);
12273     F->insert(It, midMBB);
12274     F->insert(It, exitMBB);
12275     exitMBB->splice(exitMBB->begin(), BB,
12276                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12277     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12278 
12279     MachineRegisterInfo &RegInfo = F->getRegInfo();
12280     const TargetRegisterClass *RC =
12281         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12282     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12283 
12284     Register PtrReg = RegInfo.createVirtualRegister(RC);
12285     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12286     Register ShiftReg =
12287         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12288     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12289     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12290     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12291     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12292     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12293     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12294     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12295     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12296     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12297     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12298     Register Ptr1Reg;
12299     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12300     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12301     //  thisMBB:
12302     //   ...
12303     //   fallthrough --> loopMBB
12304     BB->addSuccessor(loop1MBB);
12305 
12306     // The 4-byte load must be aligned, while a char or short may be
12307     // anywhere in the word.  Hence all this nasty bookkeeping code.
12308     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12309     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12310     //   xori shift, shift1, 24 [16]
12311     //   rlwinm ptr, ptr1, 0, 0, 29
12312     //   slw newval2, newval, shift
12313     //   slw oldval2, oldval,shift
12314     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12315     //   slw mask, mask2, shift
12316     //   and newval3, newval2, mask
12317     //   and oldval3, oldval2, mask
12318     // loop1MBB:
12319     //   lwarx tmpDest, ptr
12320     //   and tmp, tmpDest, mask
12321     //   cmpw tmp, oldval3
12322     //   bne- midMBB
12323     // loop2MBB:
12324     //   andc tmp2, tmpDest, mask
12325     //   or tmp4, tmp2, newval3
12326     //   stwcx. tmp4, ptr
12327     //   bne- loop1MBB
12328     //   b exitBB
12329     // midMBB:
12330     //   stwcx. tmpDest, ptr
12331     // exitBB:
12332     //   srw dest, tmpDest, shift
12333     if (ptrA != ZeroReg) {
12334       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12335       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12336           .addReg(ptrA)
12337           .addReg(ptrB);
12338     } else {
12339       Ptr1Reg = ptrB;
12340     }
12341 
12342     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12343     // mode.
12344     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12345         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12346         .addImm(3)
12347         .addImm(27)
12348         .addImm(is8bit ? 28 : 27);
12349     if (!isLittleEndian)
12350       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12351           .addReg(Shift1Reg)
12352           .addImm(is8bit ? 24 : 16);
12353     if (is64bit)
12354       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12355           .addReg(Ptr1Reg)
12356           .addImm(0)
12357           .addImm(61);
12358     else
12359       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12360           .addReg(Ptr1Reg)
12361           .addImm(0)
12362           .addImm(0)
12363           .addImm(29);
12364     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12365         .addReg(newval)
12366         .addReg(ShiftReg);
12367     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12368         .addReg(oldval)
12369         .addReg(ShiftReg);
12370     if (is8bit)
12371       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12372     else {
12373       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12374       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12375           .addReg(Mask3Reg)
12376           .addImm(65535);
12377     }
12378     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12379         .addReg(Mask2Reg)
12380         .addReg(ShiftReg);
12381     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12382         .addReg(NewVal2Reg)
12383         .addReg(MaskReg);
12384     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12385         .addReg(OldVal2Reg)
12386         .addReg(MaskReg);
12387 
12388     BB = loop1MBB;
12389     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12390         .addReg(ZeroReg)
12391         .addReg(PtrReg);
12392     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12393         .addReg(TmpDestReg)
12394         .addReg(MaskReg);
12395     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12396         .addReg(TmpReg)
12397         .addReg(OldVal3Reg);
12398     BuildMI(BB, dl, TII->get(PPC::BCC))
12399         .addImm(PPC::PRED_NE)
12400         .addReg(PPC::CR0)
12401         .addMBB(midMBB);
12402     BB->addSuccessor(loop2MBB);
12403     BB->addSuccessor(midMBB);
12404 
12405     BB = loop2MBB;
12406     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12407         .addReg(TmpDestReg)
12408         .addReg(MaskReg);
12409     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12410         .addReg(Tmp2Reg)
12411         .addReg(NewVal3Reg);
12412     BuildMI(BB, dl, TII->get(PPC::STWCX))
12413         .addReg(Tmp4Reg)
12414         .addReg(ZeroReg)
12415         .addReg(PtrReg);
12416     BuildMI(BB, dl, TII->get(PPC::BCC))
12417         .addImm(PPC::PRED_NE)
12418         .addReg(PPC::CR0)
12419         .addMBB(loop1MBB);
12420     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12421     BB->addSuccessor(loop1MBB);
12422     BB->addSuccessor(exitMBB);
12423 
12424     BB = midMBB;
12425     BuildMI(BB, dl, TII->get(PPC::STWCX))
12426         .addReg(TmpDestReg)
12427         .addReg(ZeroReg)
12428         .addReg(PtrReg);
12429     BB->addSuccessor(exitMBB);
12430 
12431     //  exitMBB:
12432     //   ...
12433     BB = exitMBB;
12434     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12435         .addReg(TmpReg)
12436         .addReg(ShiftReg);
12437   } else if (MI.getOpcode() == PPC::FADDrtz) {
12438     // This pseudo performs an FADD with rounding mode temporarily forced
12439     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12440     // is not modeled at the SelectionDAG level.
12441     Register Dest = MI.getOperand(0).getReg();
12442     Register Src1 = MI.getOperand(1).getReg();
12443     Register Src2 = MI.getOperand(2).getReg();
12444     DebugLoc dl = MI.getDebugLoc();
12445 
12446     MachineRegisterInfo &RegInfo = F->getRegInfo();
12447     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12448 
12449     // Save FPSCR value.
12450     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12451 
12452     // Set rounding mode to round-to-zero.
12453     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12454         .addImm(31)
12455         .addReg(PPC::RM, RegState::ImplicitDefine);
12456 
12457     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12458         .addImm(30)
12459         .addReg(PPC::RM, RegState::ImplicitDefine);
12460 
12461     // Perform addition.
12462     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12463                    .addReg(Src1)
12464                    .addReg(Src2);
12465     if (MI.getFlag(MachineInstr::NoFPExcept))
12466       MIB.setMIFlag(MachineInstr::NoFPExcept);
12467 
12468     // Restore FPSCR value.
12469     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12470   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12471              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12472              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12473              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12474     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12475                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12476                           ? PPC::ANDI8_rec
12477                           : PPC::ANDI_rec;
12478     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12479                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12480 
12481     MachineRegisterInfo &RegInfo = F->getRegInfo();
12482     Register Dest = RegInfo.createVirtualRegister(
12483         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12484 
12485     DebugLoc Dl = MI.getDebugLoc();
12486     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12487         .addReg(MI.getOperand(1).getReg())
12488         .addImm(1);
12489     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12490             MI.getOperand(0).getReg())
12491         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12492   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12493     DebugLoc Dl = MI.getDebugLoc();
12494     MachineRegisterInfo &RegInfo = F->getRegInfo();
12495     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12496     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12497     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12498             MI.getOperand(0).getReg())
12499         .addReg(CRReg);
12500   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12501     DebugLoc Dl = MI.getDebugLoc();
12502     unsigned Imm = MI.getOperand(1).getImm();
12503     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12504     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12505             MI.getOperand(0).getReg())
12506         .addReg(PPC::CR0EQ);
12507   } else if (MI.getOpcode() == PPC::SETRNDi) {
12508     DebugLoc dl = MI.getDebugLoc();
12509     Register OldFPSCRReg = MI.getOperand(0).getReg();
12510 
12511     // Save FPSCR value.
12512     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12513 
12514     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12515     // the following settings:
12516     //   00 Round to nearest
12517     //   01 Round to 0
12518     //   10 Round to +inf
12519     //   11 Round to -inf
12520 
12521     // When the operand is immediate, using the two least significant bits of
12522     // the immediate to set the bits 62:63 of FPSCR.
12523     unsigned Mode = MI.getOperand(1).getImm();
12524     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12525         .addImm(31)
12526         .addReg(PPC::RM, RegState::ImplicitDefine);
12527 
12528     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12529         .addImm(30)
12530         .addReg(PPC::RM, RegState::ImplicitDefine);
12531   } else if (MI.getOpcode() == PPC::SETRND) {
12532     DebugLoc dl = MI.getDebugLoc();
12533 
12534     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12535     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12536     // If the target doesn't have DirectMove, we should use stack to do the
12537     // conversion, because the target doesn't have the instructions like mtvsrd
12538     // or mfvsrd to do this conversion directly.
12539     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12540       if (Subtarget.hasDirectMove()) {
12541         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12542           .addReg(SrcReg);
12543       } else {
12544         // Use stack to do the register copy.
12545         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12546         MachineRegisterInfo &RegInfo = F->getRegInfo();
12547         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12548         if (RC == &PPC::F8RCRegClass) {
12549           // Copy register from F8RCRegClass to G8RCRegclass.
12550           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12551                  "Unsupported RegClass.");
12552 
12553           StoreOp = PPC::STFD;
12554           LoadOp = PPC::LD;
12555         } else {
12556           // Copy register from G8RCRegClass to F8RCRegclass.
12557           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12558                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12559                  "Unsupported RegClass.");
12560         }
12561 
12562         MachineFrameInfo &MFI = F->getFrameInfo();
12563         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12564 
12565         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12566             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12567             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12568             MFI.getObjectAlign(FrameIdx));
12569 
12570         // Store the SrcReg into the stack.
12571         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12572           .addReg(SrcReg)
12573           .addImm(0)
12574           .addFrameIndex(FrameIdx)
12575           .addMemOperand(MMOStore);
12576 
12577         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12578             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12579             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12580             MFI.getObjectAlign(FrameIdx));
12581 
12582         // Load from the stack where SrcReg is stored, and save to DestReg,
12583         // so we have done the RegClass conversion from RegClass::SrcReg to
12584         // RegClass::DestReg.
12585         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12586           .addImm(0)
12587           .addFrameIndex(FrameIdx)
12588           .addMemOperand(MMOLoad);
12589       }
12590     };
12591 
12592     Register OldFPSCRReg = MI.getOperand(0).getReg();
12593 
12594     // Save FPSCR value.
12595     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12596 
12597     // When the operand is gprc register, use two least significant bits of the
12598     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12599     //
12600     // copy OldFPSCRTmpReg, OldFPSCRReg
12601     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12602     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12603     // copy NewFPSCRReg, NewFPSCRTmpReg
12604     // mtfsf 255, NewFPSCRReg
12605     MachineOperand SrcOp = MI.getOperand(1);
12606     MachineRegisterInfo &RegInfo = F->getRegInfo();
12607     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12608 
12609     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12610 
12611     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12612     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12613 
12614     // The first operand of INSERT_SUBREG should be a register which has
12615     // subregisters, we only care about its RegClass, so we should use an
12616     // IMPLICIT_DEF register.
12617     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12618     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12619       .addReg(ImDefReg)
12620       .add(SrcOp)
12621       .addImm(1);
12622 
12623     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12624     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12625       .addReg(OldFPSCRTmpReg)
12626       .addReg(ExtSrcReg)
12627       .addImm(0)
12628       .addImm(62);
12629 
12630     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12631     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12632 
12633     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12634     // bits of FPSCR.
12635     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12636       .addImm(255)
12637       .addReg(NewFPSCRReg)
12638       .addImm(0)
12639       .addImm(0);
12640   } else if (MI.getOpcode() == PPC::SETFLM) {
12641     DebugLoc Dl = MI.getDebugLoc();
12642 
12643     // Result of setflm is previous FPSCR content, so we need to save it first.
12644     Register OldFPSCRReg = MI.getOperand(0).getReg();
12645     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12646 
12647     // Put bits in 32:63 to FPSCR.
12648     Register NewFPSCRReg = MI.getOperand(1).getReg();
12649     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12650         .addImm(255)
12651         .addReg(NewFPSCRReg)
12652         .addImm(0)
12653         .addImm(0);
12654   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12655              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12656     return emitProbedAlloca(MI, BB);
12657   } else {
12658     llvm_unreachable("Unexpected instr type to insert");
12659   }
12660 
12661   MI.eraseFromParent(); // The pseudo instruction is gone now.
12662   return BB;
12663 }
12664 
12665 //===----------------------------------------------------------------------===//
12666 // Target Optimization Hooks
12667 //===----------------------------------------------------------------------===//
12668 
12669 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12670   // For the estimates, convergence is quadratic, so we essentially double the
12671   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12672   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12673   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12674   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12675   if (VT.getScalarType() == MVT::f64)
12676     RefinementSteps++;
12677   return RefinementSteps;
12678 }
12679 
12680 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12681                                            int Enabled, int &RefinementSteps,
12682                                            bool &UseOneConstNR,
12683                                            bool Reciprocal) const {
12684   EVT VT = Operand.getValueType();
12685   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12686       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12687       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12688       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12689     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12690       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12691 
12692     // The Newton-Raphson computation with a single constant does not provide
12693     // enough accuracy on some CPUs.
12694     UseOneConstNR = !Subtarget.needsTwoConstNR();
12695     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12696   }
12697   return SDValue();
12698 }
12699 
12700 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12701                                             int Enabled,
12702                                             int &RefinementSteps) const {
12703   EVT VT = Operand.getValueType();
12704   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12705       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12706       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12707       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12708     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12709       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12710     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12711   }
12712   return SDValue();
12713 }
12714 
12715 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12716   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12717   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12718   // enabled for division), this functionality is redundant with the default
12719   // combiner logic (once the division -> reciprocal/multiply transformation
12720   // has taken place). As a result, this matters more for older cores than for
12721   // newer ones.
12722 
12723   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12724   // reciprocal if there are two or more FDIVs (for embedded cores with only
12725   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12726   switch (Subtarget.getCPUDirective()) {
12727   default:
12728     return 3;
12729   case PPC::DIR_440:
12730   case PPC::DIR_A2:
12731   case PPC::DIR_E500:
12732   case PPC::DIR_E500mc:
12733   case PPC::DIR_E5500:
12734     return 2;
12735   }
12736 }
12737 
12738 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12739 // collapsed, and so we need to look through chains of them.
12740 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12741                                      int64_t& Offset, SelectionDAG &DAG) {
12742   if (DAG.isBaseWithConstantOffset(Loc)) {
12743     Base = Loc.getOperand(0);
12744     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12745 
12746     // The base might itself be a base plus an offset, and if so, accumulate
12747     // that as well.
12748     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12749   }
12750 }
12751 
12752 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12753                             unsigned Bytes, int Dist,
12754                             SelectionDAG &DAG) {
12755   if (VT.getSizeInBits() / 8 != Bytes)
12756     return false;
12757 
12758   SDValue BaseLoc = Base->getBasePtr();
12759   if (Loc.getOpcode() == ISD::FrameIndex) {
12760     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12761       return false;
12762     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12763     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12764     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12765     int FS  = MFI.getObjectSize(FI);
12766     int BFS = MFI.getObjectSize(BFI);
12767     if (FS != BFS || FS != (int)Bytes) return false;
12768     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12769   }
12770 
12771   SDValue Base1 = Loc, Base2 = BaseLoc;
12772   int64_t Offset1 = 0, Offset2 = 0;
12773   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12774   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12775   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12776     return true;
12777 
12778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12779   const GlobalValue *GV1 = nullptr;
12780   const GlobalValue *GV2 = nullptr;
12781   Offset1 = 0;
12782   Offset2 = 0;
12783   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12784   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12785   if (isGA1 && isGA2 && GV1 == GV2)
12786     return Offset1 == (Offset2 + Dist*Bytes);
12787   return false;
12788 }
12789 
12790 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12791 // not enforce equality of the chain operands.
12792 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12793                             unsigned Bytes, int Dist,
12794                             SelectionDAG &DAG) {
12795   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12796     EVT VT = LS->getMemoryVT();
12797     SDValue Loc = LS->getBasePtr();
12798     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12799   }
12800 
12801   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12802     EVT VT;
12803     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12804     default: return false;
12805     case Intrinsic::ppc_altivec_lvx:
12806     case Intrinsic::ppc_altivec_lvxl:
12807     case Intrinsic::ppc_vsx_lxvw4x:
12808     case Intrinsic::ppc_vsx_lxvw4x_be:
12809       VT = MVT::v4i32;
12810       break;
12811     case Intrinsic::ppc_vsx_lxvd2x:
12812     case Intrinsic::ppc_vsx_lxvd2x_be:
12813       VT = MVT::v2f64;
12814       break;
12815     case Intrinsic::ppc_altivec_lvebx:
12816       VT = MVT::i8;
12817       break;
12818     case Intrinsic::ppc_altivec_lvehx:
12819       VT = MVT::i16;
12820       break;
12821     case Intrinsic::ppc_altivec_lvewx:
12822       VT = MVT::i32;
12823       break;
12824     }
12825 
12826     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12827   }
12828 
12829   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12830     EVT VT;
12831     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12832     default: return false;
12833     case Intrinsic::ppc_altivec_stvx:
12834     case Intrinsic::ppc_altivec_stvxl:
12835     case Intrinsic::ppc_vsx_stxvw4x:
12836       VT = MVT::v4i32;
12837       break;
12838     case Intrinsic::ppc_vsx_stxvd2x:
12839       VT = MVT::v2f64;
12840       break;
12841     case Intrinsic::ppc_vsx_stxvw4x_be:
12842       VT = MVT::v4i32;
12843       break;
12844     case Intrinsic::ppc_vsx_stxvd2x_be:
12845       VT = MVT::v2f64;
12846       break;
12847     case Intrinsic::ppc_altivec_stvebx:
12848       VT = MVT::i8;
12849       break;
12850     case Intrinsic::ppc_altivec_stvehx:
12851       VT = MVT::i16;
12852       break;
12853     case Intrinsic::ppc_altivec_stvewx:
12854       VT = MVT::i32;
12855       break;
12856     }
12857 
12858     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12859   }
12860 
12861   return false;
12862 }
12863 
12864 // Return true is there is a nearyby consecutive load to the one provided
12865 // (regardless of alignment). We search up and down the chain, looking though
12866 // token factors and other loads (but nothing else). As a result, a true result
12867 // indicates that it is safe to create a new consecutive load adjacent to the
12868 // load provided.
12869 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12870   SDValue Chain = LD->getChain();
12871   EVT VT = LD->getMemoryVT();
12872 
12873   SmallSet<SDNode *, 16> LoadRoots;
12874   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12875   SmallSet<SDNode *, 16> Visited;
12876 
12877   // First, search up the chain, branching to follow all token-factor operands.
12878   // If we find a consecutive load, then we're done, otherwise, record all
12879   // nodes just above the top-level loads and token factors.
12880   while (!Queue.empty()) {
12881     SDNode *ChainNext = Queue.pop_back_val();
12882     if (!Visited.insert(ChainNext).second)
12883       continue;
12884 
12885     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12886       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12887         return true;
12888 
12889       if (!Visited.count(ChainLD->getChain().getNode()))
12890         Queue.push_back(ChainLD->getChain().getNode());
12891     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12892       for (const SDUse &O : ChainNext->ops())
12893         if (!Visited.count(O.getNode()))
12894           Queue.push_back(O.getNode());
12895     } else
12896       LoadRoots.insert(ChainNext);
12897   }
12898 
12899   // Second, search down the chain, starting from the top-level nodes recorded
12900   // in the first phase. These top-level nodes are the nodes just above all
12901   // loads and token factors. Starting with their uses, recursively look though
12902   // all loads (just the chain uses) and token factors to find a consecutive
12903   // load.
12904   Visited.clear();
12905   Queue.clear();
12906 
12907   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12908        IE = LoadRoots.end(); I != IE; ++I) {
12909     Queue.push_back(*I);
12910 
12911     while (!Queue.empty()) {
12912       SDNode *LoadRoot = Queue.pop_back_val();
12913       if (!Visited.insert(LoadRoot).second)
12914         continue;
12915 
12916       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12917         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12918           return true;
12919 
12920       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12921            UE = LoadRoot->use_end(); UI != UE; ++UI)
12922         if (((isa<MemSDNode>(*UI) &&
12923             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12924             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12925           Queue.push_back(*UI);
12926     }
12927   }
12928 
12929   return false;
12930 }
12931 
12932 /// This function is called when we have proved that a SETCC node can be replaced
12933 /// by subtraction (and other supporting instructions) so that the result of
12934 /// comparison is kept in a GPR instead of CR. This function is purely for
12935 /// codegen purposes and has some flags to guide the codegen process.
12936 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12937                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12938   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12939 
12940   // Zero extend the operands to the largest legal integer. Originally, they
12941   // must be of a strictly smaller size.
12942   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12943                          DAG.getConstant(Size, DL, MVT::i32));
12944   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12945                          DAG.getConstant(Size, DL, MVT::i32));
12946 
12947   // Swap if needed. Depends on the condition code.
12948   if (Swap)
12949     std::swap(Op0, Op1);
12950 
12951   // Subtract extended integers.
12952   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12953 
12954   // Move the sign bit to the least significant position and zero out the rest.
12955   // Now the least significant bit carries the result of original comparison.
12956   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12957                              DAG.getConstant(Size - 1, DL, MVT::i32));
12958   auto Final = Shifted;
12959 
12960   // Complement the result if needed. Based on the condition code.
12961   if (Complement)
12962     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12963                         DAG.getConstant(1, DL, MVT::i64));
12964 
12965   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12966 }
12967 
12968 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12969                                                   DAGCombinerInfo &DCI) const {
12970   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12971 
12972   SelectionDAG &DAG = DCI.DAG;
12973   SDLoc DL(N);
12974 
12975   // Size of integers being compared has a critical role in the following
12976   // analysis, so we prefer to do this when all types are legal.
12977   if (!DCI.isAfterLegalizeDAG())
12978     return SDValue();
12979 
12980   // If all users of SETCC extend its value to a legal integer type
12981   // then we replace SETCC with a subtraction
12982   for (SDNode::use_iterator UI = N->use_begin(),
12983        UE = N->use_end(); UI != UE; ++UI) {
12984     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12985       return SDValue();
12986   }
12987 
12988   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12989   auto OpSize = N->getOperand(0).getValueSizeInBits();
12990 
12991   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12992 
12993   if (OpSize < Size) {
12994     switch (CC) {
12995     default: break;
12996     case ISD::SETULT:
12997       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12998     case ISD::SETULE:
12999       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13000     case ISD::SETUGT:
13001       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13002     case ISD::SETUGE:
13003       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13004     }
13005   }
13006 
13007   return SDValue();
13008 }
13009 
13010 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13011                                                   DAGCombinerInfo &DCI) const {
13012   SelectionDAG &DAG = DCI.DAG;
13013   SDLoc dl(N);
13014 
13015   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13016   // If we're tracking CR bits, we need to be careful that we don't have:
13017   //   trunc(binary-ops(zext(x), zext(y)))
13018   // or
13019   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13020   // such that we're unnecessarily moving things into GPRs when it would be
13021   // better to keep them in CR bits.
13022 
13023   // Note that trunc here can be an actual i1 trunc, or can be the effective
13024   // truncation that comes from a setcc or select_cc.
13025   if (N->getOpcode() == ISD::TRUNCATE &&
13026       N->getValueType(0) != MVT::i1)
13027     return SDValue();
13028 
13029   if (N->getOperand(0).getValueType() != MVT::i32 &&
13030       N->getOperand(0).getValueType() != MVT::i64)
13031     return SDValue();
13032 
13033   if (N->getOpcode() == ISD::SETCC ||
13034       N->getOpcode() == ISD::SELECT_CC) {
13035     // If we're looking at a comparison, then we need to make sure that the
13036     // high bits (all except for the first) don't matter the result.
13037     ISD::CondCode CC =
13038       cast<CondCodeSDNode>(N->getOperand(
13039         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13040     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13041 
13042     if (ISD::isSignedIntSetCC(CC)) {
13043       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13044           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13045         return SDValue();
13046     } else if (ISD::isUnsignedIntSetCC(CC)) {
13047       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13048                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13049           !DAG.MaskedValueIsZero(N->getOperand(1),
13050                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13051         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13052                                              : SDValue());
13053     } else {
13054       // This is neither a signed nor an unsigned comparison, just make sure
13055       // that the high bits are equal.
13056       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13057       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13058 
13059       // We don't really care about what is known about the first bit (if
13060       // anything), so clear it in all masks prior to comparing them.
13061       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
13062       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
13063 
13064       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
13065         return SDValue();
13066     }
13067   }
13068 
13069   // We now know that the higher-order bits are irrelevant, we just need to
13070   // make sure that all of the intermediate operations are bit operations, and
13071   // all inputs are extensions.
13072   if (N->getOperand(0).getOpcode() != ISD::AND &&
13073       N->getOperand(0).getOpcode() != ISD::OR  &&
13074       N->getOperand(0).getOpcode() != ISD::XOR &&
13075       N->getOperand(0).getOpcode() != ISD::SELECT &&
13076       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13077       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13078       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13079       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13080       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13081     return SDValue();
13082 
13083   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13084       N->getOperand(1).getOpcode() != ISD::AND &&
13085       N->getOperand(1).getOpcode() != ISD::OR  &&
13086       N->getOperand(1).getOpcode() != ISD::XOR &&
13087       N->getOperand(1).getOpcode() != ISD::SELECT &&
13088       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13089       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13090       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13091       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13092       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13093     return SDValue();
13094 
13095   SmallVector<SDValue, 4> Inputs;
13096   SmallVector<SDValue, 8> BinOps, PromOps;
13097   SmallPtrSet<SDNode *, 16> Visited;
13098 
13099   for (unsigned i = 0; i < 2; ++i) {
13100     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13101           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13102           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13103           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13104         isa<ConstantSDNode>(N->getOperand(i)))
13105       Inputs.push_back(N->getOperand(i));
13106     else
13107       BinOps.push_back(N->getOperand(i));
13108 
13109     if (N->getOpcode() == ISD::TRUNCATE)
13110       break;
13111   }
13112 
13113   // Visit all inputs, collect all binary operations (and, or, xor and
13114   // select) that are all fed by extensions.
13115   while (!BinOps.empty()) {
13116     SDValue BinOp = BinOps.back();
13117     BinOps.pop_back();
13118 
13119     if (!Visited.insert(BinOp.getNode()).second)
13120       continue;
13121 
13122     PromOps.push_back(BinOp);
13123 
13124     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13125       // The condition of the select is not promoted.
13126       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13127         continue;
13128       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13129         continue;
13130 
13131       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13132             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13133             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13134            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13135           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13136         Inputs.push_back(BinOp.getOperand(i));
13137       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13138                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13139                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13140                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13141                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13142                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13143                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13144                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13145                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13146         BinOps.push_back(BinOp.getOperand(i));
13147       } else {
13148         // We have an input that is not an extension or another binary
13149         // operation; we'll abort this transformation.
13150         return SDValue();
13151       }
13152     }
13153   }
13154 
13155   // Make sure that this is a self-contained cluster of operations (which
13156   // is not quite the same thing as saying that everything has only one
13157   // use).
13158   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13159     if (isa<ConstantSDNode>(Inputs[i]))
13160       continue;
13161 
13162     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13163                               UE = Inputs[i].getNode()->use_end();
13164          UI != UE; ++UI) {
13165       SDNode *User = *UI;
13166       if (User != N && !Visited.count(User))
13167         return SDValue();
13168 
13169       // Make sure that we're not going to promote the non-output-value
13170       // operand(s) or SELECT or SELECT_CC.
13171       // FIXME: Although we could sometimes handle this, and it does occur in
13172       // practice that one of the condition inputs to the select is also one of
13173       // the outputs, we currently can't deal with this.
13174       if (User->getOpcode() == ISD::SELECT) {
13175         if (User->getOperand(0) == Inputs[i])
13176           return SDValue();
13177       } else if (User->getOpcode() == ISD::SELECT_CC) {
13178         if (User->getOperand(0) == Inputs[i] ||
13179             User->getOperand(1) == Inputs[i])
13180           return SDValue();
13181       }
13182     }
13183   }
13184 
13185   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13186     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13187                               UE = PromOps[i].getNode()->use_end();
13188          UI != UE; ++UI) {
13189       SDNode *User = *UI;
13190       if (User != N && !Visited.count(User))
13191         return SDValue();
13192 
13193       // Make sure that we're not going to promote the non-output-value
13194       // operand(s) or SELECT or SELECT_CC.
13195       // FIXME: Although we could sometimes handle this, and it does occur in
13196       // practice that one of the condition inputs to the select is also one of
13197       // the outputs, we currently can't deal with this.
13198       if (User->getOpcode() == ISD::SELECT) {
13199         if (User->getOperand(0) == PromOps[i])
13200           return SDValue();
13201       } else if (User->getOpcode() == ISD::SELECT_CC) {
13202         if (User->getOperand(0) == PromOps[i] ||
13203             User->getOperand(1) == PromOps[i])
13204           return SDValue();
13205       }
13206     }
13207   }
13208 
13209   // Replace all inputs with the extension operand.
13210   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13211     // Constants may have users outside the cluster of to-be-promoted nodes,
13212     // and so we need to replace those as we do the promotions.
13213     if (isa<ConstantSDNode>(Inputs[i]))
13214       continue;
13215     else
13216       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13217   }
13218 
13219   std::list<HandleSDNode> PromOpHandles;
13220   for (auto &PromOp : PromOps)
13221     PromOpHandles.emplace_back(PromOp);
13222 
13223   // Replace all operations (these are all the same, but have a different
13224   // (i1) return type). DAG.getNode will validate that the types of
13225   // a binary operator match, so go through the list in reverse so that
13226   // we've likely promoted both operands first. Any intermediate truncations or
13227   // extensions disappear.
13228   while (!PromOpHandles.empty()) {
13229     SDValue PromOp = PromOpHandles.back().getValue();
13230     PromOpHandles.pop_back();
13231 
13232     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13233         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13234         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13235         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13236       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13237           PromOp.getOperand(0).getValueType() != MVT::i1) {
13238         // The operand is not yet ready (see comment below).
13239         PromOpHandles.emplace_front(PromOp);
13240         continue;
13241       }
13242 
13243       SDValue RepValue = PromOp.getOperand(0);
13244       if (isa<ConstantSDNode>(RepValue))
13245         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13246 
13247       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13248       continue;
13249     }
13250 
13251     unsigned C;
13252     switch (PromOp.getOpcode()) {
13253     default:             C = 0; break;
13254     case ISD::SELECT:    C = 1; break;
13255     case ISD::SELECT_CC: C = 2; break;
13256     }
13257 
13258     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13259          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13260         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13261          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13262       // The to-be-promoted operands of this node have not yet been
13263       // promoted (this should be rare because we're going through the
13264       // list backward, but if one of the operands has several users in
13265       // this cluster of to-be-promoted nodes, it is possible).
13266       PromOpHandles.emplace_front(PromOp);
13267       continue;
13268     }
13269 
13270     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13271                                 PromOp.getNode()->op_end());
13272 
13273     // If there are any constant inputs, make sure they're replaced now.
13274     for (unsigned i = 0; i < 2; ++i)
13275       if (isa<ConstantSDNode>(Ops[C+i]))
13276         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13277 
13278     DAG.ReplaceAllUsesOfValueWith(PromOp,
13279       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13280   }
13281 
13282   // Now we're left with the initial truncation itself.
13283   if (N->getOpcode() == ISD::TRUNCATE)
13284     return N->getOperand(0);
13285 
13286   // Otherwise, this is a comparison. The operands to be compared have just
13287   // changed type (to i1), but everything else is the same.
13288   return SDValue(N, 0);
13289 }
13290 
13291 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13292                                                   DAGCombinerInfo &DCI) const {
13293   SelectionDAG &DAG = DCI.DAG;
13294   SDLoc dl(N);
13295 
13296   // If we're tracking CR bits, we need to be careful that we don't have:
13297   //   zext(binary-ops(trunc(x), trunc(y)))
13298   // or
13299   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13300   // such that we're unnecessarily moving things into CR bits that can more
13301   // efficiently stay in GPRs. Note that if we're not certain that the high
13302   // bits are set as required by the final extension, we still may need to do
13303   // some masking to get the proper behavior.
13304 
13305   // This same functionality is important on PPC64 when dealing with
13306   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13307   // the return values of functions. Because it is so similar, it is handled
13308   // here as well.
13309 
13310   if (N->getValueType(0) != MVT::i32 &&
13311       N->getValueType(0) != MVT::i64)
13312     return SDValue();
13313 
13314   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13315         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13316     return SDValue();
13317 
13318   if (N->getOperand(0).getOpcode() != ISD::AND &&
13319       N->getOperand(0).getOpcode() != ISD::OR  &&
13320       N->getOperand(0).getOpcode() != ISD::XOR &&
13321       N->getOperand(0).getOpcode() != ISD::SELECT &&
13322       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13323     return SDValue();
13324 
13325   SmallVector<SDValue, 4> Inputs;
13326   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13327   SmallPtrSet<SDNode *, 16> Visited;
13328 
13329   // Visit all inputs, collect all binary operations (and, or, xor and
13330   // select) that are all fed by truncations.
13331   while (!BinOps.empty()) {
13332     SDValue BinOp = BinOps.back();
13333     BinOps.pop_back();
13334 
13335     if (!Visited.insert(BinOp.getNode()).second)
13336       continue;
13337 
13338     PromOps.push_back(BinOp);
13339 
13340     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13341       // The condition of the select is not promoted.
13342       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13343         continue;
13344       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13345         continue;
13346 
13347       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13348           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13349         Inputs.push_back(BinOp.getOperand(i));
13350       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13351                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13352                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13353                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13354                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13355         BinOps.push_back(BinOp.getOperand(i));
13356       } else {
13357         // We have an input that is not a truncation or another binary
13358         // operation; we'll abort this transformation.
13359         return SDValue();
13360       }
13361     }
13362   }
13363 
13364   // The operands of a select that must be truncated when the select is
13365   // promoted because the operand is actually part of the to-be-promoted set.
13366   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13367 
13368   // Make sure that this is a self-contained cluster of operations (which
13369   // is not quite the same thing as saying that everything has only one
13370   // use).
13371   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13372     if (isa<ConstantSDNode>(Inputs[i]))
13373       continue;
13374 
13375     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13376                               UE = Inputs[i].getNode()->use_end();
13377          UI != UE; ++UI) {
13378       SDNode *User = *UI;
13379       if (User != N && !Visited.count(User))
13380         return SDValue();
13381 
13382       // If we're going to promote the non-output-value operand(s) or SELECT or
13383       // SELECT_CC, record them for truncation.
13384       if (User->getOpcode() == ISD::SELECT) {
13385         if (User->getOperand(0) == Inputs[i])
13386           SelectTruncOp[0].insert(std::make_pair(User,
13387                                     User->getOperand(0).getValueType()));
13388       } else if (User->getOpcode() == ISD::SELECT_CC) {
13389         if (User->getOperand(0) == Inputs[i])
13390           SelectTruncOp[0].insert(std::make_pair(User,
13391                                     User->getOperand(0).getValueType()));
13392         if (User->getOperand(1) == Inputs[i])
13393           SelectTruncOp[1].insert(std::make_pair(User,
13394                                     User->getOperand(1).getValueType()));
13395       }
13396     }
13397   }
13398 
13399   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13400     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13401                               UE = PromOps[i].getNode()->use_end();
13402          UI != UE; ++UI) {
13403       SDNode *User = *UI;
13404       if (User != N && !Visited.count(User))
13405         return SDValue();
13406 
13407       // If we're going to promote the non-output-value operand(s) or SELECT or
13408       // SELECT_CC, record them for truncation.
13409       if (User->getOpcode() == ISD::SELECT) {
13410         if (User->getOperand(0) == PromOps[i])
13411           SelectTruncOp[0].insert(std::make_pair(User,
13412                                     User->getOperand(0).getValueType()));
13413       } else if (User->getOpcode() == ISD::SELECT_CC) {
13414         if (User->getOperand(0) == PromOps[i])
13415           SelectTruncOp[0].insert(std::make_pair(User,
13416                                     User->getOperand(0).getValueType()));
13417         if (User->getOperand(1) == PromOps[i])
13418           SelectTruncOp[1].insert(std::make_pair(User,
13419                                     User->getOperand(1).getValueType()));
13420       }
13421     }
13422   }
13423 
13424   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13425   bool ReallyNeedsExt = false;
13426   if (N->getOpcode() != ISD::ANY_EXTEND) {
13427     // If all of the inputs are not already sign/zero extended, then
13428     // we'll still need to do that at the end.
13429     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13430       if (isa<ConstantSDNode>(Inputs[i]))
13431         continue;
13432 
13433       unsigned OpBits =
13434         Inputs[i].getOperand(0).getValueSizeInBits();
13435       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13436 
13437       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13438            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13439                                   APInt::getHighBitsSet(OpBits,
13440                                                         OpBits-PromBits))) ||
13441           (N->getOpcode() == ISD::SIGN_EXTEND &&
13442            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13443              (OpBits-(PromBits-1)))) {
13444         ReallyNeedsExt = true;
13445         break;
13446       }
13447     }
13448   }
13449 
13450   // Replace all inputs, either with the truncation operand, or a
13451   // truncation or extension to the final output type.
13452   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13453     // Constant inputs need to be replaced with the to-be-promoted nodes that
13454     // use them because they might have users outside of the cluster of
13455     // promoted nodes.
13456     if (isa<ConstantSDNode>(Inputs[i]))
13457       continue;
13458 
13459     SDValue InSrc = Inputs[i].getOperand(0);
13460     if (Inputs[i].getValueType() == N->getValueType(0))
13461       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13462     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13463       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13464         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13465     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13466       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13467         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13468     else
13469       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13470         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13471   }
13472 
13473   std::list<HandleSDNode> PromOpHandles;
13474   for (auto &PromOp : PromOps)
13475     PromOpHandles.emplace_back(PromOp);
13476 
13477   // Replace all operations (these are all the same, but have a different
13478   // (promoted) return type). DAG.getNode will validate that the types of
13479   // a binary operator match, so go through the list in reverse so that
13480   // we've likely promoted both operands first.
13481   while (!PromOpHandles.empty()) {
13482     SDValue PromOp = PromOpHandles.back().getValue();
13483     PromOpHandles.pop_back();
13484 
13485     unsigned C;
13486     switch (PromOp.getOpcode()) {
13487     default:             C = 0; break;
13488     case ISD::SELECT:    C = 1; break;
13489     case ISD::SELECT_CC: C = 2; break;
13490     }
13491 
13492     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13493          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13494         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13495          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13496       // The to-be-promoted operands of this node have not yet been
13497       // promoted (this should be rare because we're going through the
13498       // list backward, but if one of the operands has several users in
13499       // this cluster of to-be-promoted nodes, it is possible).
13500       PromOpHandles.emplace_front(PromOp);
13501       continue;
13502     }
13503 
13504     // For SELECT and SELECT_CC nodes, we do a similar check for any
13505     // to-be-promoted comparison inputs.
13506     if (PromOp.getOpcode() == ISD::SELECT ||
13507         PromOp.getOpcode() == ISD::SELECT_CC) {
13508       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13509            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13510           (SelectTruncOp[1].count(PromOp.getNode()) &&
13511            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13512         PromOpHandles.emplace_front(PromOp);
13513         continue;
13514       }
13515     }
13516 
13517     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13518                                 PromOp.getNode()->op_end());
13519 
13520     // If this node has constant inputs, then they'll need to be promoted here.
13521     for (unsigned i = 0; i < 2; ++i) {
13522       if (!isa<ConstantSDNode>(Ops[C+i]))
13523         continue;
13524       if (Ops[C+i].getValueType() == N->getValueType(0))
13525         continue;
13526 
13527       if (N->getOpcode() == ISD::SIGN_EXTEND)
13528         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13529       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13530         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13531       else
13532         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13533     }
13534 
13535     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13536     // truncate them again to the original value type.
13537     if (PromOp.getOpcode() == ISD::SELECT ||
13538         PromOp.getOpcode() == ISD::SELECT_CC) {
13539       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13540       if (SI0 != SelectTruncOp[0].end())
13541         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13542       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13543       if (SI1 != SelectTruncOp[1].end())
13544         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13545     }
13546 
13547     DAG.ReplaceAllUsesOfValueWith(PromOp,
13548       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13549   }
13550 
13551   // Now we're left with the initial extension itself.
13552   if (!ReallyNeedsExt)
13553     return N->getOperand(0);
13554 
13555   // To zero extend, just mask off everything except for the first bit (in the
13556   // i1 case).
13557   if (N->getOpcode() == ISD::ZERO_EXTEND)
13558     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13559                        DAG.getConstant(APInt::getLowBitsSet(
13560                                          N->getValueSizeInBits(0), PromBits),
13561                                        dl, N->getValueType(0)));
13562 
13563   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13564          "Invalid extension type");
13565   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13566   SDValue ShiftCst =
13567       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13568   return DAG.getNode(
13569       ISD::SRA, dl, N->getValueType(0),
13570       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13571       ShiftCst);
13572 }
13573 
13574 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13575                                         DAGCombinerInfo &DCI) const {
13576   assert(N->getOpcode() == ISD::SETCC &&
13577          "Should be called with a SETCC node");
13578 
13579   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13580   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13581     SDValue LHS = N->getOperand(0);
13582     SDValue RHS = N->getOperand(1);
13583 
13584     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13585     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13586         LHS.hasOneUse())
13587       std::swap(LHS, RHS);
13588 
13589     // x == 0-y --> x+y == 0
13590     // x != 0-y --> x+y != 0
13591     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13592         RHS.hasOneUse()) {
13593       SDLoc DL(N);
13594       SelectionDAG &DAG = DCI.DAG;
13595       EVT VT = N->getValueType(0);
13596       EVT OpVT = LHS.getValueType();
13597       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13598       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13599     }
13600   }
13601 
13602   return DAGCombineTruncBoolExt(N, DCI);
13603 }
13604 
13605 // Is this an extending load from an f32 to an f64?
13606 static bool isFPExtLoad(SDValue Op) {
13607   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13608     return LD->getExtensionType() == ISD::EXTLOAD &&
13609       Op.getValueType() == MVT::f64;
13610   return false;
13611 }
13612 
13613 /// Reduces the number of fp-to-int conversion when building a vector.
13614 ///
13615 /// If this vector is built out of floating to integer conversions,
13616 /// transform it to a vector built out of floating point values followed by a
13617 /// single floating to integer conversion of the vector.
13618 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13619 /// becomes (fptosi (build_vector ($A, $B, ...)))
13620 SDValue PPCTargetLowering::
13621 combineElementTruncationToVectorTruncation(SDNode *N,
13622                                            DAGCombinerInfo &DCI) const {
13623   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13624          "Should be called with a BUILD_VECTOR node");
13625 
13626   SelectionDAG &DAG = DCI.DAG;
13627   SDLoc dl(N);
13628 
13629   SDValue FirstInput = N->getOperand(0);
13630   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13631          "The input operand must be an fp-to-int conversion.");
13632 
13633   // This combine happens after legalization so the fp_to_[su]i nodes are
13634   // already converted to PPCSISD nodes.
13635   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13636   if (FirstConversion == PPCISD::FCTIDZ ||
13637       FirstConversion == PPCISD::FCTIDUZ ||
13638       FirstConversion == PPCISD::FCTIWZ ||
13639       FirstConversion == PPCISD::FCTIWUZ) {
13640     bool IsSplat = true;
13641     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13642       FirstConversion == PPCISD::FCTIWUZ;
13643     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13644     SmallVector<SDValue, 4> Ops;
13645     EVT TargetVT = N->getValueType(0);
13646     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13647       SDValue NextOp = N->getOperand(i);
13648       if (NextOp.getOpcode() != PPCISD::MFVSR)
13649         return SDValue();
13650       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13651       if (NextConversion != FirstConversion)
13652         return SDValue();
13653       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13654       // This is not valid if the input was originally double precision. It is
13655       // also not profitable to do unless this is an extending load in which
13656       // case doing this combine will allow us to combine consecutive loads.
13657       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13658         return SDValue();
13659       if (N->getOperand(i) != FirstInput)
13660         IsSplat = false;
13661     }
13662 
13663     // If this is a splat, we leave it as-is since there will be only a single
13664     // fp-to-int conversion followed by a splat of the integer. This is better
13665     // for 32-bit and smaller ints and neutral for 64-bit ints.
13666     if (IsSplat)
13667       return SDValue();
13668 
13669     // Now that we know we have the right type of node, get its operands
13670     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13671       SDValue In = N->getOperand(i).getOperand(0);
13672       if (Is32Bit) {
13673         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13674         // here, we know that all inputs are extending loads so this is safe).
13675         if (In.isUndef())
13676           Ops.push_back(DAG.getUNDEF(SrcVT));
13677         else {
13678           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13679                                       MVT::f32, In.getOperand(0),
13680                                       DAG.getIntPtrConstant(1, dl));
13681           Ops.push_back(Trunc);
13682         }
13683       } else
13684         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13685     }
13686 
13687     unsigned Opcode;
13688     if (FirstConversion == PPCISD::FCTIDZ ||
13689         FirstConversion == PPCISD::FCTIWZ)
13690       Opcode = ISD::FP_TO_SINT;
13691     else
13692       Opcode = ISD::FP_TO_UINT;
13693 
13694     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13695     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13696     return DAG.getNode(Opcode, dl, TargetVT, BV);
13697   }
13698   return SDValue();
13699 }
13700 
13701 /// Reduce the number of loads when building a vector.
13702 ///
13703 /// Building a vector out of multiple loads can be converted to a load
13704 /// of the vector type if the loads are consecutive. If the loads are
13705 /// consecutive but in descending order, a shuffle is added at the end
13706 /// to reorder the vector.
13707 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13708   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13709          "Should be called with a BUILD_VECTOR node");
13710 
13711   SDLoc dl(N);
13712 
13713   // Return early for non byte-sized type, as they can't be consecutive.
13714   if (!N->getValueType(0).getVectorElementType().isByteSized())
13715     return SDValue();
13716 
13717   bool InputsAreConsecutiveLoads = true;
13718   bool InputsAreReverseConsecutive = true;
13719   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13720   SDValue FirstInput = N->getOperand(0);
13721   bool IsRoundOfExtLoad = false;
13722 
13723   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13724       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13725     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13726     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13727   }
13728   // Not a build vector of (possibly fp_rounded) loads.
13729   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13730       N->getNumOperands() == 1)
13731     return SDValue();
13732 
13733   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13734     // If any inputs are fp_round(extload), they all must be.
13735     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13736       return SDValue();
13737 
13738     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13739       N->getOperand(i);
13740     if (NextInput.getOpcode() != ISD::LOAD)
13741       return SDValue();
13742 
13743     SDValue PreviousInput =
13744       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13745     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13746     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13747 
13748     // If any inputs are fp_round(extload), they all must be.
13749     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13750       return SDValue();
13751 
13752     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13753       InputsAreConsecutiveLoads = false;
13754     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13755       InputsAreReverseConsecutive = false;
13756 
13757     // Exit early if the loads are neither consecutive nor reverse consecutive.
13758     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13759       return SDValue();
13760   }
13761 
13762   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13763          "The loads cannot be both consecutive and reverse consecutive.");
13764 
13765   SDValue FirstLoadOp =
13766     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13767   SDValue LastLoadOp =
13768     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13769                        N->getOperand(N->getNumOperands()-1);
13770 
13771   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13772   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13773   if (InputsAreConsecutiveLoads) {
13774     assert(LD1 && "Input needs to be a LoadSDNode.");
13775     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13776                        LD1->getBasePtr(), LD1->getPointerInfo(),
13777                        LD1->getAlignment());
13778   }
13779   if (InputsAreReverseConsecutive) {
13780     assert(LDL && "Input needs to be a LoadSDNode.");
13781     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13782                                LDL->getBasePtr(), LDL->getPointerInfo(),
13783                                LDL->getAlignment());
13784     SmallVector<int, 16> Ops;
13785     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13786       Ops.push_back(i);
13787 
13788     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13789                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13790   }
13791   return SDValue();
13792 }
13793 
13794 // This function adds the required vector_shuffle needed to get
13795 // the elements of the vector extract in the correct position
13796 // as specified by the CorrectElems encoding.
13797 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13798                                       SDValue Input, uint64_t Elems,
13799                                       uint64_t CorrectElems) {
13800   SDLoc dl(N);
13801 
13802   unsigned NumElems = Input.getValueType().getVectorNumElements();
13803   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13804 
13805   // Knowing the element indices being extracted from the original
13806   // vector and the order in which they're being inserted, just put
13807   // them at element indices required for the instruction.
13808   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13809     if (DAG.getDataLayout().isLittleEndian())
13810       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13811     else
13812       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13813     CorrectElems = CorrectElems >> 8;
13814     Elems = Elems >> 8;
13815   }
13816 
13817   SDValue Shuffle =
13818       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13819                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13820 
13821   EVT VT = N->getValueType(0);
13822   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13823 
13824   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13825                                Input.getValueType().getVectorElementType(),
13826                                VT.getVectorNumElements());
13827   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13828                      DAG.getValueType(ExtVT));
13829 }
13830 
13831 // Look for build vector patterns where input operands come from sign
13832 // extended vector_extract elements of specific indices. If the correct indices
13833 // aren't used, add a vector shuffle to fix up the indices and create
13834 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13835 // during instruction selection.
13836 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13837   // This array encodes the indices that the vector sign extend instructions
13838   // extract from when extending from one type to another for both BE and LE.
13839   // The right nibble of each byte corresponds to the LE incides.
13840   // and the left nibble of each byte corresponds to the BE incides.
13841   // For example: 0x3074B8FC  byte->word
13842   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13843   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13844   // For example: 0x000070F8  byte->double word
13845   // For LE: the allowed indices are: 0x0,0x8
13846   // For BE: the allowed indices are: 0x7,0xF
13847   uint64_t TargetElems[] = {
13848       0x3074B8FC, // b->w
13849       0x000070F8, // b->d
13850       0x10325476, // h->w
13851       0x00003074, // h->d
13852       0x00001032, // w->d
13853   };
13854 
13855   uint64_t Elems = 0;
13856   int Index;
13857   SDValue Input;
13858 
13859   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13860     if (!Op)
13861       return false;
13862     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13863         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13864       return false;
13865 
13866     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13867     // of the right width.
13868     SDValue Extract = Op.getOperand(0);
13869     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13870       Extract = Extract.getOperand(0);
13871     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13872       return false;
13873 
13874     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13875     if (!ExtOp)
13876       return false;
13877 
13878     Index = ExtOp->getZExtValue();
13879     if (Input && Input != Extract.getOperand(0))
13880       return false;
13881 
13882     if (!Input)
13883       Input = Extract.getOperand(0);
13884 
13885     Elems = Elems << 8;
13886     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13887     Elems |= Index;
13888 
13889     return true;
13890   };
13891 
13892   // If the build vector operands aren't sign extended vector extracts,
13893   // of the same input vector, then return.
13894   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13895     if (!isSExtOfVecExtract(N->getOperand(i))) {
13896       return SDValue();
13897     }
13898   }
13899 
13900   // If the vector extract indicies are not correct, add the appropriate
13901   // vector_shuffle.
13902   int TgtElemArrayIdx;
13903   int InputSize = Input.getValueType().getScalarSizeInBits();
13904   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13905   if (InputSize + OutputSize == 40)
13906     TgtElemArrayIdx = 0;
13907   else if (InputSize + OutputSize == 72)
13908     TgtElemArrayIdx = 1;
13909   else if (InputSize + OutputSize == 48)
13910     TgtElemArrayIdx = 2;
13911   else if (InputSize + OutputSize == 80)
13912     TgtElemArrayIdx = 3;
13913   else if (InputSize + OutputSize == 96)
13914     TgtElemArrayIdx = 4;
13915   else
13916     return SDValue();
13917 
13918   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13919   CorrectElems = DAG.getDataLayout().isLittleEndian()
13920                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13921                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13922   if (Elems != CorrectElems) {
13923     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13924   }
13925 
13926   // Regular lowering will catch cases where a shuffle is not needed.
13927   return SDValue();
13928 }
13929 
13930 // Look for the pattern of a load from a narrow width to i128, feeding
13931 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13932 // (LXVRZX). This node represents a zero extending load that will be matched
13933 // to the Load VSX Vector Rightmost instructions.
13934 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13935   SDLoc DL(N);
13936 
13937   // This combine is only eligible for a BUILD_VECTOR of v1i128.
13938   if (N->getValueType(0) != MVT::v1i128)
13939     return SDValue();
13940 
13941   SDValue Operand = N->getOperand(0);
13942   // Proceed with the transformation if the operand to the BUILD_VECTOR
13943   // is a load instruction.
13944   if (Operand.getOpcode() != ISD::LOAD)
13945     return SDValue();
13946 
13947   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
13948   EVT MemoryType = LD->getMemoryVT();
13949 
13950   // This transformation is only valid if the we are loading either a byte,
13951   // halfword, word, or doubleword.
13952   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
13953                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
13954 
13955   // Ensure that the load from the narrow width is being zero extended to i128.
13956   if (!ValidLDType ||
13957       (LD->getExtensionType() != ISD::ZEXTLOAD &&
13958        LD->getExtensionType() != ISD::EXTLOAD))
13959     return SDValue();
13960 
13961   SDValue LoadOps[] = {
13962       LD->getChain(), LD->getBasePtr(),
13963       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
13964 
13965   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
13966                                  DAG.getVTList(MVT::v1i128, MVT::Other),
13967                                  LoadOps, MemoryType, LD->getMemOperand());
13968 }
13969 
13970 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13971                                                  DAGCombinerInfo &DCI) const {
13972   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13973          "Should be called with a BUILD_VECTOR node");
13974 
13975   SelectionDAG &DAG = DCI.DAG;
13976   SDLoc dl(N);
13977 
13978   if (!Subtarget.hasVSX())
13979     return SDValue();
13980 
13981   // The target independent DAG combiner will leave a build_vector of
13982   // float-to-int conversions intact. We can generate MUCH better code for
13983   // a float-to-int conversion of a vector of floats.
13984   SDValue FirstInput = N->getOperand(0);
13985   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13986     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13987     if (Reduced)
13988       return Reduced;
13989   }
13990 
13991   // If we're building a vector out of consecutive loads, just load that
13992   // vector type.
13993   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13994   if (Reduced)
13995     return Reduced;
13996 
13997   // If we're building a vector out of extended elements from another vector
13998   // we have P9 vector integer extend instructions. The code assumes legal
13999   // input types (i.e. it can't handle things like v4i16) so do not run before
14000   // legalization.
14001   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14002     Reduced = combineBVOfVecSExt(N, DAG);
14003     if (Reduced)
14004       return Reduced;
14005   }
14006 
14007   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14008   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14009   // is a load from <valid narrow width> to i128.
14010   if (Subtarget.isISA3_1()) {
14011     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14012     if (BVOfZLoad)
14013       return BVOfZLoad;
14014   }
14015 
14016   if (N->getValueType(0) != MVT::v2f64)
14017     return SDValue();
14018 
14019   // Looking for:
14020   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14021   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14022       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14023     return SDValue();
14024   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14025       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14026     return SDValue();
14027   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14028     return SDValue();
14029 
14030   SDValue Ext1 = FirstInput.getOperand(0);
14031   SDValue Ext2 = N->getOperand(1).getOperand(0);
14032   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14033      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14034     return SDValue();
14035 
14036   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14037   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14038   if (!Ext1Op || !Ext2Op)
14039     return SDValue();
14040   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14041       Ext1.getOperand(0) != Ext2.getOperand(0))
14042     return SDValue();
14043 
14044   int FirstElem = Ext1Op->getZExtValue();
14045   int SecondElem = Ext2Op->getZExtValue();
14046   int SubvecIdx;
14047   if (FirstElem == 0 && SecondElem == 1)
14048     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14049   else if (FirstElem == 2 && SecondElem == 3)
14050     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14051   else
14052     return SDValue();
14053 
14054   SDValue SrcVec = Ext1.getOperand(0);
14055   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14056     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14057   return DAG.getNode(NodeType, dl, MVT::v2f64,
14058                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14059 }
14060 
14061 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14062                                               DAGCombinerInfo &DCI) const {
14063   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14064           N->getOpcode() == ISD::UINT_TO_FP) &&
14065          "Need an int -> FP conversion node here");
14066 
14067   if (useSoftFloat() || !Subtarget.has64BitSupport())
14068     return SDValue();
14069 
14070   SelectionDAG &DAG = DCI.DAG;
14071   SDLoc dl(N);
14072   SDValue Op(N, 0);
14073 
14074   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14075   // from the hardware.
14076   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14077     return SDValue();
14078   if (!Op.getOperand(0).getValueType().isSimple())
14079     return SDValue();
14080   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14081       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14082     return SDValue();
14083 
14084   SDValue FirstOperand(Op.getOperand(0));
14085   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14086     (FirstOperand.getValueType() == MVT::i8 ||
14087      FirstOperand.getValueType() == MVT::i16);
14088   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14089     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14090     bool DstDouble = Op.getValueType() == MVT::f64;
14091     unsigned ConvOp = Signed ?
14092       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14093       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14094     SDValue WidthConst =
14095       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14096                             dl, false);
14097     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14098     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14099     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14100                                          DAG.getVTList(MVT::f64, MVT::Other),
14101                                          Ops, MVT::i8, LDN->getMemOperand());
14102 
14103     // For signed conversion, we need to sign-extend the value in the VSR
14104     if (Signed) {
14105       SDValue ExtOps[] = { Ld, WidthConst };
14106       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14107       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14108     } else
14109       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14110   }
14111 
14112 
14113   // For i32 intermediate values, unfortunately, the conversion functions
14114   // leave the upper 32 bits of the value are undefined. Within the set of
14115   // scalar instructions, we have no method for zero- or sign-extending the
14116   // value. Thus, we cannot handle i32 intermediate values here.
14117   if (Op.getOperand(0).getValueType() == MVT::i32)
14118     return SDValue();
14119 
14120   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14121          "UINT_TO_FP is supported only with FPCVT");
14122 
14123   // If we have FCFIDS, then use it when converting to single-precision.
14124   // Otherwise, convert to double-precision and then round.
14125   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14126                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14127                                                             : PPCISD::FCFIDS)
14128                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14129                                                             : PPCISD::FCFID);
14130   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14131                   ? MVT::f32
14132                   : MVT::f64;
14133 
14134   // If we're converting from a float, to an int, and back to a float again,
14135   // then we don't need the store/load pair at all.
14136   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14137        Subtarget.hasFPCVT()) ||
14138       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14139     SDValue Src = Op.getOperand(0).getOperand(0);
14140     if (Src.getValueType() == MVT::f32) {
14141       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14142       DCI.AddToWorklist(Src.getNode());
14143     } else if (Src.getValueType() != MVT::f64) {
14144       // Make sure that we don't pick up a ppc_fp128 source value.
14145       return SDValue();
14146     }
14147 
14148     unsigned FCTOp =
14149       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14150                                                         PPCISD::FCTIDUZ;
14151 
14152     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14153     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14154 
14155     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14156       FP = DAG.getNode(ISD::FP_ROUND, dl,
14157                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14158       DCI.AddToWorklist(FP.getNode());
14159     }
14160 
14161     return FP;
14162   }
14163 
14164   return SDValue();
14165 }
14166 
14167 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14168 // builtins) into loads with swaps.
14169 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14170                                               DAGCombinerInfo &DCI) const {
14171   SelectionDAG &DAG = DCI.DAG;
14172   SDLoc dl(N);
14173   SDValue Chain;
14174   SDValue Base;
14175   MachineMemOperand *MMO;
14176 
14177   switch (N->getOpcode()) {
14178   default:
14179     llvm_unreachable("Unexpected opcode for little endian VSX load");
14180   case ISD::LOAD: {
14181     LoadSDNode *LD = cast<LoadSDNode>(N);
14182     Chain = LD->getChain();
14183     Base = LD->getBasePtr();
14184     MMO = LD->getMemOperand();
14185     // If the MMO suggests this isn't a load of a full vector, leave
14186     // things alone.  For a built-in, we have to make the change for
14187     // correctness, so if there is a size problem that will be a bug.
14188     if (MMO->getSize() < 16)
14189       return SDValue();
14190     break;
14191   }
14192   case ISD::INTRINSIC_W_CHAIN: {
14193     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14194     Chain = Intrin->getChain();
14195     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14196     // us what we want. Get operand 2 instead.
14197     Base = Intrin->getOperand(2);
14198     MMO = Intrin->getMemOperand();
14199     break;
14200   }
14201   }
14202 
14203   MVT VecTy = N->getValueType(0).getSimpleVT();
14204 
14205   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14206   // aligned and the type is a vector with elements up to 4 bytes
14207   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14208       VecTy.getScalarSizeInBits() <= 32) {
14209     return SDValue();
14210   }
14211 
14212   SDValue LoadOps[] = { Chain, Base };
14213   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14214                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14215                                          LoadOps, MVT::v2f64, MMO);
14216 
14217   DCI.AddToWorklist(Load.getNode());
14218   Chain = Load.getValue(1);
14219   SDValue Swap = DAG.getNode(
14220       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14221   DCI.AddToWorklist(Swap.getNode());
14222 
14223   // Add a bitcast if the resulting load type doesn't match v2f64.
14224   if (VecTy != MVT::v2f64) {
14225     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14226     DCI.AddToWorklist(N.getNode());
14227     // Package {bitcast value, swap's chain} to match Load's shape.
14228     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14229                        N, Swap.getValue(1));
14230   }
14231 
14232   return Swap;
14233 }
14234 
14235 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14236 // builtins) into stores with swaps.
14237 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14238                                                DAGCombinerInfo &DCI) const {
14239   SelectionDAG &DAG = DCI.DAG;
14240   SDLoc dl(N);
14241   SDValue Chain;
14242   SDValue Base;
14243   unsigned SrcOpnd;
14244   MachineMemOperand *MMO;
14245 
14246   switch (N->getOpcode()) {
14247   default:
14248     llvm_unreachable("Unexpected opcode for little endian VSX store");
14249   case ISD::STORE: {
14250     StoreSDNode *ST = cast<StoreSDNode>(N);
14251     Chain = ST->getChain();
14252     Base = ST->getBasePtr();
14253     MMO = ST->getMemOperand();
14254     SrcOpnd = 1;
14255     // If the MMO suggests this isn't a store of a full vector, leave
14256     // things alone.  For a built-in, we have to make the change for
14257     // correctness, so if there is a size problem that will be a bug.
14258     if (MMO->getSize() < 16)
14259       return SDValue();
14260     break;
14261   }
14262   case ISD::INTRINSIC_VOID: {
14263     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14264     Chain = Intrin->getChain();
14265     // Intrin->getBasePtr() oddly does not get what we want.
14266     Base = Intrin->getOperand(3);
14267     MMO = Intrin->getMemOperand();
14268     SrcOpnd = 2;
14269     break;
14270   }
14271   }
14272 
14273   SDValue Src = N->getOperand(SrcOpnd);
14274   MVT VecTy = Src.getValueType().getSimpleVT();
14275 
14276   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14277   // aligned and the type is a vector with elements up to 4 bytes
14278   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14279       VecTy.getScalarSizeInBits() <= 32) {
14280     return SDValue();
14281   }
14282 
14283   // All stores are done as v2f64 and possible bit cast.
14284   if (VecTy != MVT::v2f64) {
14285     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14286     DCI.AddToWorklist(Src.getNode());
14287   }
14288 
14289   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14290                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14291   DCI.AddToWorklist(Swap.getNode());
14292   Chain = Swap.getValue(1);
14293   SDValue StoreOps[] = { Chain, Swap, Base };
14294   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14295                                           DAG.getVTList(MVT::Other),
14296                                           StoreOps, VecTy, MMO);
14297   DCI.AddToWorklist(Store.getNode());
14298   return Store;
14299 }
14300 
14301 // Handle DAG combine for STORE (FP_TO_INT F).
14302 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14303                                                DAGCombinerInfo &DCI) const {
14304 
14305   SelectionDAG &DAG = DCI.DAG;
14306   SDLoc dl(N);
14307   unsigned Opcode = N->getOperand(1).getOpcode();
14308 
14309   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14310          && "Not a FP_TO_INT Instruction!");
14311 
14312   SDValue Val = N->getOperand(1).getOperand(0);
14313   EVT Op1VT = N->getOperand(1).getValueType();
14314   EVT ResVT = Val.getValueType();
14315 
14316   if (!isTypeLegal(ResVT))
14317     return SDValue();
14318 
14319   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14320   bool ValidTypeForStoreFltAsInt =
14321         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14322          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14323 
14324   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14325       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14326     return SDValue();
14327 
14328   // Extend f32 values to f64
14329   if (ResVT.getScalarSizeInBits() == 32) {
14330     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14331     DCI.AddToWorklist(Val.getNode());
14332   }
14333 
14334   // Set signed or unsigned conversion opcode.
14335   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14336                           PPCISD::FP_TO_SINT_IN_VSR :
14337                           PPCISD::FP_TO_UINT_IN_VSR;
14338 
14339   Val = DAG.getNode(ConvOpcode,
14340                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14341   DCI.AddToWorklist(Val.getNode());
14342 
14343   // Set number of bytes being converted.
14344   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14345   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14346                     DAG.getIntPtrConstant(ByteSize, dl, false),
14347                     DAG.getValueType(Op1VT) };
14348 
14349   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14350           DAG.getVTList(MVT::Other), Ops,
14351           cast<StoreSDNode>(N)->getMemoryVT(),
14352           cast<StoreSDNode>(N)->getMemOperand());
14353 
14354   DCI.AddToWorklist(Val.getNode());
14355   return Val;
14356 }
14357 
14358 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14359   // Check that the source of the element keeps flipping
14360   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14361   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14362   for (int i = 1, e = Mask.size(); i < e; i++) {
14363     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14364       return false;
14365     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14366       return false;
14367     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14368   }
14369   return true;
14370 }
14371 
14372 static bool isSplatBV(SDValue Op) {
14373   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14374     return false;
14375   SDValue FirstOp;
14376 
14377   // Find first non-undef input.
14378   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14379     FirstOp = Op.getOperand(i);
14380     if (!FirstOp.isUndef())
14381       break;
14382   }
14383 
14384   // All inputs are undef or the same as the first non-undef input.
14385   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14386     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14387       return false;
14388   return true;
14389 }
14390 
14391 static SDValue isScalarToVec(SDValue Op) {
14392   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14393     return Op;
14394   if (Op.getOpcode() != ISD::BITCAST)
14395     return SDValue();
14396   Op = Op.getOperand(0);
14397   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14398     return Op;
14399   return SDValue();
14400 }
14401 
14402 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14403                                             int LHSMaxIdx, int RHSMinIdx,
14404                                             int RHSMaxIdx, int HalfVec) {
14405   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14406     int Idx = ShuffV[i];
14407     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14408       ShuffV[i] += HalfVec;
14409   }
14410   return;
14411 }
14412 
14413 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14414 // the original is:
14415 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14416 // In such a case, just change the shuffle mask to extract the element
14417 // from the permuted index.
14418 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14419   SDLoc dl(OrigSToV);
14420   EVT VT = OrigSToV.getValueType();
14421   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14422          "Expecting a SCALAR_TO_VECTOR here");
14423   SDValue Input = OrigSToV.getOperand(0);
14424 
14425   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14426     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14427     SDValue OrigVector = Input.getOperand(0);
14428 
14429     // Can't handle non-const element indices or different vector types
14430     // for the input to the extract and the output of the scalar_to_vector.
14431     if (Idx && VT == OrigVector.getValueType()) {
14432       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14433       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14434       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14435     }
14436   }
14437   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14438                      OrigSToV.getOperand(0));
14439 }
14440 
14441 // On little endian subtargets, combine shuffles such as:
14442 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14443 // into:
14444 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14445 // because the latter can be matched to a single instruction merge.
14446 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14447 // to put the value into element zero. Adjust the shuffle mask so that the
14448 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14449 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14450                                                 SelectionDAG &DAG) const {
14451   SDValue LHS = SVN->getOperand(0);
14452   SDValue RHS = SVN->getOperand(1);
14453   auto Mask = SVN->getMask();
14454   int NumElts = LHS.getValueType().getVectorNumElements();
14455   SDValue Res(SVN, 0);
14456   SDLoc dl(SVN);
14457 
14458   // None of these combines are useful on big endian systems since the ISA
14459   // already has a big endian bias.
14460   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14461     return Res;
14462 
14463   // If this is not a shuffle of a shuffle and the first element comes from
14464   // the second vector, canonicalize to the commuted form. This will make it
14465   // more likely to match one of the single instruction patterns.
14466   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14467       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14468     std::swap(LHS, RHS);
14469     Res = DAG.getCommutedVectorShuffle(*SVN);
14470     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14471   }
14472 
14473   // Adjust the shuffle mask if either input vector comes from a
14474   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14475   // form (to prevent the need for a swap).
14476   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14477   SDValue SToVLHS = isScalarToVec(LHS);
14478   SDValue SToVRHS = isScalarToVec(RHS);
14479   if (SToVLHS || SToVRHS) {
14480     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14481                             : SToVRHS.getValueType().getVectorNumElements();
14482     int NumEltsOut = ShuffV.size();
14483 
14484     // Initially assume that neither input is permuted. These will be adjusted
14485     // accordingly if either input is.
14486     int LHSMaxIdx = -1;
14487     int RHSMinIdx = -1;
14488     int RHSMaxIdx = -1;
14489     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14490 
14491     // Get the permuted scalar to vector nodes for the source(s) that come from
14492     // ISD::SCALAR_TO_VECTOR.
14493     if (SToVLHS) {
14494       // Set up the values for the shuffle vector fixup.
14495       LHSMaxIdx = NumEltsOut / NumEltsIn;
14496       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14497       if (SToVLHS.getValueType() != LHS.getValueType())
14498         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14499       LHS = SToVLHS;
14500     }
14501     if (SToVRHS) {
14502       RHSMinIdx = NumEltsOut;
14503       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14504       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14505       if (SToVRHS.getValueType() != RHS.getValueType())
14506         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14507       RHS = SToVRHS;
14508     }
14509 
14510     // Fix up the shuffle mask to reflect where the desired element actually is.
14511     // The minimum and maximum indices that correspond to element zero for both
14512     // the LHS and RHS are computed and will control which shuffle mask entries
14513     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14514     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14515     // HalfVec to refer to the corresponding element in the permuted vector.
14516     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14517                                     HalfVec);
14518     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14519 
14520     // We may have simplified away the shuffle. We won't be able to do anything
14521     // further with it here.
14522     if (!isa<ShuffleVectorSDNode>(Res))
14523       return Res;
14524     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14525   }
14526 
14527   // The common case after we commuted the shuffle is that the RHS is a splat
14528   // and we have elements coming in from the splat at indices that are not
14529   // conducive to using a merge.
14530   // Example:
14531   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14532   if (!isSplatBV(RHS))
14533     return Res;
14534 
14535   // We are looking for a mask such that all even elements are from
14536   // one vector and all odd elements from the other.
14537   if (!isAlternatingShuffMask(Mask, NumElts))
14538     return Res;
14539 
14540   // Adjust the mask so we are pulling in the same index from the splat
14541   // as the index from the interesting vector in consecutive elements.
14542   // Example (even elements from first vector):
14543   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14544   if (Mask[0] < NumElts)
14545     for (int i = 1, e = Mask.size(); i < e; i += 2)
14546       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14547   // Example (odd elements from first vector):
14548   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14549   else
14550     for (int i = 0, e = Mask.size(); i < e; i += 2)
14551       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14552 
14553   // If the RHS has undefs, we need to remove them since we may have created
14554   // a shuffle that adds those instead of the splat value.
14555   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14556   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14557 
14558   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14559   return Res;
14560 }
14561 
14562 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14563                                                 LSBaseSDNode *LSBase,
14564                                                 DAGCombinerInfo &DCI) const {
14565   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14566         "Not a reverse memop pattern!");
14567 
14568   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14569     auto Mask = SVN->getMask();
14570     int i = 0;
14571     auto I = Mask.rbegin();
14572     auto E = Mask.rend();
14573 
14574     for (; I != E; ++I) {
14575       if (*I != i)
14576         return false;
14577       i++;
14578     }
14579     return true;
14580   };
14581 
14582   SelectionDAG &DAG = DCI.DAG;
14583   EVT VT = SVN->getValueType(0);
14584 
14585   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14586     return SDValue();
14587 
14588   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14589   // See comment in PPCVSXSwapRemoval.cpp.
14590   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14591   if (!Subtarget.hasP9Vector())
14592     return SDValue();
14593 
14594   if(!IsElementReverse(SVN))
14595     return SDValue();
14596 
14597   if (LSBase->getOpcode() == ISD::LOAD) {
14598     SDLoc dl(SVN);
14599     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14600     return DAG.getMemIntrinsicNode(
14601         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14602         LSBase->getMemoryVT(), LSBase->getMemOperand());
14603   }
14604 
14605   if (LSBase->getOpcode() == ISD::STORE) {
14606     SDLoc dl(LSBase);
14607     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14608                           LSBase->getBasePtr()};
14609     return DAG.getMemIntrinsicNode(
14610         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14611         LSBase->getMemoryVT(), LSBase->getMemOperand());
14612   }
14613 
14614   llvm_unreachable("Expected a load or store node here");
14615 }
14616 
14617 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14618                                              DAGCombinerInfo &DCI) const {
14619   SelectionDAG &DAG = DCI.DAG;
14620   SDLoc dl(N);
14621   switch (N->getOpcode()) {
14622   default: break;
14623   case ISD::ADD:
14624     return combineADD(N, DCI);
14625   case ISD::SHL:
14626     return combineSHL(N, DCI);
14627   case ISD::SRA:
14628     return combineSRA(N, DCI);
14629   case ISD::SRL:
14630     return combineSRL(N, DCI);
14631   case ISD::MUL:
14632     return combineMUL(N, DCI);
14633   case ISD::FMA:
14634   case PPCISD::FNMSUB:
14635     return combineFMALike(N, DCI);
14636   case PPCISD::SHL:
14637     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14638         return N->getOperand(0);
14639     break;
14640   case PPCISD::SRL:
14641     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14642         return N->getOperand(0);
14643     break;
14644   case PPCISD::SRA:
14645     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14646       if (C->isNullValue() ||   //  0 >>s V -> 0.
14647           C->isAllOnesValue())    // -1 >>s V -> -1.
14648         return N->getOperand(0);
14649     }
14650     break;
14651   case ISD::SIGN_EXTEND:
14652   case ISD::ZERO_EXTEND:
14653   case ISD::ANY_EXTEND:
14654     return DAGCombineExtBoolTrunc(N, DCI);
14655   case ISD::TRUNCATE:
14656     return combineTRUNCATE(N, DCI);
14657   case ISD::SETCC:
14658     if (SDValue CSCC = combineSetCC(N, DCI))
14659       return CSCC;
14660     LLVM_FALLTHROUGH;
14661   case ISD::SELECT_CC:
14662     return DAGCombineTruncBoolExt(N, DCI);
14663   case ISD::SINT_TO_FP:
14664   case ISD::UINT_TO_FP:
14665     return combineFPToIntToFP(N, DCI);
14666   case ISD::VECTOR_SHUFFLE:
14667     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14668       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14669       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14670     }
14671     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14672   case ISD::STORE: {
14673 
14674     EVT Op1VT = N->getOperand(1).getValueType();
14675     unsigned Opcode = N->getOperand(1).getOpcode();
14676 
14677     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14678       SDValue Val= combineStoreFPToInt(N, DCI);
14679       if (Val)
14680         return Val;
14681     }
14682 
14683     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14684       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14685       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14686       if (Val)
14687         return Val;
14688     }
14689 
14690     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14691     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14692         N->getOperand(1).getNode()->hasOneUse() &&
14693         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14694          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14695 
14696       // STBRX can only handle simple types and it makes no sense to store less
14697       // two bytes in byte-reversed order.
14698       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14699       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14700         break;
14701 
14702       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14703       // Do an any-extend to 32-bits if this is a half-word input.
14704       if (BSwapOp.getValueType() == MVT::i16)
14705         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14706 
14707       // If the type of BSWAP operand is wider than stored memory width
14708       // it need to be shifted to the right side before STBRX.
14709       if (Op1VT.bitsGT(mVT)) {
14710         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14711         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14712                               DAG.getConstant(Shift, dl, MVT::i32));
14713         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14714         if (Op1VT == MVT::i64)
14715           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14716       }
14717 
14718       SDValue Ops[] = {
14719         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14720       };
14721       return
14722         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14723                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14724                                 cast<StoreSDNode>(N)->getMemOperand());
14725     }
14726 
14727     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14728     // So it can increase the chance of CSE constant construction.
14729     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14730         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14731       // Need to sign-extended to 64-bits to handle negative values.
14732       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14733       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14734                                     MemVT.getSizeInBits());
14735       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14736 
14737       // DAG.getTruncStore() can't be used here because it doesn't accept
14738       // the general (base + offset) addressing mode.
14739       // So we use UpdateNodeOperands and setTruncatingStore instead.
14740       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14741                              N->getOperand(3));
14742       cast<StoreSDNode>(N)->setTruncatingStore(true);
14743       return SDValue(N, 0);
14744     }
14745 
14746     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14747     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14748     if (Op1VT.isSimple()) {
14749       MVT StoreVT = Op1VT.getSimpleVT();
14750       if (Subtarget.needsSwapsForVSXMemOps() &&
14751           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14752            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14753         return expandVSXStoreForLE(N, DCI);
14754     }
14755     break;
14756   }
14757   case ISD::LOAD: {
14758     LoadSDNode *LD = cast<LoadSDNode>(N);
14759     EVT VT = LD->getValueType(0);
14760 
14761     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14762     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14763     if (VT.isSimple()) {
14764       MVT LoadVT = VT.getSimpleVT();
14765       if (Subtarget.needsSwapsForVSXMemOps() &&
14766           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14767            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14768         return expandVSXLoadForLE(N, DCI);
14769     }
14770 
14771     // We sometimes end up with a 64-bit integer load, from which we extract
14772     // two single-precision floating-point numbers. This happens with
14773     // std::complex<float>, and other similar structures, because of the way we
14774     // canonicalize structure copies. However, if we lack direct moves,
14775     // then the final bitcasts from the extracted integer values to the
14776     // floating-point numbers turn into store/load pairs. Even with direct moves,
14777     // just loading the two floating-point numbers is likely better.
14778     auto ReplaceTwoFloatLoad = [&]() {
14779       if (VT != MVT::i64)
14780         return false;
14781 
14782       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14783           LD->isVolatile())
14784         return false;
14785 
14786       //  We're looking for a sequence like this:
14787       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14788       //      t16: i64 = srl t13, Constant:i32<32>
14789       //    t17: i32 = truncate t16
14790       //  t18: f32 = bitcast t17
14791       //    t19: i32 = truncate t13
14792       //  t20: f32 = bitcast t19
14793 
14794       if (!LD->hasNUsesOfValue(2, 0))
14795         return false;
14796 
14797       auto UI = LD->use_begin();
14798       while (UI.getUse().getResNo() != 0) ++UI;
14799       SDNode *Trunc = *UI++;
14800       while (UI.getUse().getResNo() != 0) ++UI;
14801       SDNode *RightShift = *UI;
14802       if (Trunc->getOpcode() != ISD::TRUNCATE)
14803         std::swap(Trunc, RightShift);
14804 
14805       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14806           Trunc->getValueType(0) != MVT::i32 ||
14807           !Trunc->hasOneUse())
14808         return false;
14809       if (RightShift->getOpcode() != ISD::SRL ||
14810           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14811           RightShift->getConstantOperandVal(1) != 32 ||
14812           !RightShift->hasOneUse())
14813         return false;
14814 
14815       SDNode *Trunc2 = *RightShift->use_begin();
14816       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14817           Trunc2->getValueType(0) != MVT::i32 ||
14818           !Trunc2->hasOneUse())
14819         return false;
14820 
14821       SDNode *Bitcast = *Trunc->use_begin();
14822       SDNode *Bitcast2 = *Trunc2->use_begin();
14823 
14824       if (Bitcast->getOpcode() != ISD::BITCAST ||
14825           Bitcast->getValueType(0) != MVT::f32)
14826         return false;
14827       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14828           Bitcast2->getValueType(0) != MVT::f32)
14829         return false;
14830 
14831       if (Subtarget.isLittleEndian())
14832         std::swap(Bitcast, Bitcast2);
14833 
14834       // Bitcast has the second float (in memory-layout order) and Bitcast2
14835       // has the first one.
14836 
14837       SDValue BasePtr = LD->getBasePtr();
14838       if (LD->isIndexed()) {
14839         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14840                "Non-pre-inc AM on PPC?");
14841         BasePtr =
14842           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14843                       LD->getOffset());
14844       }
14845 
14846       auto MMOFlags =
14847           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14848       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14849                                       LD->getPointerInfo(), LD->getAlignment(),
14850                                       MMOFlags, LD->getAAInfo());
14851       SDValue AddPtr =
14852         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14853                     BasePtr, DAG.getIntPtrConstant(4, dl));
14854       SDValue FloatLoad2 = DAG.getLoad(
14855           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14856           LD->getPointerInfo().getWithOffset(4),
14857           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14858 
14859       if (LD->isIndexed()) {
14860         // Note that DAGCombine should re-form any pre-increment load(s) from
14861         // what is produced here if that makes sense.
14862         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14863       }
14864 
14865       DCI.CombineTo(Bitcast2, FloatLoad);
14866       DCI.CombineTo(Bitcast, FloatLoad2);
14867 
14868       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14869                                     SDValue(FloatLoad2.getNode(), 1));
14870       return true;
14871     };
14872 
14873     if (ReplaceTwoFloatLoad())
14874       return SDValue(N, 0);
14875 
14876     EVT MemVT = LD->getMemoryVT();
14877     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14878     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14879     if (LD->isUnindexed() && VT.isVector() &&
14880         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14881           // P8 and later hardware should just use LOAD.
14882           !Subtarget.hasP8Vector() &&
14883           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14884            VT == MVT::v4f32))) &&
14885         LD->getAlign() < ABIAlignment) {
14886       // This is a type-legal unaligned Altivec load.
14887       SDValue Chain = LD->getChain();
14888       SDValue Ptr = LD->getBasePtr();
14889       bool isLittleEndian = Subtarget.isLittleEndian();
14890 
14891       // This implements the loading of unaligned vectors as described in
14892       // the venerable Apple Velocity Engine overview. Specifically:
14893       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14894       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14895       //
14896       // The general idea is to expand a sequence of one or more unaligned
14897       // loads into an alignment-based permutation-control instruction (lvsl
14898       // or lvsr), a series of regular vector loads (which always truncate
14899       // their input address to an aligned address), and a series of
14900       // permutations.  The results of these permutations are the requested
14901       // loaded values.  The trick is that the last "extra" load is not taken
14902       // from the address you might suspect (sizeof(vector) bytes after the
14903       // last requested load), but rather sizeof(vector) - 1 bytes after the
14904       // last requested vector. The point of this is to avoid a page fault if
14905       // the base address happened to be aligned. This works because if the
14906       // base address is aligned, then adding less than a full vector length
14907       // will cause the last vector in the sequence to be (re)loaded.
14908       // Otherwise, the next vector will be fetched as you might suspect was
14909       // necessary.
14910 
14911       // We might be able to reuse the permutation generation from
14912       // a different base address offset from this one by an aligned amount.
14913       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14914       // optimization later.
14915       Intrinsic::ID Intr, IntrLD, IntrPerm;
14916       MVT PermCntlTy, PermTy, LDTy;
14917       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14918                             : Intrinsic::ppc_altivec_lvsl;
14919       IntrLD = Intrinsic::ppc_altivec_lvx;
14920       IntrPerm = Intrinsic::ppc_altivec_vperm;
14921       PermCntlTy = MVT::v16i8;
14922       PermTy = MVT::v4i32;
14923       LDTy = MVT::v4i32;
14924 
14925       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14926 
14927       // Create the new MMO for the new base load. It is like the original MMO,
14928       // but represents an area in memory almost twice the vector size centered
14929       // on the original address. If the address is unaligned, we might start
14930       // reading up to (sizeof(vector)-1) bytes below the address of the
14931       // original unaligned load.
14932       MachineFunction &MF = DAG.getMachineFunction();
14933       MachineMemOperand *BaseMMO =
14934         MF.getMachineMemOperand(LD->getMemOperand(),
14935                                 -(long)MemVT.getStoreSize()+1,
14936                                 2*MemVT.getStoreSize()-1);
14937 
14938       // Create the new base load.
14939       SDValue LDXIntID =
14940           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14941       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14942       SDValue BaseLoad =
14943         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14944                                 DAG.getVTList(PermTy, MVT::Other),
14945                                 BaseLoadOps, LDTy, BaseMMO);
14946 
14947       // Note that the value of IncOffset (which is provided to the next
14948       // load's pointer info offset value, and thus used to calculate the
14949       // alignment), and the value of IncValue (which is actually used to
14950       // increment the pointer value) are different! This is because we
14951       // require the next load to appear to be aligned, even though it
14952       // is actually offset from the base pointer by a lesser amount.
14953       int IncOffset = VT.getSizeInBits() / 8;
14954       int IncValue = IncOffset;
14955 
14956       // Walk (both up and down) the chain looking for another load at the real
14957       // (aligned) offset (the alignment of the other load does not matter in
14958       // this case). If found, then do not use the offset reduction trick, as
14959       // that will prevent the loads from being later combined (as they would
14960       // otherwise be duplicates).
14961       if (!findConsecutiveLoad(LD, DAG))
14962         --IncValue;
14963 
14964       SDValue Increment =
14965           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14966       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14967 
14968       MachineMemOperand *ExtraMMO =
14969         MF.getMachineMemOperand(LD->getMemOperand(),
14970                                 1, 2*MemVT.getStoreSize()-1);
14971       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14972       SDValue ExtraLoad =
14973         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14974                                 DAG.getVTList(PermTy, MVT::Other),
14975                                 ExtraLoadOps, LDTy, ExtraMMO);
14976 
14977       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14978         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14979 
14980       // Because vperm has a big-endian bias, we must reverse the order
14981       // of the input vectors and complement the permute control vector
14982       // when generating little endian code.  We have already handled the
14983       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14984       // and ExtraLoad here.
14985       SDValue Perm;
14986       if (isLittleEndian)
14987         Perm = BuildIntrinsicOp(IntrPerm,
14988                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14989       else
14990         Perm = BuildIntrinsicOp(IntrPerm,
14991                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14992 
14993       if (VT != PermTy)
14994         Perm = Subtarget.hasAltivec()
14995                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14996                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14997                                  DAG.getTargetConstant(1, dl, MVT::i64));
14998                                // second argument is 1 because this rounding
14999                                // is always exact.
15000 
15001       // The output of the permutation is our loaded result, the TokenFactor is
15002       // our new chain.
15003       DCI.CombineTo(N, Perm, TF);
15004       return SDValue(N, 0);
15005     }
15006     }
15007     break;
15008     case ISD::INTRINSIC_WO_CHAIN: {
15009       bool isLittleEndian = Subtarget.isLittleEndian();
15010       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15011       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15012                                            : Intrinsic::ppc_altivec_lvsl);
15013       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15014         SDValue Add = N->getOperand(1);
15015 
15016         int Bits = 4 /* 16 byte alignment */;
15017 
15018         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15019                                   APInt::getAllOnesValue(Bits /* alignment */)
15020                                       .zext(Add.getScalarValueSizeInBits()))) {
15021           SDNode *BasePtr = Add->getOperand(0).getNode();
15022           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15023                                     UE = BasePtr->use_end();
15024                UI != UE; ++UI) {
15025             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15026                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
15027                     IID) {
15028               // We've found another LVSL/LVSR, and this address is an aligned
15029               // multiple of that one. The results will be the same, so use the
15030               // one we've just found instead.
15031 
15032               return SDValue(*UI, 0);
15033             }
15034           }
15035         }
15036 
15037         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15038           SDNode *BasePtr = Add->getOperand(0).getNode();
15039           for (SDNode::use_iterator UI = BasePtr->use_begin(),
15040                UE = BasePtr->use_end(); UI != UE; ++UI) {
15041             if (UI->getOpcode() == ISD::ADD &&
15042                 isa<ConstantSDNode>(UI->getOperand(1)) &&
15043                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15044                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
15045                 (1ULL << Bits) == 0) {
15046               SDNode *OtherAdd = *UI;
15047               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
15048                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
15049                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15050                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
15051                   return SDValue(*VI, 0);
15052                 }
15053               }
15054             }
15055           }
15056         }
15057       }
15058 
15059       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15060       // Expose the vabsduw/h/b opportunity for down stream
15061       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15062           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15063            IID == Intrinsic::ppc_altivec_vmaxsh ||
15064            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15065         SDValue V1 = N->getOperand(1);
15066         SDValue V2 = N->getOperand(2);
15067         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15068              V1.getSimpleValueType() == MVT::v8i16 ||
15069              V1.getSimpleValueType() == MVT::v16i8) &&
15070             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15071           // (0-a, a)
15072           if (V1.getOpcode() == ISD::SUB &&
15073               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15074               V1.getOperand(1) == V2) {
15075             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15076           }
15077           // (a, 0-a)
15078           if (V2.getOpcode() == ISD::SUB &&
15079               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15080               V2.getOperand(1) == V1) {
15081             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15082           }
15083           // (x-y, y-x)
15084           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15085               V1.getOperand(0) == V2.getOperand(1) &&
15086               V1.getOperand(1) == V2.getOperand(0)) {
15087             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15088           }
15089         }
15090       }
15091     }
15092 
15093     break;
15094   case ISD::INTRINSIC_W_CHAIN:
15095     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15096     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15097     if (Subtarget.needsSwapsForVSXMemOps()) {
15098       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15099       default:
15100         break;
15101       case Intrinsic::ppc_vsx_lxvw4x:
15102       case Intrinsic::ppc_vsx_lxvd2x:
15103         return expandVSXLoadForLE(N, DCI);
15104       }
15105     }
15106     break;
15107   case ISD::INTRINSIC_VOID:
15108     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15109     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15110     if (Subtarget.needsSwapsForVSXMemOps()) {
15111       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15112       default:
15113         break;
15114       case Intrinsic::ppc_vsx_stxvw4x:
15115       case Intrinsic::ppc_vsx_stxvd2x:
15116         return expandVSXStoreForLE(N, DCI);
15117       }
15118     }
15119     break;
15120   case ISD::BSWAP:
15121     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15122     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
15123         N->getOperand(0).hasOneUse() &&
15124         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15125          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
15126           N->getValueType(0) == MVT::i64))) {
15127       SDValue Load = N->getOperand(0);
15128       LoadSDNode *LD = cast<LoadSDNode>(Load);
15129       // Create the byte-swapping load.
15130       SDValue Ops[] = {
15131         LD->getChain(),    // Chain
15132         LD->getBasePtr(),  // Ptr
15133         DAG.getValueType(N->getValueType(0)) // VT
15134       };
15135       SDValue BSLoad =
15136         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15137                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15138                                               MVT::i64 : MVT::i32, MVT::Other),
15139                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15140 
15141       // If this is an i16 load, insert the truncate.
15142       SDValue ResVal = BSLoad;
15143       if (N->getValueType(0) == MVT::i16)
15144         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15145 
15146       // First, combine the bswap away.  This makes the value produced by the
15147       // load dead.
15148       DCI.CombineTo(N, ResVal);
15149 
15150       // Next, combine the load away, we give it a bogus result value but a real
15151       // chain result.  The result value is dead because the bswap is dead.
15152       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15153 
15154       // Return N so it doesn't get rechecked!
15155       return SDValue(N, 0);
15156     }
15157     break;
15158   case PPCISD::VCMP:
15159     // If a VCMPo node already exists with exactly the same operands as this
15160     // node, use its result instead of this node (VCMPo computes both a CR6 and
15161     // a normal output).
15162     //
15163     if (!N->getOperand(0).hasOneUse() &&
15164         !N->getOperand(1).hasOneUse() &&
15165         !N->getOperand(2).hasOneUse()) {
15166 
15167       // Scan all of the users of the LHS, looking for VCMPo's that match.
15168       SDNode *VCMPoNode = nullptr;
15169 
15170       SDNode *LHSN = N->getOperand(0).getNode();
15171       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15172            UI != E; ++UI)
15173         if (UI->getOpcode() == PPCISD::VCMPo &&
15174             UI->getOperand(1) == N->getOperand(1) &&
15175             UI->getOperand(2) == N->getOperand(2) &&
15176             UI->getOperand(0) == N->getOperand(0)) {
15177           VCMPoNode = *UI;
15178           break;
15179         }
15180 
15181       // If there is no VCMPo node, or if the flag value has a single use, don't
15182       // transform this.
15183       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
15184         break;
15185 
15186       // Look at the (necessarily single) use of the flag value.  If it has a
15187       // chain, this transformation is more complex.  Note that multiple things
15188       // could use the value result, which we should ignore.
15189       SDNode *FlagUser = nullptr;
15190       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
15191            FlagUser == nullptr; ++UI) {
15192         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
15193         SDNode *User = *UI;
15194         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15195           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
15196             FlagUser = User;
15197             break;
15198           }
15199         }
15200       }
15201 
15202       // If the user is a MFOCRF instruction, we know this is safe.
15203       // Otherwise we give up for right now.
15204       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15205         return SDValue(VCMPoNode, 0);
15206     }
15207     break;
15208   case ISD::BRCOND: {
15209     SDValue Cond = N->getOperand(1);
15210     SDValue Target = N->getOperand(2);
15211 
15212     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15213         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15214           Intrinsic::loop_decrement) {
15215 
15216       // We now need to make the intrinsic dead (it cannot be instruction
15217       // selected).
15218       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15219       assert(Cond.getNode()->hasOneUse() &&
15220              "Counter decrement has more than one use");
15221 
15222       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15223                          N->getOperand(0), Target);
15224     }
15225   }
15226   break;
15227   case ISD::BR_CC: {
15228     // If this is a branch on an altivec predicate comparison, lower this so
15229     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15230     // lowering is done pre-legalize, because the legalizer lowers the predicate
15231     // compare down to code that is difficult to reassemble.
15232     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15233     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15234 
15235     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15236     // value. If so, pass-through the AND to get to the intrinsic.
15237     if (LHS.getOpcode() == ISD::AND &&
15238         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15239         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15240           Intrinsic::loop_decrement &&
15241         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15242         !isNullConstant(LHS.getOperand(1)))
15243       LHS = LHS.getOperand(0);
15244 
15245     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15246         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15247           Intrinsic::loop_decrement &&
15248         isa<ConstantSDNode>(RHS)) {
15249       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15250              "Counter decrement comparison is not EQ or NE");
15251 
15252       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15253       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15254                     (CC == ISD::SETNE && !Val);
15255 
15256       // We now need to make the intrinsic dead (it cannot be instruction
15257       // selected).
15258       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15259       assert(LHS.getNode()->hasOneUse() &&
15260              "Counter decrement has more than one use");
15261 
15262       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15263                          N->getOperand(0), N->getOperand(4));
15264     }
15265 
15266     int CompareOpc;
15267     bool isDot;
15268 
15269     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15270         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15271         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15272       assert(isDot && "Can't compare against a vector result!");
15273 
15274       // If this is a comparison against something other than 0/1, then we know
15275       // that the condition is never/always true.
15276       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15277       if (Val != 0 && Val != 1) {
15278         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15279           return N->getOperand(0);
15280         // Always !=, turn it into an unconditional branch.
15281         return DAG.getNode(ISD::BR, dl, MVT::Other,
15282                            N->getOperand(0), N->getOperand(4));
15283       }
15284 
15285       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15286 
15287       // Create the PPCISD altivec 'dot' comparison node.
15288       SDValue Ops[] = {
15289         LHS.getOperand(2),  // LHS of compare
15290         LHS.getOperand(3),  // RHS of compare
15291         DAG.getConstant(CompareOpc, dl, MVT::i32)
15292       };
15293       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15294       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
15295 
15296       // Unpack the result based on how the target uses it.
15297       PPC::Predicate CompOpc;
15298       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15299       default:  // Can't happen, don't crash on invalid number though.
15300       case 0:   // Branch on the value of the EQ bit of CR6.
15301         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15302         break;
15303       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15304         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15305         break;
15306       case 2:   // Branch on the value of the LT bit of CR6.
15307         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15308         break;
15309       case 3:   // Branch on the inverted value of the LT bit of CR6.
15310         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15311         break;
15312       }
15313 
15314       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15315                          DAG.getConstant(CompOpc, dl, MVT::i32),
15316                          DAG.getRegister(PPC::CR6, MVT::i32),
15317                          N->getOperand(4), CompNode.getValue(1));
15318     }
15319     break;
15320   }
15321   case ISD::BUILD_VECTOR:
15322     return DAGCombineBuildVector(N, DCI);
15323   case ISD::ABS:
15324     return combineABS(N, DCI);
15325   case ISD::VSELECT:
15326     return combineVSelect(N, DCI);
15327   }
15328 
15329   return SDValue();
15330 }
15331 
15332 SDValue
15333 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15334                                  SelectionDAG &DAG,
15335                                  SmallVectorImpl<SDNode *> &Created) const {
15336   // fold (sdiv X, pow2)
15337   EVT VT = N->getValueType(0);
15338   if (VT == MVT::i64 && !Subtarget.isPPC64())
15339     return SDValue();
15340   if ((VT != MVT::i32 && VT != MVT::i64) ||
15341       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15342     return SDValue();
15343 
15344   SDLoc DL(N);
15345   SDValue N0 = N->getOperand(0);
15346 
15347   bool IsNegPow2 = (-Divisor).isPowerOf2();
15348   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15349   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15350 
15351   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15352   Created.push_back(Op.getNode());
15353 
15354   if (IsNegPow2) {
15355     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15356     Created.push_back(Op.getNode());
15357   }
15358 
15359   return Op;
15360 }
15361 
15362 //===----------------------------------------------------------------------===//
15363 // Inline Assembly Support
15364 //===----------------------------------------------------------------------===//
15365 
15366 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15367                                                       KnownBits &Known,
15368                                                       const APInt &DemandedElts,
15369                                                       const SelectionDAG &DAG,
15370                                                       unsigned Depth) const {
15371   Known.resetAll();
15372   switch (Op.getOpcode()) {
15373   default: break;
15374   case PPCISD::LBRX: {
15375     // lhbrx is known to have the top bits cleared out.
15376     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15377       Known.Zero = 0xFFFF0000;
15378     break;
15379   }
15380   case ISD::INTRINSIC_WO_CHAIN: {
15381     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15382     default: break;
15383     case Intrinsic::ppc_altivec_vcmpbfp_p:
15384     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15385     case Intrinsic::ppc_altivec_vcmpequb_p:
15386     case Intrinsic::ppc_altivec_vcmpequh_p:
15387     case Intrinsic::ppc_altivec_vcmpequw_p:
15388     case Intrinsic::ppc_altivec_vcmpequd_p:
15389     case Intrinsic::ppc_altivec_vcmpequq_p:
15390     case Intrinsic::ppc_altivec_vcmpgefp_p:
15391     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15392     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15393     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15394     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15395     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15396     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15397     case Intrinsic::ppc_altivec_vcmpgtub_p:
15398     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15399     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15400     case Intrinsic::ppc_altivec_vcmpgtud_p:
15401     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15402       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15403       break;
15404     }
15405   }
15406   }
15407 }
15408 
15409 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15410   switch (Subtarget.getCPUDirective()) {
15411   default: break;
15412   case PPC::DIR_970:
15413   case PPC::DIR_PWR4:
15414   case PPC::DIR_PWR5:
15415   case PPC::DIR_PWR5X:
15416   case PPC::DIR_PWR6:
15417   case PPC::DIR_PWR6X:
15418   case PPC::DIR_PWR7:
15419   case PPC::DIR_PWR8:
15420   case PPC::DIR_PWR9:
15421   case PPC::DIR_PWR10:
15422   case PPC::DIR_PWR_FUTURE: {
15423     if (!ML)
15424       break;
15425 
15426     if (!DisableInnermostLoopAlign32) {
15427       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15428       // so that we can decrease cache misses and branch-prediction misses.
15429       // Actual alignment of the loop will depend on the hotness check and other
15430       // logic in alignBlocks.
15431       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15432         return Align(32);
15433     }
15434 
15435     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15436 
15437     // For small loops (between 5 and 8 instructions), align to a 32-byte
15438     // boundary so that the entire loop fits in one instruction-cache line.
15439     uint64_t LoopSize = 0;
15440     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15441       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15442         LoopSize += TII->getInstSizeInBytes(*J);
15443         if (LoopSize > 32)
15444           break;
15445       }
15446 
15447     if (LoopSize > 16 && LoopSize <= 32)
15448       return Align(32);
15449 
15450     break;
15451   }
15452   }
15453 
15454   return TargetLowering::getPrefLoopAlignment(ML);
15455 }
15456 
15457 /// getConstraintType - Given a constraint, return the type of
15458 /// constraint it is for this target.
15459 PPCTargetLowering::ConstraintType
15460 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15461   if (Constraint.size() == 1) {
15462     switch (Constraint[0]) {
15463     default: break;
15464     case 'b':
15465     case 'r':
15466     case 'f':
15467     case 'd':
15468     case 'v':
15469     case 'y':
15470       return C_RegisterClass;
15471     case 'Z':
15472       // FIXME: While Z does indicate a memory constraint, it specifically
15473       // indicates an r+r address (used in conjunction with the 'y' modifier
15474       // in the replacement string). Currently, we're forcing the base
15475       // register to be r0 in the asm printer (which is interpreted as zero)
15476       // and forming the complete address in the second register. This is
15477       // suboptimal.
15478       return C_Memory;
15479     }
15480   } else if (Constraint == "wc") { // individual CR bits.
15481     return C_RegisterClass;
15482   } else if (Constraint == "wa" || Constraint == "wd" ||
15483              Constraint == "wf" || Constraint == "ws" ||
15484              Constraint == "wi" || Constraint == "ww") {
15485     return C_RegisterClass; // VSX registers.
15486   }
15487   return TargetLowering::getConstraintType(Constraint);
15488 }
15489 
15490 /// Examine constraint type and operand type and determine a weight value.
15491 /// This object must already have been set up with the operand type
15492 /// and the current alternative constraint selected.
15493 TargetLowering::ConstraintWeight
15494 PPCTargetLowering::getSingleConstraintMatchWeight(
15495     AsmOperandInfo &info, const char *constraint) const {
15496   ConstraintWeight weight = CW_Invalid;
15497   Value *CallOperandVal = info.CallOperandVal;
15498     // If we don't have a value, we can't do a match,
15499     // but allow it at the lowest weight.
15500   if (!CallOperandVal)
15501     return CW_Default;
15502   Type *type = CallOperandVal->getType();
15503 
15504   // Look at the constraint type.
15505   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15506     return CW_Register; // an individual CR bit.
15507   else if ((StringRef(constraint) == "wa" ||
15508             StringRef(constraint) == "wd" ||
15509             StringRef(constraint) == "wf") &&
15510            type->isVectorTy())
15511     return CW_Register;
15512   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15513     return CW_Register; // just hold 64-bit integers data.
15514   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15515     return CW_Register;
15516   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15517     return CW_Register;
15518 
15519   switch (*constraint) {
15520   default:
15521     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15522     break;
15523   case 'b':
15524     if (type->isIntegerTy())
15525       weight = CW_Register;
15526     break;
15527   case 'f':
15528     if (type->isFloatTy())
15529       weight = CW_Register;
15530     break;
15531   case 'd':
15532     if (type->isDoubleTy())
15533       weight = CW_Register;
15534     break;
15535   case 'v':
15536     if (type->isVectorTy())
15537       weight = CW_Register;
15538     break;
15539   case 'y':
15540     weight = CW_Register;
15541     break;
15542   case 'Z':
15543     weight = CW_Memory;
15544     break;
15545   }
15546   return weight;
15547 }
15548 
15549 std::pair<unsigned, const TargetRegisterClass *>
15550 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15551                                                 StringRef Constraint,
15552                                                 MVT VT) const {
15553   if (Constraint.size() == 1) {
15554     // GCC RS6000 Constraint Letters
15555     switch (Constraint[0]) {
15556     case 'b':   // R1-R31
15557       if (VT == MVT::i64 && Subtarget.isPPC64())
15558         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15559       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15560     case 'r':   // R0-R31
15561       if (VT == MVT::i64 && Subtarget.isPPC64())
15562         return std::make_pair(0U, &PPC::G8RCRegClass);
15563       return std::make_pair(0U, &PPC::GPRCRegClass);
15564     // 'd' and 'f' constraints are both defined to be "the floating point
15565     // registers", where one is for 32-bit and the other for 64-bit. We don't
15566     // really care overly much here so just give them all the same reg classes.
15567     case 'd':
15568     case 'f':
15569       if (Subtarget.hasSPE()) {
15570         if (VT == MVT::f32 || VT == MVT::i32)
15571           return std::make_pair(0U, &PPC::GPRCRegClass);
15572         if (VT == MVT::f64 || VT == MVT::i64)
15573           return std::make_pair(0U, &PPC::SPERCRegClass);
15574       } else {
15575         if (VT == MVT::f32 || VT == MVT::i32)
15576           return std::make_pair(0U, &PPC::F4RCRegClass);
15577         if (VT == MVT::f64 || VT == MVT::i64)
15578           return std::make_pair(0U, &PPC::F8RCRegClass);
15579       }
15580       break;
15581     case 'v':
15582       if (Subtarget.hasAltivec())
15583         return std::make_pair(0U, &PPC::VRRCRegClass);
15584       break;
15585     case 'y':   // crrc
15586       return std::make_pair(0U, &PPC::CRRCRegClass);
15587     }
15588   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15589     // An individual CR bit.
15590     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15591   } else if ((Constraint == "wa" || Constraint == "wd" ||
15592              Constraint == "wf" || Constraint == "wi") &&
15593              Subtarget.hasVSX()) {
15594     return std::make_pair(0U, &PPC::VSRCRegClass);
15595   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15596     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15597       return std::make_pair(0U, &PPC::VSSRCRegClass);
15598     else
15599       return std::make_pair(0U, &PPC::VSFRCRegClass);
15600   }
15601 
15602   // If we name a VSX register, we can't defer to the base class because it
15603   // will not recognize the correct register (their names will be VSL{0-31}
15604   // and V{0-31} so they won't match). So we match them here.
15605   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15606     int VSNum = atoi(Constraint.data() + 3);
15607     assert(VSNum >= 0 && VSNum <= 63 &&
15608            "Attempted to access a vsr out of range");
15609     if (VSNum < 32)
15610       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15611     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15612   }
15613   std::pair<unsigned, const TargetRegisterClass *> R =
15614       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15615 
15616   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15617   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15618   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15619   // register.
15620   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15621   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15622   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15623       PPC::GPRCRegClass.contains(R.first))
15624     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15625                             PPC::sub_32, &PPC::G8RCRegClass),
15626                           &PPC::G8RCRegClass);
15627 
15628   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15629   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15630     R.first = PPC::CR0;
15631     R.second = &PPC::CRRCRegClass;
15632   }
15633 
15634   return R;
15635 }
15636 
15637 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15638 /// vector.  If it is invalid, don't add anything to Ops.
15639 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15640                                                      std::string &Constraint,
15641                                                      std::vector<SDValue>&Ops,
15642                                                      SelectionDAG &DAG) const {
15643   SDValue Result;
15644 
15645   // Only support length 1 constraints.
15646   if (Constraint.length() > 1) return;
15647 
15648   char Letter = Constraint[0];
15649   switch (Letter) {
15650   default: break;
15651   case 'I':
15652   case 'J':
15653   case 'K':
15654   case 'L':
15655   case 'M':
15656   case 'N':
15657   case 'O':
15658   case 'P': {
15659     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15660     if (!CST) return; // Must be an immediate to match.
15661     SDLoc dl(Op);
15662     int64_t Value = CST->getSExtValue();
15663     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15664                          // numbers are printed as such.
15665     switch (Letter) {
15666     default: llvm_unreachable("Unknown constraint letter!");
15667     case 'I':  // "I" is a signed 16-bit constant.
15668       if (isInt<16>(Value))
15669         Result = DAG.getTargetConstant(Value, dl, TCVT);
15670       break;
15671     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15672       if (isShiftedUInt<16, 16>(Value))
15673         Result = DAG.getTargetConstant(Value, dl, TCVT);
15674       break;
15675     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15676       if (isShiftedInt<16, 16>(Value))
15677         Result = DAG.getTargetConstant(Value, dl, TCVT);
15678       break;
15679     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15680       if (isUInt<16>(Value))
15681         Result = DAG.getTargetConstant(Value, dl, TCVT);
15682       break;
15683     case 'M':  // "M" is a constant that is greater than 31.
15684       if (Value > 31)
15685         Result = DAG.getTargetConstant(Value, dl, TCVT);
15686       break;
15687     case 'N':  // "N" is a positive constant that is an exact power of two.
15688       if (Value > 0 && isPowerOf2_64(Value))
15689         Result = DAG.getTargetConstant(Value, dl, TCVT);
15690       break;
15691     case 'O':  // "O" is the constant zero.
15692       if (Value == 0)
15693         Result = DAG.getTargetConstant(Value, dl, TCVT);
15694       break;
15695     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15696       if (isInt<16>(-Value))
15697         Result = DAG.getTargetConstant(Value, dl, TCVT);
15698       break;
15699     }
15700     break;
15701   }
15702   }
15703 
15704   if (Result.getNode()) {
15705     Ops.push_back(Result);
15706     return;
15707   }
15708 
15709   // Handle standard constraint letters.
15710   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15711 }
15712 
15713 // isLegalAddressingMode - Return true if the addressing mode represented
15714 // by AM is legal for this target, for a load/store of the specified type.
15715 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15716                                               const AddrMode &AM, Type *Ty,
15717                                               unsigned AS,
15718                                               Instruction *I) const {
15719   // Vector type r+i form is supported since power9 as DQ form. We don't check
15720   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15721   // imm form is preferred and the offset can be adjusted to use imm form later
15722   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15723   // max offset to check legal addressing mode, we should be a little aggressive
15724   // to contain other offsets for that LSRUse.
15725   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15726     return false;
15727 
15728   // PPC allows a sign-extended 16-bit immediate field.
15729   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15730     return false;
15731 
15732   // No global is ever allowed as a base.
15733   if (AM.BaseGV)
15734     return false;
15735 
15736   // PPC only support r+r,
15737   switch (AM.Scale) {
15738   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15739     break;
15740   case 1:
15741     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15742       return false;
15743     // Otherwise we have r+r or r+i.
15744     break;
15745   case 2:
15746     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15747       return false;
15748     // Allow 2*r as r+r.
15749     break;
15750   default:
15751     // No other scales are supported.
15752     return false;
15753   }
15754 
15755   return true;
15756 }
15757 
15758 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15759                                            SelectionDAG &DAG) const {
15760   MachineFunction &MF = DAG.getMachineFunction();
15761   MachineFrameInfo &MFI = MF.getFrameInfo();
15762   MFI.setReturnAddressIsTaken(true);
15763 
15764   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15765     return SDValue();
15766 
15767   SDLoc dl(Op);
15768   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15769 
15770   // Make sure the function does not optimize away the store of the RA to
15771   // the stack.
15772   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15773   FuncInfo->setLRStoreRequired();
15774   bool isPPC64 = Subtarget.isPPC64();
15775   auto PtrVT = getPointerTy(MF.getDataLayout());
15776 
15777   if (Depth > 0) {
15778     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15779     SDValue Offset =
15780         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15781                         isPPC64 ? MVT::i64 : MVT::i32);
15782     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15783                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15784                        MachinePointerInfo());
15785   }
15786 
15787   // Just load the return address off the stack.
15788   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15789   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15790                      MachinePointerInfo());
15791 }
15792 
15793 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15794                                           SelectionDAG &DAG) const {
15795   SDLoc dl(Op);
15796   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15797 
15798   MachineFunction &MF = DAG.getMachineFunction();
15799   MachineFrameInfo &MFI = MF.getFrameInfo();
15800   MFI.setFrameAddressIsTaken(true);
15801 
15802   EVT PtrVT = getPointerTy(MF.getDataLayout());
15803   bool isPPC64 = PtrVT == MVT::i64;
15804 
15805   // Naked functions never have a frame pointer, and so we use r1. For all
15806   // other functions, this decision must be delayed until during PEI.
15807   unsigned FrameReg;
15808   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15809     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15810   else
15811     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15812 
15813   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15814                                          PtrVT);
15815   while (Depth--)
15816     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15817                             FrameAddr, MachinePointerInfo());
15818   return FrameAddr;
15819 }
15820 
15821 // FIXME? Maybe this could be a TableGen attribute on some registers and
15822 // this table could be generated automatically from RegInfo.
15823 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15824                                               const MachineFunction &MF) const {
15825   bool isPPC64 = Subtarget.isPPC64();
15826 
15827   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15828   if (!is64Bit && VT != LLT::scalar(32))
15829     report_fatal_error("Invalid register global variable type");
15830 
15831   Register Reg = StringSwitch<Register>(RegName)
15832                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15833                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15834                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15835                      .Default(Register());
15836 
15837   if (Reg)
15838     return Reg;
15839   report_fatal_error("Invalid register name global variable");
15840 }
15841 
15842 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15843   // 32-bit SVR4 ABI access everything as got-indirect.
15844   if (Subtarget.is32BitELFABI())
15845     return true;
15846 
15847   // AIX accesses everything indirectly through the TOC, which is similar to
15848   // the GOT.
15849   if (Subtarget.isAIXABI())
15850     return true;
15851 
15852   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15853   // If it is small or large code model, module locals are accessed
15854   // indirectly by loading their address from .toc/.got.
15855   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15856     return true;
15857 
15858   // JumpTable and BlockAddress are accessed as got-indirect.
15859   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15860     return true;
15861 
15862   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15863     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15864 
15865   return false;
15866 }
15867 
15868 bool
15869 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15870   // The PowerPC target isn't yet aware of offsets.
15871   return false;
15872 }
15873 
15874 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15875                                            const CallInst &I,
15876                                            MachineFunction &MF,
15877                                            unsigned Intrinsic) const {
15878   switch (Intrinsic) {
15879   case Intrinsic::ppc_altivec_lvx:
15880   case Intrinsic::ppc_altivec_lvxl:
15881   case Intrinsic::ppc_altivec_lvebx:
15882   case Intrinsic::ppc_altivec_lvehx:
15883   case Intrinsic::ppc_altivec_lvewx:
15884   case Intrinsic::ppc_vsx_lxvd2x:
15885   case Intrinsic::ppc_vsx_lxvw4x:
15886   case Intrinsic::ppc_vsx_lxvd2x_be:
15887   case Intrinsic::ppc_vsx_lxvw4x_be:
15888   case Intrinsic::ppc_vsx_lxvl:
15889   case Intrinsic::ppc_vsx_lxvll: {
15890     EVT VT;
15891     switch (Intrinsic) {
15892     case Intrinsic::ppc_altivec_lvebx:
15893       VT = MVT::i8;
15894       break;
15895     case Intrinsic::ppc_altivec_lvehx:
15896       VT = MVT::i16;
15897       break;
15898     case Intrinsic::ppc_altivec_lvewx:
15899       VT = MVT::i32;
15900       break;
15901     case Intrinsic::ppc_vsx_lxvd2x:
15902     case Intrinsic::ppc_vsx_lxvd2x_be:
15903       VT = MVT::v2f64;
15904       break;
15905     default:
15906       VT = MVT::v4i32;
15907       break;
15908     }
15909 
15910     Info.opc = ISD::INTRINSIC_W_CHAIN;
15911     Info.memVT = VT;
15912     Info.ptrVal = I.getArgOperand(0);
15913     Info.offset = -VT.getStoreSize()+1;
15914     Info.size = 2*VT.getStoreSize()-1;
15915     Info.align = Align(1);
15916     Info.flags = MachineMemOperand::MOLoad;
15917     return true;
15918   }
15919   case Intrinsic::ppc_altivec_stvx:
15920   case Intrinsic::ppc_altivec_stvxl:
15921   case Intrinsic::ppc_altivec_stvebx:
15922   case Intrinsic::ppc_altivec_stvehx:
15923   case Intrinsic::ppc_altivec_stvewx:
15924   case Intrinsic::ppc_vsx_stxvd2x:
15925   case Intrinsic::ppc_vsx_stxvw4x:
15926   case Intrinsic::ppc_vsx_stxvd2x_be:
15927   case Intrinsic::ppc_vsx_stxvw4x_be:
15928   case Intrinsic::ppc_vsx_stxvl:
15929   case Intrinsic::ppc_vsx_stxvll: {
15930     EVT VT;
15931     switch (Intrinsic) {
15932     case Intrinsic::ppc_altivec_stvebx:
15933       VT = MVT::i8;
15934       break;
15935     case Intrinsic::ppc_altivec_stvehx:
15936       VT = MVT::i16;
15937       break;
15938     case Intrinsic::ppc_altivec_stvewx:
15939       VT = MVT::i32;
15940       break;
15941     case Intrinsic::ppc_vsx_stxvd2x:
15942     case Intrinsic::ppc_vsx_stxvd2x_be:
15943       VT = MVT::v2f64;
15944       break;
15945     default:
15946       VT = MVT::v4i32;
15947       break;
15948     }
15949 
15950     Info.opc = ISD::INTRINSIC_VOID;
15951     Info.memVT = VT;
15952     Info.ptrVal = I.getArgOperand(1);
15953     Info.offset = -VT.getStoreSize()+1;
15954     Info.size = 2*VT.getStoreSize()-1;
15955     Info.align = Align(1);
15956     Info.flags = MachineMemOperand::MOStore;
15957     return true;
15958   }
15959   default:
15960     break;
15961   }
15962 
15963   return false;
15964 }
15965 
15966 /// It returns EVT::Other if the type should be determined using generic
15967 /// target-independent logic.
15968 EVT PPCTargetLowering::getOptimalMemOpType(
15969     const MemOp &Op, const AttributeList &FuncAttributes) const {
15970   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15971     // We should use Altivec/VSX loads and stores when available. For unaligned
15972     // addresses, unaligned VSX loads are only fast starting with the P8.
15973     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15974         (Op.isAligned(Align(16)) ||
15975          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15976       return MVT::v4i32;
15977   }
15978 
15979   if (Subtarget.isPPC64()) {
15980     return MVT::i64;
15981   }
15982 
15983   return MVT::i32;
15984 }
15985 
15986 /// Returns true if it is beneficial to convert a load of a constant
15987 /// to just the constant itself.
15988 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15989                                                           Type *Ty) const {
15990   assert(Ty->isIntegerTy());
15991 
15992   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15993   return !(BitSize == 0 || BitSize > 64);
15994 }
15995 
15996 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15997   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15998     return false;
15999   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16000   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16001   return NumBits1 == 64 && NumBits2 == 32;
16002 }
16003 
16004 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16005   if (!VT1.isInteger() || !VT2.isInteger())
16006     return false;
16007   unsigned NumBits1 = VT1.getSizeInBits();
16008   unsigned NumBits2 = VT2.getSizeInBits();
16009   return NumBits1 == 64 && NumBits2 == 32;
16010 }
16011 
16012 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16013   // Generally speaking, zexts are not free, but they are free when they can be
16014   // folded with other operations.
16015   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16016     EVT MemVT = LD->getMemoryVT();
16017     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16018          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16019         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16020          LD->getExtensionType() == ISD::ZEXTLOAD))
16021       return true;
16022   }
16023 
16024   // FIXME: Add other cases...
16025   //  - 32-bit shifts with a zext to i64
16026   //  - zext after ctlz, bswap, etc.
16027   //  - zext after and by a constant mask
16028 
16029   return TargetLowering::isZExtFree(Val, VT2);
16030 }
16031 
16032 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16033   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16034          "invalid fpext types");
16035   // Extending to float128 is not free.
16036   if (DestVT == MVT::f128)
16037     return false;
16038   return true;
16039 }
16040 
16041 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16042   return isInt<16>(Imm) || isUInt<16>(Imm);
16043 }
16044 
16045 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16046   return isInt<16>(Imm) || isUInt<16>(Imm);
16047 }
16048 
16049 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
16050                                                        unsigned,
16051                                                        unsigned,
16052                                                        MachineMemOperand::Flags,
16053                                                        bool *Fast) const {
16054   if (DisablePPCUnaligned)
16055     return false;
16056 
16057   // PowerPC supports unaligned memory access for simple non-vector types.
16058   // Although accessing unaligned addresses is not as efficient as accessing
16059   // aligned addresses, it is generally more efficient than manual expansion,
16060   // and generally only traps for software emulation when crossing page
16061   // boundaries.
16062 
16063   if (!VT.isSimple())
16064     return false;
16065 
16066   if (VT.isFloatingPoint() && !VT.isVector() &&
16067       !Subtarget.allowsUnalignedFPAccess())
16068     return false;
16069 
16070   if (VT.getSimpleVT().isVector()) {
16071     if (Subtarget.hasVSX()) {
16072       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16073           VT != MVT::v4f32 && VT != MVT::v4i32)
16074         return false;
16075     } else {
16076       return false;
16077     }
16078   }
16079 
16080   if (VT == MVT::ppcf128)
16081     return false;
16082 
16083   if (Fast)
16084     *Fast = true;
16085 
16086   return true;
16087 }
16088 
16089 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16090                                                SDValue C) const {
16091   // Check integral scalar types.
16092   if (!VT.isScalarInteger())
16093     return false;
16094   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16095     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16096       return false;
16097     // This transformation will generate >= 2 operations. But the following
16098     // cases will generate <= 2 instructions during ISEL. So exclude them.
16099     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16100     // HW instruction, ie. MULLI
16101     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16102     // instruction is needed than case 1, ie. MULLI and RLDICR
16103     int64_t Imm = ConstNode->getSExtValue();
16104     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16105     Imm >>= Shift;
16106     if (isInt<16>(Imm))
16107       return false;
16108     uint64_t UImm = static_cast<uint64_t>(Imm);
16109     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16110         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16111       return true;
16112   }
16113   return false;
16114 }
16115 
16116 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16117                                                    EVT VT) const {
16118   return isFMAFasterThanFMulAndFAdd(
16119       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16120 }
16121 
16122 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16123                                                    Type *Ty) const {
16124   switch (Ty->getScalarType()->getTypeID()) {
16125   case Type::FloatTyID:
16126   case Type::DoubleTyID:
16127     return true;
16128   case Type::FP128TyID:
16129     return Subtarget.hasP9Vector();
16130   default:
16131     return false;
16132   }
16133 }
16134 
16135 // FIXME: add more patterns which are not profitable to hoist.
16136 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16137   if (!I->hasOneUse())
16138     return true;
16139 
16140   Instruction *User = I->user_back();
16141   assert(User && "A single use instruction with no uses.");
16142 
16143   switch (I->getOpcode()) {
16144   case Instruction::FMul: {
16145     // Don't break FMA, PowerPC prefers FMA.
16146     if (User->getOpcode() != Instruction::FSub &&
16147         User->getOpcode() != Instruction::FAdd)
16148       return true;
16149 
16150     const TargetOptions &Options = getTargetMachine().Options;
16151     const Function *F = I->getFunction();
16152     const DataLayout &DL = F->getParent()->getDataLayout();
16153     Type *Ty = User->getOperand(0)->getType();
16154 
16155     return !(
16156         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16157         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16158         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16159   }
16160   case Instruction::Load: {
16161     // Don't break "store (load float*)" pattern, this pattern will be combined
16162     // to "store (load int32)" in later InstCombine pass. See function
16163     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16164     // cycles than loading a 32 bit integer.
16165     LoadInst *LI = cast<LoadInst>(I);
16166     // For the loads that combineLoadToOperationType does nothing, like
16167     // ordered load, it should be profitable to hoist them.
16168     // For swifterror load, it can only be used for pointer to pointer type, so
16169     // later type check should get rid of this case.
16170     if (!LI->isUnordered())
16171       return true;
16172 
16173     if (User->getOpcode() != Instruction::Store)
16174       return true;
16175 
16176     if (I->getType()->getTypeID() != Type::FloatTyID)
16177       return true;
16178 
16179     return false;
16180   }
16181   default:
16182     return true;
16183   }
16184   return true;
16185 }
16186 
16187 const MCPhysReg *
16188 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16189   // LR is a callee-save register, but we must treat it as clobbered by any call
16190   // site. Hence we include LR in the scratch registers, which are in turn added
16191   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16192   // to CTR, which is used by any indirect call.
16193   static const MCPhysReg ScratchRegs[] = {
16194     PPC::X12, PPC::LR8, PPC::CTR8, 0
16195   };
16196 
16197   return ScratchRegs;
16198 }
16199 
16200 Register PPCTargetLowering::getExceptionPointerRegister(
16201     const Constant *PersonalityFn) const {
16202   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16203 }
16204 
16205 Register PPCTargetLowering::getExceptionSelectorRegister(
16206     const Constant *PersonalityFn) const {
16207   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16208 }
16209 
16210 bool
16211 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16212                      EVT VT , unsigned DefinedValues) const {
16213   if (VT == MVT::v2i64)
16214     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16215 
16216   if (Subtarget.hasVSX())
16217     return true;
16218 
16219   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16220 }
16221 
16222 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16223   if (DisableILPPref || Subtarget.enableMachineScheduler())
16224     return TargetLowering::getSchedulingPreference(N);
16225 
16226   return Sched::ILP;
16227 }
16228 
16229 // Create a fast isel object.
16230 FastISel *
16231 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16232                                   const TargetLibraryInfo *LibInfo) const {
16233   return PPC::createFastISel(FuncInfo, LibInfo);
16234 }
16235 
16236 // 'Inverted' means the FMA opcode after negating one multiplicand.
16237 // For example, (fma -a b c) = (fnmsub a b c)
16238 static unsigned invertFMAOpcode(unsigned Opc) {
16239   switch (Opc) {
16240   default:
16241     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16242   case ISD::FMA:
16243     return PPCISD::FNMSUB;
16244   case PPCISD::FNMSUB:
16245     return ISD::FMA;
16246   }
16247 }
16248 
16249 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16250                                                 bool LegalOps, bool OptForSize,
16251                                                 NegatibleCost &Cost,
16252                                                 unsigned Depth) const {
16253   if (Depth > SelectionDAG::MaxRecursionDepth)
16254     return SDValue();
16255 
16256   unsigned Opc = Op.getOpcode();
16257   EVT VT = Op.getValueType();
16258   SDNodeFlags Flags = Op.getNode()->getFlags();
16259 
16260   switch (Opc) {
16261   case PPCISD::FNMSUB:
16262     if (!Op.hasOneUse() || !isTypeLegal(VT))
16263       break;
16264 
16265     const TargetOptions &Options = getTargetMachine().Options;
16266     SDValue N0 = Op.getOperand(0);
16267     SDValue N1 = Op.getOperand(1);
16268     SDValue N2 = Op.getOperand(2);
16269     SDLoc Loc(Op);
16270 
16271     NegatibleCost N2Cost = NegatibleCost::Expensive;
16272     SDValue NegN2 =
16273         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16274 
16275     if (!NegN2)
16276       return SDValue();
16277 
16278     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16279     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16280     // These transformations may change sign of zeroes. For example,
16281     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16282     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16283       // Try and choose the cheaper one to negate.
16284       NegatibleCost N0Cost = NegatibleCost::Expensive;
16285       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16286                                            N0Cost, Depth + 1);
16287 
16288       NegatibleCost N1Cost = NegatibleCost::Expensive;
16289       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16290                                            N1Cost, Depth + 1);
16291 
16292       if (NegN0 && N0Cost <= N1Cost) {
16293         Cost = std::min(N0Cost, N2Cost);
16294         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16295       } else if (NegN1) {
16296         Cost = std::min(N1Cost, N2Cost);
16297         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16298       }
16299     }
16300 
16301     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16302     if (isOperationLegal(ISD::FMA, VT)) {
16303       Cost = N2Cost;
16304       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16305     }
16306 
16307     break;
16308   }
16309 
16310   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16311                                               Cost, Depth);
16312 }
16313 
16314 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16315 bool PPCTargetLowering::useLoadStackGuardNode() const {
16316   if (!Subtarget.isTargetLinux())
16317     return TargetLowering::useLoadStackGuardNode();
16318   return true;
16319 }
16320 
16321 // Override to disable global variable loading on Linux.
16322 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16323   if (!Subtarget.isTargetLinux())
16324     return TargetLowering::insertSSPDeclarations(M);
16325 }
16326 
16327 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16328                                      bool ForCodeSize) const {
16329   if (!VT.isSimple() || !Subtarget.hasVSX())
16330     return false;
16331 
16332   switch(VT.getSimpleVT().SimpleTy) {
16333   default:
16334     // For FP types that are currently not supported by PPC backend, return
16335     // false. Examples: f16, f80.
16336     return false;
16337   case MVT::f32:
16338   case MVT::f64:
16339     if (Subtarget.hasPrefixInstrs()) {
16340       // With prefixed instructions, we can materialize anything that can be
16341       // represented with a 32-bit immediate, not just positive zero.
16342       APFloat APFloatOfImm = Imm;
16343       return convertToNonDenormSingle(APFloatOfImm);
16344     }
16345     LLVM_FALLTHROUGH;
16346   case MVT::ppcf128:
16347     return Imm.isPosZero();
16348   }
16349 }
16350 
16351 // For vector shift operation op, fold
16352 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16353 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16354                                   SelectionDAG &DAG) {
16355   SDValue N0 = N->getOperand(0);
16356   SDValue N1 = N->getOperand(1);
16357   EVT VT = N0.getValueType();
16358   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16359   unsigned Opcode = N->getOpcode();
16360   unsigned TargetOpcode;
16361 
16362   switch (Opcode) {
16363   default:
16364     llvm_unreachable("Unexpected shift operation");
16365   case ISD::SHL:
16366     TargetOpcode = PPCISD::SHL;
16367     break;
16368   case ISD::SRL:
16369     TargetOpcode = PPCISD::SRL;
16370     break;
16371   case ISD::SRA:
16372     TargetOpcode = PPCISD::SRA;
16373     break;
16374   }
16375 
16376   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16377       N1->getOpcode() == ISD::AND)
16378     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16379       if (Mask->getZExtValue() == OpSizeInBits - 1)
16380         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16381 
16382   return SDValue();
16383 }
16384 
16385 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16386   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16387     return Value;
16388 
16389   SDValue N0 = N->getOperand(0);
16390   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16391   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16392       N0.getOpcode() != ISD::SIGN_EXTEND ||
16393       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16394       N->getValueType(0) != MVT::i64)
16395     return SDValue();
16396 
16397   // We can't save an operation here if the value is already extended, and
16398   // the existing shift is easier to combine.
16399   SDValue ExtsSrc = N0.getOperand(0);
16400   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16401       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16402     return SDValue();
16403 
16404   SDLoc DL(N0);
16405   SDValue ShiftBy = SDValue(CN1, 0);
16406   // We want the shift amount to be i32 on the extswli, but the shift could
16407   // have an i64.
16408   if (ShiftBy.getValueType() == MVT::i64)
16409     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16410 
16411   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16412                          ShiftBy);
16413 }
16414 
16415 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16416   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16417     return Value;
16418 
16419   return SDValue();
16420 }
16421 
16422 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16423   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16424     return Value;
16425 
16426   return SDValue();
16427 }
16428 
16429 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16430 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16431 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16432 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16433 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16434                                  const PPCSubtarget &Subtarget) {
16435   if (!Subtarget.isPPC64())
16436     return SDValue();
16437 
16438   SDValue LHS = N->getOperand(0);
16439   SDValue RHS = N->getOperand(1);
16440 
16441   auto isZextOfCompareWithConstant = [](SDValue Op) {
16442     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16443         Op.getValueType() != MVT::i64)
16444       return false;
16445 
16446     SDValue Cmp = Op.getOperand(0);
16447     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16448         Cmp.getOperand(0).getValueType() != MVT::i64)
16449       return false;
16450 
16451     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16452       int64_t NegConstant = 0 - Constant->getSExtValue();
16453       // Due to the limitations of the addi instruction,
16454       // -C is required to be [-32768, 32767].
16455       return isInt<16>(NegConstant);
16456     }
16457 
16458     return false;
16459   };
16460 
16461   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16462   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16463 
16464   // If there is a pattern, canonicalize a zext operand to the RHS.
16465   if (LHSHasPattern && !RHSHasPattern)
16466     std::swap(LHS, RHS);
16467   else if (!LHSHasPattern && !RHSHasPattern)
16468     return SDValue();
16469 
16470   SDLoc DL(N);
16471   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16472   SDValue Cmp = RHS.getOperand(0);
16473   SDValue Z = Cmp.getOperand(0);
16474   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16475 
16476   assert(Constant && "Constant Should not be a null pointer.");
16477   int64_t NegConstant = 0 - Constant->getSExtValue();
16478 
16479   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16480   default: break;
16481   case ISD::SETNE: {
16482     //                                 when C == 0
16483     //                             --> addze X, (addic Z, -1).carry
16484     //                            /
16485     // add X, (zext(setne Z, C))--
16486     //                            \    when -32768 <= -C <= 32767 && C != 0
16487     //                             --> addze X, (addic (addi Z, -C), -1).carry
16488     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16489                               DAG.getConstant(NegConstant, DL, MVT::i64));
16490     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16491     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16492                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16493     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16494                        SDValue(Addc.getNode(), 1));
16495     }
16496   case ISD::SETEQ: {
16497     //                                 when C == 0
16498     //                             --> addze X, (subfic Z, 0).carry
16499     //                            /
16500     // add X, (zext(sete  Z, C))--
16501     //                            \    when -32768 <= -C <= 32767 && C != 0
16502     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16503     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16504                               DAG.getConstant(NegConstant, DL, MVT::i64));
16505     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16506     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16507                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16508     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16509                        SDValue(Subc.getNode(), 1));
16510     }
16511   }
16512 
16513   return SDValue();
16514 }
16515 
16516 // Transform
16517 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16518 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16519 // In this case both C1 and C2 must be known constants.
16520 // C1+C2 must fit into a 34 bit signed integer.
16521 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16522                                           const PPCSubtarget &Subtarget) {
16523   if (!Subtarget.isUsingPCRelativeCalls())
16524     return SDValue();
16525 
16526   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16527   // If we find that node try to cast the Global Address and the Constant.
16528   SDValue LHS = N->getOperand(0);
16529   SDValue RHS = N->getOperand(1);
16530 
16531   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16532     std::swap(LHS, RHS);
16533 
16534   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16535     return SDValue();
16536 
16537   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16538   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16539   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16540 
16541   // Check that both casts succeeded.
16542   if (!GSDN || !ConstNode)
16543     return SDValue();
16544 
16545   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16546   SDLoc DL(GSDN);
16547 
16548   // The signed int offset needs to fit in 34 bits.
16549   if (!isInt<34>(NewOffset))
16550     return SDValue();
16551 
16552   // The new global address is a copy of the old global address except
16553   // that it has the updated Offset.
16554   SDValue GA =
16555       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16556                                  NewOffset, GSDN->getTargetFlags());
16557   SDValue MatPCRel =
16558       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16559   return MatPCRel;
16560 }
16561 
16562 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16563   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16564     return Value;
16565 
16566   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16567     return Value;
16568 
16569   return SDValue();
16570 }
16571 
16572 // Detect TRUNCATE operations on bitcasts of float128 values.
16573 // What we are looking for here is the situtation where we extract a subset
16574 // of bits from a 128 bit float.
16575 // This can be of two forms:
16576 // 1) BITCAST of f128 feeding TRUNCATE
16577 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16578 // The reason this is required is because we do not have a legal i128 type
16579 // and so we want to prevent having to store the f128 and then reload part
16580 // of it.
16581 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16582                                            DAGCombinerInfo &DCI) const {
16583   // If we are using CRBits then try that first.
16584   if (Subtarget.useCRBits()) {
16585     // Check if CRBits did anything and return that if it did.
16586     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16587       return CRTruncValue;
16588   }
16589 
16590   SDLoc dl(N);
16591   SDValue Op0 = N->getOperand(0);
16592 
16593   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16594   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16595     EVT VT = N->getValueType(0);
16596     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16597       return SDValue();
16598     SDValue Sub = Op0.getOperand(0);
16599     if (Sub.getOpcode() == ISD::SUB) {
16600       SDValue SubOp0 = Sub.getOperand(0);
16601       SDValue SubOp1 = Sub.getOperand(1);
16602       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16603           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16604         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16605                                SubOp1.getOperand(0),
16606                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16607       }
16608     }
16609   }
16610 
16611   // Looking for a truncate of i128 to i64.
16612   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16613     return SDValue();
16614 
16615   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16616 
16617   // SRL feeding TRUNCATE.
16618   if (Op0.getOpcode() == ISD::SRL) {
16619     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16620     // The right shift has to be by 64 bits.
16621     if (!ConstNode || ConstNode->getZExtValue() != 64)
16622       return SDValue();
16623 
16624     // Switch the element number to extract.
16625     EltToExtract = EltToExtract ? 0 : 1;
16626     // Update Op0 past the SRL.
16627     Op0 = Op0.getOperand(0);
16628   }
16629 
16630   // BITCAST feeding a TRUNCATE possibly via SRL.
16631   if (Op0.getOpcode() == ISD::BITCAST &&
16632       Op0.getValueType() == MVT::i128 &&
16633       Op0.getOperand(0).getValueType() == MVT::f128) {
16634     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16635     return DCI.DAG.getNode(
16636         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16637         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16638   }
16639   return SDValue();
16640 }
16641 
16642 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16643   SelectionDAG &DAG = DCI.DAG;
16644 
16645   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16646   if (!ConstOpOrElement)
16647     return SDValue();
16648 
16649   // An imul is usually smaller than the alternative sequence for legal type.
16650   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16651       isOperationLegal(ISD::MUL, N->getValueType(0)))
16652     return SDValue();
16653 
16654   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16655     switch (this->Subtarget.getCPUDirective()) {
16656     default:
16657       // TODO: enhance the condition for subtarget before pwr8
16658       return false;
16659     case PPC::DIR_PWR8:
16660       //  type        mul     add    shl
16661       // scalar        4       1      1
16662       // vector        7       2      2
16663       return true;
16664     case PPC::DIR_PWR9:
16665     case PPC::DIR_PWR10:
16666     case PPC::DIR_PWR_FUTURE:
16667       //  type        mul     add    shl
16668       // scalar        5       2      2
16669       // vector        7       2      2
16670 
16671       // The cycle RATIO of related operations are showed as a table above.
16672       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16673       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16674       // are 4, it is always profitable; but for 3 instrs patterns
16675       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16676       // So we should only do it for vector type.
16677       return IsAddOne && IsNeg ? VT.isVector() : true;
16678     }
16679   };
16680 
16681   EVT VT = N->getValueType(0);
16682   SDLoc DL(N);
16683 
16684   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16685   bool IsNeg = MulAmt.isNegative();
16686   APInt MulAmtAbs = MulAmt.abs();
16687 
16688   if ((MulAmtAbs - 1).isPowerOf2()) {
16689     // (mul x, 2^N + 1) => (add (shl x, N), x)
16690     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16691 
16692     if (!IsProfitable(IsNeg, true, VT))
16693       return SDValue();
16694 
16695     SDValue Op0 = N->getOperand(0);
16696     SDValue Op1 =
16697         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16698                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16699     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16700 
16701     if (!IsNeg)
16702       return Res;
16703 
16704     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16705   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16706     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16707     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16708 
16709     if (!IsProfitable(IsNeg, false, VT))
16710       return SDValue();
16711 
16712     SDValue Op0 = N->getOperand(0);
16713     SDValue Op1 =
16714         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16715                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16716 
16717     if (!IsNeg)
16718       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16719     else
16720       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16721 
16722   } else {
16723     return SDValue();
16724   }
16725 }
16726 
16727 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16728 // in combiner since we need to check SD flags and other subtarget features.
16729 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16730                                           DAGCombinerInfo &DCI) const {
16731   SDValue N0 = N->getOperand(0);
16732   SDValue N1 = N->getOperand(1);
16733   SDValue N2 = N->getOperand(2);
16734   SDNodeFlags Flags = N->getFlags();
16735   EVT VT = N->getValueType(0);
16736   SelectionDAG &DAG = DCI.DAG;
16737   const TargetOptions &Options = getTargetMachine().Options;
16738   unsigned Opc = N->getOpcode();
16739   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16740   bool LegalOps = !DCI.isBeforeLegalizeOps();
16741   SDLoc Loc(N);
16742 
16743   if (!isOperationLegal(ISD::FMA, VT))
16744     return SDValue();
16745 
16746   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16747   // since (fnmsub a b c)=-0 while c-ab=+0.
16748   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16749     return SDValue();
16750 
16751   // (fma (fneg a) b c) => (fnmsub a b c)
16752   // (fnmsub (fneg a) b c) => (fma a b c)
16753   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16754     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16755 
16756   // (fma a (fneg b) c) => (fnmsub a b c)
16757   // (fnmsub a (fneg b) c) => (fma a b c)
16758   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16759     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16760 
16761   return SDValue();
16762 }
16763 
16764 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16765   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16766   if (!Subtarget.is64BitELFABI())
16767     return false;
16768 
16769   // If not a tail call then no need to proceed.
16770   if (!CI->isTailCall())
16771     return false;
16772 
16773   // If sibling calls have been disabled and tail-calls aren't guaranteed
16774   // there is no reason to duplicate.
16775   auto &TM = getTargetMachine();
16776   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16777     return false;
16778 
16779   // Can't tail call a function called indirectly, or if it has variadic args.
16780   const Function *Callee = CI->getCalledFunction();
16781   if (!Callee || Callee->isVarArg())
16782     return false;
16783 
16784   // Make sure the callee and caller calling conventions are eligible for tco.
16785   const Function *Caller = CI->getParent()->getParent();
16786   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16787                                            CI->getCallingConv()))
16788       return false;
16789 
16790   // If the function is local then we have a good chance at tail-calling it
16791   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16792 }
16793 
16794 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16795   if (!Subtarget.hasVSX())
16796     return false;
16797   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16798     return true;
16799   return VT == MVT::f32 || VT == MVT::f64 ||
16800     VT == MVT::v4f32 || VT == MVT::v2f64;
16801 }
16802 
16803 bool PPCTargetLowering::
16804 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16805   const Value *Mask = AndI.getOperand(1);
16806   // If the mask is suitable for andi. or andis. we should sink the and.
16807   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16808     // Can't handle constants wider than 64-bits.
16809     if (CI->getBitWidth() > 64)
16810       return false;
16811     int64_t ConstVal = CI->getZExtValue();
16812     return isUInt<16>(ConstVal) ||
16813       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16814   }
16815 
16816   // For non-constant masks, we can always use the record-form and.
16817   return true;
16818 }
16819 
16820 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16821 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16822 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16823 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16824 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16825 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16826   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16827   assert(Subtarget.hasP9Altivec() &&
16828          "Only combine this when P9 altivec supported!");
16829   EVT VT = N->getValueType(0);
16830   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16831     return SDValue();
16832 
16833   SelectionDAG &DAG = DCI.DAG;
16834   SDLoc dl(N);
16835   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16836     // Even for signed integers, if it's known to be positive (as signed
16837     // integer) due to zero-extended inputs.
16838     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16839     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16840     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16841          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16842         (SubOpcd1 == ISD::ZERO_EXTEND ||
16843          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16844       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16845                          N->getOperand(0)->getOperand(0),
16846                          N->getOperand(0)->getOperand(1),
16847                          DAG.getTargetConstant(0, dl, MVT::i32));
16848     }
16849 
16850     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16851     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16852         N->getOperand(0).hasOneUse()) {
16853       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16854                          N->getOperand(0)->getOperand(0),
16855                          N->getOperand(0)->getOperand(1),
16856                          DAG.getTargetConstant(1, dl, MVT::i32));
16857     }
16858   }
16859 
16860   return SDValue();
16861 }
16862 
16863 // For type v4i32/v8ii16/v16i8, transform
16864 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16865 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16866 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16867 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16868 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16869                                           DAGCombinerInfo &DCI) const {
16870   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16871   assert(Subtarget.hasP9Altivec() &&
16872          "Only combine this when P9 altivec supported!");
16873 
16874   SelectionDAG &DAG = DCI.DAG;
16875   SDLoc dl(N);
16876   SDValue Cond = N->getOperand(0);
16877   SDValue TrueOpnd = N->getOperand(1);
16878   SDValue FalseOpnd = N->getOperand(2);
16879   EVT VT = N->getOperand(1).getValueType();
16880 
16881   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16882       FalseOpnd.getOpcode() != ISD::SUB)
16883     return SDValue();
16884 
16885   // ABSD only available for type v4i32/v8i16/v16i8
16886   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16887     return SDValue();
16888 
16889   // At least to save one more dependent computation
16890   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16891     return SDValue();
16892 
16893   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16894 
16895   // Can only handle unsigned comparison here
16896   switch (CC) {
16897   default:
16898     return SDValue();
16899   case ISD::SETUGT:
16900   case ISD::SETUGE:
16901     break;
16902   case ISD::SETULT:
16903   case ISD::SETULE:
16904     std::swap(TrueOpnd, FalseOpnd);
16905     break;
16906   }
16907 
16908   SDValue CmpOpnd1 = Cond.getOperand(0);
16909   SDValue CmpOpnd2 = Cond.getOperand(1);
16910 
16911   // SETCC CmpOpnd1 CmpOpnd2 cond
16912   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16913   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16914   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16915       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16916       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16917       FalseOpnd.getOperand(1) == CmpOpnd1) {
16918     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16919                        CmpOpnd1, CmpOpnd2,
16920                        DAG.getTargetConstant(0, dl, MVT::i32));
16921   }
16922 
16923   return SDValue();
16924 }
16925