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     }
896 
897     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
898     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
899 
900     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
901     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
902 
903     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
904     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
905     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
906     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
907 
908     // Altivec does not contain unordered floating-point compare instructions
909     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
910     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
911     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
912     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
913 
914     if (Subtarget.hasVSX()) {
915       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
916       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
917       if (Subtarget.hasP8Vector()) {
918         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
919         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
920       }
921       if (Subtarget.hasDirectMove() && isPPC64) {
922         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
923         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
924         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
925         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
926         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
927         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
928         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
929         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
930       }
931       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
932 
933       // The nearbyint variants are not allowed to raise the inexact exception
934       // so we can only code-gen them with unsafe math.
935       if (TM.Options.UnsafeFPMath) {
936         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
937         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
938       }
939 
940       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
941       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
942       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
943       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
944       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
945       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
946       setOperationAction(ISD::FROUND, MVT::f64, Legal);
947       setOperationAction(ISD::FRINT, MVT::f64, Legal);
948 
949       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
950       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
951       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
952       setOperationAction(ISD::FROUND, MVT::f32, Legal);
953       setOperationAction(ISD::FRINT, MVT::f32, Legal);
954 
955       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
956       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
957 
958       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
959       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
960 
961       // Share the Altivec comparison restrictions.
962       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
963       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
964       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
965       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
966 
967       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
968       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
969 
970       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
971 
972       if (Subtarget.hasP8Vector())
973         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
974 
975       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
976 
977       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
978       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
979       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
980 
981       if (Subtarget.hasP8Altivec()) {
982         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
983         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
984         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
985 
986         // 128 bit shifts can be accomplished via 3 instructions for SHL and
987         // SRL, but not for SRA because of the instructions available:
988         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
989         // doing
990         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
991         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
992         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
993 
994         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
995       }
996       else {
997         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
998         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
999         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1000 
1001         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1002 
1003         // VSX v2i64 only supports non-arithmetic operations.
1004         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1005         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1006       }
1007 
1008       setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1009 
1010       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1011       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1012       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1013       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1014 
1015       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1016 
1017       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1018       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1019       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1020       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1021       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1022       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1023       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1024       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1025 
1026       // Custom handling for partial vectors of integers converted to
1027       // floating point. We already have optimal handling for v2i32 through
1028       // the DAG combine, so those aren't necessary.
1029       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1030       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1031       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1032       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1033       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1034       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1035       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1036       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1037       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1038       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1039       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1040       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1041       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1042       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1043       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1044       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1045 
1046       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1047       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1048       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1049       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1050       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1051       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1052 
1053       if (Subtarget.hasDirectMove())
1054         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1055       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1056 
1057       // Handle constrained floating-point operations of vector.
1058       // The predictor is `hasVSX` because altivec instruction has
1059       // no exception but VSX vector instruction has.
1060       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1061       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1062       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1063       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1064       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1065       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1066       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1067       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1068       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1069       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1070       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1071       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1072       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1073 
1074       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1075       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1076       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1077       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1078       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1079       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1080       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1081       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1082       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1083       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1084       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1085       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1086       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1087 
1088       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1089     }
1090 
1091     if (Subtarget.hasP8Altivec()) {
1092       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1093       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1094     }
1095 
1096     if (Subtarget.hasP9Vector()) {
1097       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1098       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1099 
1100       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1101       // SRL, but not for SRA because of the instructions available:
1102       // VS{RL} and VS{RL}O.
1103       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1104       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1105       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1106 
1107       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1108       setOperationAction(ISD::FADD, MVT::f128, Legal);
1109       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1110       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1111       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1112       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1113       // No extending loads to f128 on PPC.
1114       for (MVT FPT : MVT::fp_valuetypes())
1115         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1116       setOperationAction(ISD::FMA, MVT::f128, Legal);
1117       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1118       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1119       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1120       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1121       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1122       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1123 
1124       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1125       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1126       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1127       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1128       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1129       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1130 
1131       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1132       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1133       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1134       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1135       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1136       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1137       // No implementation for these ops for PowerPC.
1138       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1139       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1140       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1141       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1142       setOperationAction(ISD::FREM, MVT::f128, Expand);
1143 
1144       // Handle constrained floating-point operations of fp128
1145       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1146       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1147       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1148       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1149       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1150       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1151       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1152       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1153       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1154       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1155       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1156       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1157       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1158       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1159       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1160       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1161       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1162       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1163       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1164       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1165     }
1166 
1167     if (Subtarget.hasP9Altivec()) {
1168       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1169       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1170 
1171       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1172       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1173       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1174       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1175       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1176       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1177       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1178     }
1179   }
1180 
1181   if (Subtarget.has64BitSupport())
1182     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1183 
1184   if (Subtarget.isISA3_1())
1185     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1186 
1187   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1188 
1189   if (!isPPC64) {
1190     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1191     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1192   }
1193 
1194   setBooleanContents(ZeroOrOneBooleanContent);
1195 
1196   if (Subtarget.hasAltivec()) {
1197     // Altivec instructions set fields to all zeros or all ones.
1198     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1199   }
1200 
1201   if (!isPPC64) {
1202     // These libcalls are not available in 32-bit.
1203     setLibcallName(RTLIB::SHL_I128, nullptr);
1204     setLibcallName(RTLIB::SRL_I128, nullptr);
1205     setLibcallName(RTLIB::SRA_I128, nullptr);
1206   }
1207 
1208   if (!isPPC64)
1209     setMaxAtomicSizeInBitsSupported(32);
1210 
1211   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1212 
1213   // We have target-specific dag combine patterns for the following nodes:
1214   setTargetDAGCombine(ISD::ADD);
1215   setTargetDAGCombine(ISD::SHL);
1216   setTargetDAGCombine(ISD::SRA);
1217   setTargetDAGCombine(ISD::SRL);
1218   setTargetDAGCombine(ISD::MUL);
1219   setTargetDAGCombine(ISD::FMA);
1220   setTargetDAGCombine(ISD::SINT_TO_FP);
1221   setTargetDAGCombine(ISD::BUILD_VECTOR);
1222   if (Subtarget.hasFPCVT())
1223     setTargetDAGCombine(ISD::UINT_TO_FP);
1224   setTargetDAGCombine(ISD::LOAD);
1225   setTargetDAGCombine(ISD::STORE);
1226   setTargetDAGCombine(ISD::BR_CC);
1227   if (Subtarget.useCRBits())
1228     setTargetDAGCombine(ISD::BRCOND);
1229   setTargetDAGCombine(ISD::BSWAP);
1230   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1231   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1232   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1233 
1234   setTargetDAGCombine(ISD::SIGN_EXTEND);
1235   setTargetDAGCombine(ISD::ZERO_EXTEND);
1236   setTargetDAGCombine(ISD::ANY_EXTEND);
1237 
1238   setTargetDAGCombine(ISD::TRUNCATE);
1239   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1240 
1241 
1242   if (Subtarget.useCRBits()) {
1243     setTargetDAGCombine(ISD::TRUNCATE);
1244     setTargetDAGCombine(ISD::SETCC);
1245     setTargetDAGCombine(ISD::SELECT_CC);
1246   }
1247 
1248   if (Subtarget.hasP9Altivec()) {
1249     setTargetDAGCombine(ISD::ABS);
1250     setTargetDAGCombine(ISD::VSELECT);
1251   }
1252 
1253   setLibcallName(RTLIB::LOG_F128, "logf128");
1254   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1255   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1256   setLibcallName(RTLIB::EXP_F128, "expf128");
1257   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1258   setLibcallName(RTLIB::SIN_F128, "sinf128");
1259   setLibcallName(RTLIB::COS_F128, "cosf128");
1260   setLibcallName(RTLIB::POW_F128, "powf128");
1261   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1262   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1263   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1264   setLibcallName(RTLIB::REM_F128, "fmodf128");
1265 
1266   // With 32 condition bits, we don't need to sink (and duplicate) compares
1267   // aggressively in CodeGenPrep.
1268   if (Subtarget.useCRBits()) {
1269     setHasMultipleConditionRegisters();
1270     setJumpIsExpensive();
1271   }
1272 
1273   setMinFunctionAlignment(Align(4));
1274 
1275   switch (Subtarget.getCPUDirective()) {
1276   default: break;
1277   case PPC::DIR_970:
1278   case PPC::DIR_A2:
1279   case PPC::DIR_E500:
1280   case PPC::DIR_E500mc:
1281   case PPC::DIR_E5500:
1282   case PPC::DIR_PWR4:
1283   case PPC::DIR_PWR5:
1284   case PPC::DIR_PWR5X:
1285   case PPC::DIR_PWR6:
1286   case PPC::DIR_PWR6X:
1287   case PPC::DIR_PWR7:
1288   case PPC::DIR_PWR8:
1289   case PPC::DIR_PWR9:
1290   case PPC::DIR_PWR10:
1291   case PPC::DIR_PWR_FUTURE:
1292     setPrefLoopAlignment(Align(16));
1293     setPrefFunctionAlignment(Align(16));
1294     break;
1295   }
1296 
1297   if (Subtarget.enableMachineScheduler())
1298     setSchedulingPreference(Sched::Source);
1299   else
1300     setSchedulingPreference(Sched::Hybrid);
1301 
1302   computeRegisterProperties(STI.getRegisterInfo());
1303 
1304   // The Freescale cores do better with aggressive inlining of memcpy and
1305   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1306   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1307       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1308     MaxStoresPerMemset = 32;
1309     MaxStoresPerMemsetOptSize = 16;
1310     MaxStoresPerMemcpy = 32;
1311     MaxStoresPerMemcpyOptSize = 8;
1312     MaxStoresPerMemmove = 32;
1313     MaxStoresPerMemmoveOptSize = 8;
1314   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1315     // The A2 also benefits from (very) aggressive inlining of memcpy and
1316     // friends. The overhead of a the function call, even when warm, can be
1317     // over one hundred cycles.
1318     MaxStoresPerMemset = 128;
1319     MaxStoresPerMemcpy = 128;
1320     MaxStoresPerMemmove = 128;
1321     MaxLoadsPerMemcmp = 128;
1322   } else {
1323     MaxLoadsPerMemcmp = 8;
1324     MaxLoadsPerMemcmpOptSize = 4;
1325   }
1326 
1327   IsStrictFPEnabled = true;
1328 
1329   // Let the subtarget (CPU) decide if a predictable select is more expensive
1330   // than the corresponding branch. This information is used in CGP to decide
1331   // when to convert selects into branches.
1332   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1333 }
1334 
1335 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1336 /// the desired ByVal argument alignment.
1337 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1338   if (MaxAlign == MaxMaxAlign)
1339     return;
1340   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1341     if (MaxMaxAlign >= 32 &&
1342         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1343       MaxAlign = Align(32);
1344     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1345              MaxAlign < 16)
1346       MaxAlign = Align(16);
1347   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1348     Align EltAlign;
1349     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1350     if (EltAlign > MaxAlign)
1351       MaxAlign = EltAlign;
1352   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1353     for (auto *EltTy : STy->elements()) {
1354       Align EltAlign;
1355       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1356       if (EltAlign > MaxAlign)
1357         MaxAlign = EltAlign;
1358       if (MaxAlign == MaxMaxAlign)
1359         break;
1360     }
1361   }
1362 }
1363 
1364 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1365 /// function arguments in the caller parameter area.
1366 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1367                                                   const DataLayout &DL) const {
1368   // 16byte and wider vectors are passed on 16byte boundary.
1369   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1370   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1371   if (Subtarget.hasAltivec())
1372     getMaxByValAlign(Ty, Alignment, Align(16));
1373   return Alignment.value();
1374 }
1375 
1376 bool PPCTargetLowering::useSoftFloat() const {
1377   return Subtarget.useSoftFloat();
1378 }
1379 
1380 bool PPCTargetLowering::hasSPE() const {
1381   return Subtarget.hasSPE();
1382 }
1383 
1384 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1385   return VT.isScalarInteger();
1386 }
1387 
1388 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1389 /// type is cheaper than a multiply followed by a shift.
1390 /// This is true for words and doublewords on 64-bit PowerPC.
1391 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1392   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1393                               isOperationLegal(ISD::MULHU, Type)))
1394     return true;
1395   return TargetLowering::isMulhCheaperThanMulShift(Type);
1396 }
1397 
1398 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1399   switch ((PPCISD::NodeType)Opcode) {
1400   case PPCISD::FIRST_NUMBER:    break;
1401   case PPCISD::FSEL:            return "PPCISD::FSEL";
1402   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1403   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1404   case PPCISD::FCFID:           return "PPCISD::FCFID";
1405   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1406   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1407   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1408   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1409   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1410   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1411   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1412   case PPCISD::FP_TO_UINT_IN_VSR:
1413                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1414   case PPCISD::FP_TO_SINT_IN_VSR:
1415                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1416   case PPCISD::FRE:             return "PPCISD::FRE";
1417   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1418   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1419   case PPCISD::VPERM:           return "PPCISD::VPERM";
1420   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1421   case PPCISD::XXSPLTI_SP_TO_DP:
1422     return "PPCISD::XXSPLTI_SP_TO_DP";
1423   case PPCISD::XXSPLTI32DX:
1424     return "PPCISD::XXSPLTI32DX";
1425   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1426   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1427   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1428   case PPCISD::CMPB:            return "PPCISD::CMPB";
1429   case PPCISD::Hi:              return "PPCISD::Hi";
1430   case PPCISD::Lo:              return "PPCISD::Lo";
1431   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1432   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1433   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1434   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1435   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1436   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1437   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1438   case PPCISD::SRL:             return "PPCISD::SRL";
1439   case PPCISD::SRA:             return "PPCISD::SRA";
1440   case PPCISD::SHL:             return "PPCISD::SHL";
1441   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1442   case PPCISD::CALL:            return "PPCISD::CALL";
1443   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1444   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1445   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1446   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1447   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1448   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1449   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1450   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1451   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1452   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1453   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1454   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1455   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1456   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1457   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1458   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1459     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1460   case PPCISD::ANDI_rec_1_EQ_BIT:
1461     return "PPCISD::ANDI_rec_1_EQ_BIT";
1462   case PPCISD::ANDI_rec_1_GT_BIT:
1463     return "PPCISD::ANDI_rec_1_GT_BIT";
1464   case PPCISD::VCMP:            return "PPCISD::VCMP";
1465   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1466   case PPCISD::LBRX:            return "PPCISD::LBRX";
1467   case PPCISD::STBRX:           return "PPCISD::STBRX";
1468   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1469   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1470   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1471   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1472   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1473   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1474   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1475   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1476   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1477   case PPCISD::ST_VSR_SCAL_INT:
1478                                 return "PPCISD::ST_VSR_SCAL_INT";
1479   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1480   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1481   case PPCISD::BDZ:             return "PPCISD::BDZ";
1482   case PPCISD::MFFS:            return "PPCISD::MFFS";
1483   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1484   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1485   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1486   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1487   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1488   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1489   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1490   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1491   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1492   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1493   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1494   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1495   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1496   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1497   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1498   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1499   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1500   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1501   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1502   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1503   case PPCISD::SC:              return "PPCISD::SC";
1504   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1505   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1506   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1507   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1508   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1509   case PPCISD::VABSD:           return "PPCISD::VABSD";
1510   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1511   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1512   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1513   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1514   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1515   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1516   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1517   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1518     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1519   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1520     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1521   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1522   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1523   case PPCISD::STRICT_FADDRTZ:
1524     return "PPCISD::STRICT_FADDRTZ";
1525   case PPCISD::STRICT_FCTIDZ:
1526     return "PPCISD::STRICT_FCTIDZ";
1527   case PPCISD::STRICT_FCTIWZ:
1528     return "PPCISD::STRICT_FCTIWZ";
1529   case PPCISD::STRICT_FCTIDUZ:
1530     return "PPCISD::STRICT_FCTIDUZ";
1531   case PPCISD::STRICT_FCTIWUZ:
1532     return "PPCISD::STRICT_FCTIWUZ";
1533   case PPCISD::STRICT_FCFID:
1534     return "PPCISD::STRICT_FCFID";
1535   case PPCISD::STRICT_FCFIDU:
1536     return "PPCISD::STRICT_FCFIDU";
1537   case PPCISD::STRICT_FCFIDS:
1538     return "PPCISD::STRICT_FCFIDS";
1539   case PPCISD::STRICT_FCFIDUS:
1540     return "PPCISD::STRICT_FCFIDUS";
1541   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1542   }
1543   return nullptr;
1544 }
1545 
1546 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1547                                           EVT VT) const {
1548   if (!VT.isVector())
1549     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1550 
1551   return VT.changeVectorElementTypeToInteger();
1552 }
1553 
1554 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1555   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1556   return true;
1557 }
1558 
1559 //===----------------------------------------------------------------------===//
1560 // Node matching predicates, for use by the tblgen matching code.
1561 //===----------------------------------------------------------------------===//
1562 
1563 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1564 static bool isFloatingPointZero(SDValue Op) {
1565   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1566     return CFP->getValueAPF().isZero();
1567   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1568     // Maybe this has already been legalized into the constant pool?
1569     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1570       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1571         return CFP->getValueAPF().isZero();
1572   }
1573   return false;
1574 }
1575 
1576 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1577 /// true if Op is undef or if it matches the specified value.
1578 static bool isConstantOrUndef(int Op, int Val) {
1579   return Op < 0 || Op == Val;
1580 }
1581 
1582 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1583 /// VPKUHUM instruction.
1584 /// The ShuffleKind distinguishes between big-endian operations with
1585 /// two different inputs (0), either-endian operations with two identical
1586 /// inputs (1), and little-endian operations with two different inputs (2).
1587 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1588 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1589                                SelectionDAG &DAG) {
1590   bool IsLE = DAG.getDataLayout().isLittleEndian();
1591   if (ShuffleKind == 0) {
1592     if (IsLE)
1593       return false;
1594     for (unsigned i = 0; i != 16; ++i)
1595       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1596         return false;
1597   } else if (ShuffleKind == 2) {
1598     if (!IsLE)
1599       return false;
1600     for (unsigned i = 0; i != 16; ++i)
1601       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1602         return false;
1603   } else if (ShuffleKind == 1) {
1604     unsigned j = IsLE ? 0 : 1;
1605     for (unsigned i = 0; i != 8; ++i)
1606       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1607           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1608         return false;
1609   }
1610   return true;
1611 }
1612 
1613 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1614 /// VPKUWUM instruction.
1615 /// The ShuffleKind distinguishes between big-endian operations with
1616 /// two different inputs (0), either-endian operations with two identical
1617 /// inputs (1), and little-endian operations with two different inputs (2).
1618 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1619 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1620                                SelectionDAG &DAG) {
1621   bool IsLE = DAG.getDataLayout().isLittleEndian();
1622   if (ShuffleKind == 0) {
1623     if (IsLE)
1624       return false;
1625     for (unsigned i = 0; i != 16; i += 2)
1626       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1627           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1628         return false;
1629   } else if (ShuffleKind == 2) {
1630     if (!IsLE)
1631       return false;
1632     for (unsigned i = 0; i != 16; i += 2)
1633       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1634           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1635         return false;
1636   } else if (ShuffleKind == 1) {
1637     unsigned j = IsLE ? 0 : 2;
1638     for (unsigned i = 0; i != 8; i += 2)
1639       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1640           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1641           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1642           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1643         return false;
1644   }
1645   return true;
1646 }
1647 
1648 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1649 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1650 /// current subtarget.
1651 ///
1652 /// The ShuffleKind distinguishes between big-endian operations with
1653 /// two different inputs (0), either-endian operations with two identical
1654 /// inputs (1), and little-endian operations with two different inputs (2).
1655 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1656 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1657                                SelectionDAG &DAG) {
1658   const PPCSubtarget& Subtarget =
1659       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1660   if (!Subtarget.hasP8Vector())
1661     return false;
1662 
1663   bool IsLE = DAG.getDataLayout().isLittleEndian();
1664   if (ShuffleKind == 0) {
1665     if (IsLE)
1666       return false;
1667     for (unsigned i = 0; i != 16; i += 4)
1668       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1669           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1670           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1671           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1672         return false;
1673   } else if (ShuffleKind == 2) {
1674     if (!IsLE)
1675       return false;
1676     for (unsigned i = 0; i != 16; i += 4)
1677       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1678           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1679           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1680           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1681         return false;
1682   } else if (ShuffleKind == 1) {
1683     unsigned j = IsLE ? 0 : 4;
1684     for (unsigned i = 0; i != 8; i += 4)
1685       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1686           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1687           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1688           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1689           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1690           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1691           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1692           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1693         return false;
1694   }
1695   return true;
1696 }
1697 
1698 /// isVMerge - Common function, used to match vmrg* shuffles.
1699 ///
1700 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1701                      unsigned LHSStart, unsigned RHSStart) {
1702   if (N->getValueType(0) != MVT::v16i8)
1703     return false;
1704   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1705          "Unsupported merge size!");
1706 
1707   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1708     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1709       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1710                              LHSStart+j+i*UnitSize) ||
1711           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1712                              RHSStart+j+i*UnitSize))
1713         return false;
1714     }
1715   return true;
1716 }
1717 
1718 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1719 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1720 /// The ShuffleKind distinguishes between big-endian merges with two
1721 /// different inputs (0), either-endian merges with two identical inputs (1),
1722 /// and little-endian merges with two different inputs (2).  For the latter,
1723 /// the input operands are swapped (see PPCInstrAltivec.td).
1724 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1725                              unsigned ShuffleKind, SelectionDAG &DAG) {
1726   if (DAG.getDataLayout().isLittleEndian()) {
1727     if (ShuffleKind == 1) // unary
1728       return isVMerge(N, UnitSize, 0, 0);
1729     else if (ShuffleKind == 2) // swapped
1730       return isVMerge(N, UnitSize, 0, 16);
1731     else
1732       return false;
1733   } else {
1734     if (ShuffleKind == 1) // unary
1735       return isVMerge(N, UnitSize, 8, 8);
1736     else if (ShuffleKind == 0) // normal
1737       return isVMerge(N, UnitSize, 8, 24);
1738     else
1739       return false;
1740   }
1741 }
1742 
1743 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1744 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1745 /// The ShuffleKind distinguishes between big-endian merges with two
1746 /// different inputs (0), either-endian merges with two identical inputs (1),
1747 /// and little-endian merges with two different inputs (2).  For the latter,
1748 /// the input operands are swapped (see PPCInstrAltivec.td).
1749 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1750                              unsigned ShuffleKind, SelectionDAG &DAG) {
1751   if (DAG.getDataLayout().isLittleEndian()) {
1752     if (ShuffleKind == 1) // unary
1753       return isVMerge(N, UnitSize, 8, 8);
1754     else if (ShuffleKind == 2) // swapped
1755       return isVMerge(N, UnitSize, 8, 24);
1756     else
1757       return false;
1758   } else {
1759     if (ShuffleKind == 1) // unary
1760       return isVMerge(N, UnitSize, 0, 0);
1761     else if (ShuffleKind == 0) // normal
1762       return isVMerge(N, UnitSize, 0, 16);
1763     else
1764       return false;
1765   }
1766 }
1767 
1768 /**
1769  * Common function used to match vmrgew and vmrgow shuffles
1770  *
1771  * The indexOffset determines whether to look for even or odd words in
1772  * the shuffle mask. This is based on the of the endianness of the target
1773  * machine.
1774  *   - Little Endian:
1775  *     - Use offset of 0 to check for odd elements
1776  *     - Use offset of 4 to check for even elements
1777  *   - Big Endian:
1778  *     - Use offset of 0 to check for even elements
1779  *     - Use offset of 4 to check for odd elements
1780  * A detailed description of the vector element ordering for little endian and
1781  * big endian can be found at
1782  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1783  * Targeting your applications - what little endian and big endian IBM XL C/C++
1784  * compiler differences mean to you
1785  *
1786  * The mask to the shuffle vector instruction specifies the indices of the
1787  * elements from the two input vectors to place in the result. The elements are
1788  * numbered in array-access order, starting with the first vector. These vectors
1789  * are always of type v16i8, thus each vector will contain 16 elements of size
1790  * 8. More info on the shuffle vector can be found in the
1791  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1792  * Language Reference.
1793  *
1794  * The RHSStartValue indicates whether the same input vectors are used (unary)
1795  * or two different input vectors are used, based on the following:
1796  *   - If the instruction uses the same vector for both inputs, the range of the
1797  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1798  *     be 0.
1799  *   - If the instruction has two different vectors then the range of the
1800  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1801  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1802  *     to 31 specify elements in the second vector).
1803  *
1804  * \param[in] N The shuffle vector SD Node to analyze
1805  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1806  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1807  * vector to the shuffle_vector instruction
1808  * \return true iff this shuffle vector represents an even or odd word merge
1809  */
1810 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1811                      unsigned RHSStartValue) {
1812   if (N->getValueType(0) != MVT::v16i8)
1813     return false;
1814 
1815   for (unsigned i = 0; i < 2; ++i)
1816     for (unsigned j = 0; j < 4; ++j)
1817       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1818                              i*RHSStartValue+j+IndexOffset) ||
1819           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1820                              i*RHSStartValue+j+IndexOffset+8))
1821         return false;
1822   return true;
1823 }
1824 
1825 /**
1826  * Determine if the specified shuffle mask is suitable for the vmrgew or
1827  * vmrgow instructions.
1828  *
1829  * \param[in] N The shuffle vector SD Node to analyze
1830  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1831  * \param[in] ShuffleKind Identify the type of merge:
1832  *   - 0 = big-endian merge with two different inputs;
1833  *   - 1 = either-endian merge with two identical inputs;
1834  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1835  *     little-endian merges).
1836  * \param[in] DAG The current SelectionDAG
1837  * \return true iff this shuffle mask
1838  */
1839 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1840                               unsigned ShuffleKind, SelectionDAG &DAG) {
1841   if (DAG.getDataLayout().isLittleEndian()) {
1842     unsigned indexOffset = CheckEven ? 4 : 0;
1843     if (ShuffleKind == 1) // Unary
1844       return isVMerge(N, indexOffset, 0);
1845     else if (ShuffleKind == 2) // swapped
1846       return isVMerge(N, indexOffset, 16);
1847     else
1848       return false;
1849   }
1850   else {
1851     unsigned indexOffset = CheckEven ? 0 : 4;
1852     if (ShuffleKind == 1) // Unary
1853       return isVMerge(N, indexOffset, 0);
1854     else if (ShuffleKind == 0) // Normal
1855       return isVMerge(N, indexOffset, 16);
1856     else
1857       return false;
1858   }
1859   return false;
1860 }
1861 
1862 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1863 /// amount, otherwise return -1.
1864 /// The ShuffleKind distinguishes between big-endian operations with two
1865 /// different inputs (0), either-endian operations with two identical inputs
1866 /// (1), and little-endian operations with two different inputs (2).  For the
1867 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1868 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1869                              SelectionDAG &DAG) {
1870   if (N->getValueType(0) != MVT::v16i8)
1871     return -1;
1872 
1873   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1874 
1875   // Find the first non-undef value in the shuffle mask.
1876   unsigned i;
1877   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1878     /*search*/;
1879 
1880   if (i == 16) return -1;  // all undef.
1881 
1882   // Otherwise, check to see if the rest of the elements are consecutively
1883   // numbered from this value.
1884   unsigned ShiftAmt = SVOp->getMaskElt(i);
1885   if (ShiftAmt < i) return -1;
1886 
1887   ShiftAmt -= i;
1888   bool isLE = DAG.getDataLayout().isLittleEndian();
1889 
1890   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1891     // Check the rest of the elements to see if they are consecutive.
1892     for (++i; i != 16; ++i)
1893       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1894         return -1;
1895   } else if (ShuffleKind == 1) {
1896     // Check the rest of the elements to see if they are consecutive.
1897     for (++i; i != 16; ++i)
1898       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1899         return -1;
1900   } else
1901     return -1;
1902 
1903   if (isLE)
1904     ShiftAmt = 16 - ShiftAmt;
1905 
1906   return ShiftAmt;
1907 }
1908 
1909 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1910 /// specifies a splat of a single element that is suitable for input to
1911 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1912 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1913   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1914          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1915 
1916   // The consecutive indices need to specify an element, not part of two
1917   // different elements.  So abandon ship early if this isn't the case.
1918   if (N->getMaskElt(0) % EltSize != 0)
1919     return false;
1920 
1921   // This is a splat operation if each element of the permute is the same, and
1922   // if the value doesn't reference the second vector.
1923   unsigned ElementBase = N->getMaskElt(0);
1924 
1925   // FIXME: Handle UNDEF elements too!
1926   if (ElementBase >= 16)
1927     return false;
1928 
1929   // Check that the indices are consecutive, in the case of a multi-byte element
1930   // splatted with a v16i8 mask.
1931   for (unsigned i = 1; i != EltSize; ++i)
1932     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1933       return false;
1934 
1935   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1936     if (N->getMaskElt(i) < 0) continue;
1937     for (unsigned j = 0; j != EltSize; ++j)
1938       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1939         return false;
1940   }
1941   return true;
1942 }
1943 
1944 /// Check that the mask is shuffling N byte elements. Within each N byte
1945 /// element of the mask, the indices could be either in increasing or
1946 /// decreasing order as long as they are consecutive.
1947 /// \param[in] N the shuffle vector SD Node to analyze
1948 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1949 /// Word/DoubleWord/QuadWord).
1950 /// \param[in] StepLen the delta indices number among the N byte element, if
1951 /// the mask is in increasing/decreasing order then it is 1/-1.
1952 /// \return true iff the mask is shuffling N byte elements.
1953 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1954                                    int StepLen) {
1955   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1956          "Unexpected element width.");
1957   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1958 
1959   unsigned NumOfElem = 16 / Width;
1960   unsigned MaskVal[16]; //  Width is never greater than 16
1961   for (unsigned i = 0; i < NumOfElem; ++i) {
1962     MaskVal[0] = N->getMaskElt(i * Width);
1963     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1964       return false;
1965     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1966       return false;
1967     }
1968 
1969     for (unsigned int j = 1; j < Width; ++j) {
1970       MaskVal[j] = N->getMaskElt(i * Width + j);
1971       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1972         return false;
1973       }
1974     }
1975   }
1976 
1977   return true;
1978 }
1979 
1980 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1981                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1982   if (!isNByteElemShuffleMask(N, 4, 1))
1983     return false;
1984 
1985   // Now we look at mask elements 0,4,8,12
1986   unsigned M0 = N->getMaskElt(0) / 4;
1987   unsigned M1 = N->getMaskElt(4) / 4;
1988   unsigned M2 = N->getMaskElt(8) / 4;
1989   unsigned M3 = N->getMaskElt(12) / 4;
1990   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1991   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1992 
1993   // Below, let H and L be arbitrary elements of the shuffle mask
1994   // where H is in the range [4,7] and L is in the range [0,3].
1995   // H, 1, 2, 3 or L, 5, 6, 7
1996   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1997       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1998     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1999     InsertAtByte = IsLE ? 12 : 0;
2000     Swap = M0 < 4;
2001     return true;
2002   }
2003   // 0, H, 2, 3 or 4, L, 6, 7
2004   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2005       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2006     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2007     InsertAtByte = IsLE ? 8 : 4;
2008     Swap = M1 < 4;
2009     return true;
2010   }
2011   // 0, 1, H, 3 or 4, 5, L, 7
2012   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2013       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2014     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2015     InsertAtByte = IsLE ? 4 : 8;
2016     Swap = M2 < 4;
2017     return true;
2018   }
2019   // 0, 1, 2, H or 4, 5, 6, L
2020   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2021       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2022     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2023     InsertAtByte = IsLE ? 0 : 12;
2024     Swap = M3 < 4;
2025     return true;
2026   }
2027 
2028   // If both vector operands for the shuffle are the same vector, the mask will
2029   // contain only elements from the first one and the second one will be undef.
2030   if (N->getOperand(1).isUndef()) {
2031     ShiftElts = 0;
2032     Swap = true;
2033     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2034     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2035       InsertAtByte = IsLE ? 12 : 0;
2036       return true;
2037     }
2038     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2039       InsertAtByte = IsLE ? 8 : 4;
2040       return true;
2041     }
2042     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2043       InsertAtByte = IsLE ? 4 : 8;
2044       return true;
2045     }
2046     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2047       InsertAtByte = IsLE ? 0 : 12;
2048       return true;
2049     }
2050   }
2051 
2052   return false;
2053 }
2054 
2055 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2056                                bool &Swap, bool IsLE) {
2057   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2058   // Ensure each byte index of the word is consecutive.
2059   if (!isNByteElemShuffleMask(N, 4, 1))
2060     return false;
2061 
2062   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2063   unsigned M0 = N->getMaskElt(0) / 4;
2064   unsigned M1 = N->getMaskElt(4) / 4;
2065   unsigned M2 = N->getMaskElt(8) / 4;
2066   unsigned M3 = N->getMaskElt(12) / 4;
2067 
2068   // If both vector operands for the shuffle are the same vector, the mask will
2069   // contain only elements from the first one and the second one will be undef.
2070   if (N->getOperand(1).isUndef()) {
2071     assert(M0 < 4 && "Indexing into an undef vector?");
2072     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2073       return false;
2074 
2075     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2076     Swap = false;
2077     return true;
2078   }
2079 
2080   // Ensure each word index of the ShuffleVector Mask is consecutive.
2081   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2082     return false;
2083 
2084   if (IsLE) {
2085     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2086       // Input vectors don't need to be swapped if the leading element
2087       // of the result is one of the 3 left elements of the second vector
2088       // (or if there is no shift to be done at all).
2089       Swap = false;
2090       ShiftElts = (8 - M0) % 8;
2091     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2092       // Input vectors need to be swapped if the leading element
2093       // of the result is one of the 3 left elements of the first vector
2094       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2095       Swap = true;
2096       ShiftElts = (4 - M0) % 4;
2097     }
2098 
2099     return true;
2100   } else {                                          // BE
2101     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2102       // Input vectors don't need to be swapped if the leading element
2103       // of the result is one of the 4 elements of the first vector.
2104       Swap = false;
2105       ShiftElts = M0;
2106     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2107       // Input vectors need to be swapped if the leading element
2108       // of the result is one of the 4 elements of the right vector.
2109       Swap = true;
2110       ShiftElts = M0 - 4;
2111     }
2112 
2113     return true;
2114   }
2115 }
2116 
2117 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2118   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2119 
2120   if (!isNByteElemShuffleMask(N, Width, -1))
2121     return false;
2122 
2123   for (int i = 0; i < 16; i += Width)
2124     if (N->getMaskElt(i) != i + Width - 1)
2125       return false;
2126 
2127   return true;
2128 }
2129 
2130 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2131   return isXXBRShuffleMaskHelper(N, 2);
2132 }
2133 
2134 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2135   return isXXBRShuffleMaskHelper(N, 4);
2136 }
2137 
2138 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2139   return isXXBRShuffleMaskHelper(N, 8);
2140 }
2141 
2142 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2143   return isXXBRShuffleMaskHelper(N, 16);
2144 }
2145 
2146 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2147 /// if the inputs to the instruction should be swapped and set \p DM to the
2148 /// value for the immediate.
2149 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2150 /// AND element 0 of the result comes from the first input (LE) or second input
2151 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2152 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2153 /// mask.
2154 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2155                                bool &Swap, bool IsLE) {
2156   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2157 
2158   // Ensure each byte index of the double word is consecutive.
2159   if (!isNByteElemShuffleMask(N, 8, 1))
2160     return false;
2161 
2162   unsigned M0 = N->getMaskElt(0) / 8;
2163   unsigned M1 = N->getMaskElt(8) / 8;
2164   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2165 
2166   // If both vector operands for the shuffle are the same vector, the mask will
2167   // contain only elements from the first one and the second one will be undef.
2168   if (N->getOperand(1).isUndef()) {
2169     if ((M0 | M1) < 2) {
2170       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2171       Swap = false;
2172       return true;
2173     } else
2174       return false;
2175   }
2176 
2177   if (IsLE) {
2178     if (M0 > 1 && M1 < 2) {
2179       Swap = false;
2180     } else if (M0 < 2 && M1 > 1) {
2181       M0 = (M0 + 2) % 4;
2182       M1 = (M1 + 2) % 4;
2183       Swap = true;
2184     } else
2185       return false;
2186 
2187     // Note: if control flow comes here that means Swap is already set above
2188     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2189     return true;
2190   } else { // BE
2191     if (M0 < 2 && M1 > 1) {
2192       Swap = false;
2193     } else if (M0 > 1 && M1 < 2) {
2194       M0 = (M0 + 2) % 4;
2195       M1 = (M1 + 2) % 4;
2196       Swap = true;
2197     } else
2198       return false;
2199 
2200     // Note: if control flow comes here that means Swap is already set above
2201     DM = (M0 << 1) + (M1 & 1);
2202     return true;
2203   }
2204 }
2205 
2206 
2207 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2208 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2209 /// elements are counted from the left of the vector register).
2210 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2211                                          SelectionDAG &DAG) {
2212   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2213   assert(isSplatShuffleMask(SVOp, EltSize));
2214   if (DAG.getDataLayout().isLittleEndian())
2215     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2216   else
2217     return SVOp->getMaskElt(0) / EltSize;
2218 }
2219 
2220 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2221 /// by using a vspltis[bhw] instruction of the specified element size, return
2222 /// the constant being splatted.  The ByteSize field indicates the number of
2223 /// bytes of each element [124] -> [bhw].
2224 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2225   SDValue OpVal(nullptr, 0);
2226 
2227   // If ByteSize of the splat is bigger than the element size of the
2228   // build_vector, then we have a case where we are checking for a splat where
2229   // multiple elements of the buildvector are folded together into a single
2230   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2231   unsigned EltSize = 16/N->getNumOperands();
2232   if (EltSize < ByteSize) {
2233     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2234     SDValue UniquedVals[4];
2235     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2236 
2237     // See if all of the elements in the buildvector agree across.
2238     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2239       if (N->getOperand(i).isUndef()) continue;
2240       // If the element isn't a constant, bail fully out.
2241       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2242 
2243       if (!UniquedVals[i&(Multiple-1)].getNode())
2244         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2245       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2246         return SDValue();  // no match.
2247     }
2248 
2249     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2250     // either constant or undef values that are identical for each chunk.  See
2251     // if these chunks can form into a larger vspltis*.
2252 
2253     // Check to see if all of the leading entries are either 0 or -1.  If
2254     // neither, then this won't fit into the immediate field.
2255     bool LeadingZero = true;
2256     bool LeadingOnes = true;
2257     for (unsigned i = 0; i != Multiple-1; ++i) {
2258       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2259 
2260       LeadingZero &= isNullConstant(UniquedVals[i]);
2261       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2262     }
2263     // Finally, check the least significant entry.
2264     if (LeadingZero) {
2265       if (!UniquedVals[Multiple-1].getNode())
2266         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2267       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2268       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2269         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2270     }
2271     if (LeadingOnes) {
2272       if (!UniquedVals[Multiple-1].getNode())
2273         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2274       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2275       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2276         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2277     }
2278 
2279     return SDValue();
2280   }
2281 
2282   // Check to see if this buildvec has a single non-undef value in its elements.
2283   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2284     if (N->getOperand(i).isUndef()) continue;
2285     if (!OpVal.getNode())
2286       OpVal = N->getOperand(i);
2287     else if (OpVal != N->getOperand(i))
2288       return SDValue();
2289   }
2290 
2291   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2292 
2293   unsigned ValSizeInBytes = EltSize;
2294   uint64_t Value = 0;
2295   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2296     Value = CN->getZExtValue();
2297   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2298     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2299     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2300   }
2301 
2302   // If the splat value is larger than the element value, then we can never do
2303   // this splat.  The only case that we could fit the replicated bits into our
2304   // immediate field for would be zero, and we prefer to use vxor for it.
2305   if (ValSizeInBytes < ByteSize) return SDValue();
2306 
2307   // If the element value is larger than the splat value, check if it consists
2308   // of a repeated bit pattern of size ByteSize.
2309   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2310     return SDValue();
2311 
2312   // Properly sign extend the value.
2313   int MaskVal = SignExtend32(Value, ByteSize * 8);
2314 
2315   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2316   if (MaskVal == 0) return SDValue();
2317 
2318   // Finally, if this value fits in a 5 bit sext field, return it
2319   if (SignExtend32<5>(MaskVal) == MaskVal)
2320     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2321   return SDValue();
2322 }
2323 
2324 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2325 /// amount, otherwise return -1.
2326 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2327   EVT VT = N->getValueType(0);
2328   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2329     return -1;
2330 
2331   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2332 
2333   // Find the first non-undef value in the shuffle mask.
2334   unsigned i;
2335   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2336     /*search*/;
2337 
2338   if (i == 4) return -1;  // all undef.
2339 
2340   // Otherwise, check to see if the rest of the elements are consecutively
2341   // numbered from this value.
2342   unsigned ShiftAmt = SVOp->getMaskElt(i);
2343   if (ShiftAmt < i) return -1;
2344   ShiftAmt -= i;
2345 
2346   // Check the rest of the elements to see if they are consecutive.
2347   for (++i; i != 4; ++i)
2348     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2349       return -1;
2350 
2351   return ShiftAmt;
2352 }
2353 
2354 //===----------------------------------------------------------------------===//
2355 //  Addressing Mode Selection
2356 //===----------------------------------------------------------------------===//
2357 
2358 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2359 /// or 64-bit immediate, and if the value can be accurately represented as a
2360 /// sign extension from a 16-bit value.  If so, this returns true and the
2361 /// immediate.
2362 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2363   if (!isa<ConstantSDNode>(N))
2364     return false;
2365 
2366   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2367   if (N->getValueType(0) == MVT::i32)
2368     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2369   else
2370     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2371 }
2372 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2373   return isIntS16Immediate(Op.getNode(), Imm);
2374 }
2375 
2376 
2377 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2378 /// be represented as an indexed [r+r] operation.
2379 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2380                                                SDValue &Index,
2381                                                SelectionDAG &DAG) const {
2382   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2383       UI != E; ++UI) {
2384     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2385       if (Memop->getMemoryVT() == MVT::f64) {
2386           Base = N.getOperand(0);
2387           Index = N.getOperand(1);
2388           return true;
2389       }
2390     }
2391   }
2392   return false;
2393 }
2394 
2395 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2396 /// can be represented as an indexed [r+r] operation.  Returns false if it
2397 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2398 /// non-zero and N can be represented by a base register plus a signed 16-bit
2399 /// displacement, make a more precise judgement by checking (displacement % \p
2400 /// EncodingAlignment).
2401 bool PPCTargetLowering::SelectAddressRegReg(
2402     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2403     MaybeAlign EncodingAlignment) const {
2404   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2405   // a [pc+imm].
2406   if (SelectAddressPCRel(N, Base))
2407     return false;
2408 
2409   int16_t Imm = 0;
2410   if (N.getOpcode() == ISD::ADD) {
2411     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2412     // SPE load/store can only handle 8-bit offsets.
2413     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2414         return true;
2415     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2416         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2417       return false; // r+i
2418     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2419       return false;    // r+i
2420 
2421     Base = N.getOperand(0);
2422     Index = N.getOperand(1);
2423     return true;
2424   } else if (N.getOpcode() == ISD::OR) {
2425     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2426         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2427       return false; // r+i can fold it if we can.
2428 
2429     // If this is an or of disjoint bitfields, we can codegen this as an add
2430     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2431     // disjoint.
2432     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2433 
2434     if (LHSKnown.Zero.getBoolValue()) {
2435       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2436       // If all of the bits are known zero on the LHS or RHS, the add won't
2437       // carry.
2438       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2439         Base = N.getOperand(0);
2440         Index = N.getOperand(1);
2441         return true;
2442       }
2443     }
2444   }
2445 
2446   return false;
2447 }
2448 
2449 // If we happen to be doing an i64 load or store into a stack slot that has
2450 // less than a 4-byte alignment, then the frame-index elimination may need to
2451 // use an indexed load or store instruction (because the offset may not be a
2452 // multiple of 4). The extra register needed to hold the offset comes from the
2453 // register scavenger, and it is possible that the scavenger will need to use
2454 // an emergency spill slot. As a result, we need to make sure that a spill slot
2455 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2456 // stack slot.
2457 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2458   // FIXME: This does not handle the LWA case.
2459   if (VT != MVT::i64)
2460     return;
2461 
2462   // NOTE: We'll exclude negative FIs here, which come from argument
2463   // lowering, because there are no known test cases triggering this problem
2464   // using packed structures (or similar). We can remove this exclusion if
2465   // we find such a test case. The reason why this is so test-case driven is
2466   // because this entire 'fixup' is only to prevent crashes (from the
2467   // register scavenger) on not-really-valid inputs. For example, if we have:
2468   //   %a = alloca i1
2469   //   %b = bitcast i1* %a to i64*
2470   //   store i64* a, i64 b
2471   // then the store should really be marked as 'align 1', but is not. If it
2472   // were marked as 'align 1' then the indexed form would have been
2473   // instruction-selected initially, and the problem this 'fixup' is preventing
2474   // won't happen regardless.
2475   if (FrameIdx < 0)
2476     return;
2477 
2478   MachineFunction &MF = DAG.getMachineFunction();
2479   MachineFrameInfo &MFI = MF.getFrameInfo();
2480 
2481   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2482     return;
2483 
2484   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2485   FuncInfo->setHasNonRISpills();
2486 }
2487 
2488 /// Returns true if the address N can be represented by a base register plus
2489 /// a signed 16-bit displacement [r+imm], and if it is not better
2490 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2491 /// displacements that are multiples of that value.
2492 bool PPCTargetLowering::SelectAddressRegImm(
2493     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2494     MaybeAlign EncodingAlignment) const {
2495   // FIXME dl should come from parent load or store, not from address
2496   SDLoc dl(N);
2497 
2498   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2499   // a [pc+imm].
2500   if (SelectAddressPCRel(N, Base))
2501     return false;
2502 
2503   // If this can be more profitably realized as r+r, fail.
2504   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2505     return false;
2506 
2507   if (N.getOpcode() == ISD::ADD) {
2508     int16_t imm = 0;
2509     if (isIntS16Immediate(N.getOperand(1), imm) &&
2510         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2511       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2512       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2513         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2514         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2515       } else {
2516         Base = N.getOperand(0);
2517       }
2518       return true; // [r+i]
2519     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2520       // Match LOAD (ADD (X, Lo(G))).
2521       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2522              && "Cannot handle constant offsets yet!");
2523       Disp = N.getOperand(1).getOperand(0);  // The global address.
2524       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2525              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2526              Disp.getOpcode() == ISD::TargetConstantPool ||
2527              Disp.getOpcode() == ISD::TargetJumpTable);
2528       Base = N.getOperand(0);
2529       return true;  // [&g+r]
2530     }
2531   } else if (N.getOpcode() == ISD::OR) {
2532     int16_t imm = 0;
2533     if (isIntS16Immediate(N.getOperand(1), imm) &&
2534         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2535       // If this is an or of disjoint bitfields, we can codegen this as an add
2536       // (for better address arithmetic) if the LHS and RHS of the OR are
2537       // provably disjoint.
2538       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2539 
2540       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2541         // If all of the bits are known zero on the LHS or RHS, the add won't
2542         // carry.
2543         if (FrameIndexSDNode *FI =
2544               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2545           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2546           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2547         } else {
2548           Base = N.getOperand(0);
2549         }
2550         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2551         return true;
2552       }
2553     }
2554   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2555     // Loading from a constant address.
2556 
2557     // If this address fits entirely in a 16-bit sext immediate field, codegen
2558     // this as "d, 0"
2559     int16_t Imm;
2560     if (isIntS16Immediate(CN, Imm) &&
2561         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2562       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2563       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2564                              CN->getValueType(0));
2565       return true;
2566     }
2567 
2568     // Handle 32-bit sext immediates with LIS + addr mode.
2569     if ((CN->getValueType(0) == MVT::i32 ||
2570          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2571         (!EncodingAlignment ||
2572          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2573       int Addr = (int)CN->getZExtValue();
2574 
2575       // Otherwise, break this down into an LIS + disp.
2576       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2577 
2578       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2579                                    MVT::i32);
2580       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2581       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2582       return true;
2583     }
2584   }
2585 
2586   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2587   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2588     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2589     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2590   } else
2591     Base = N;
2592   return true;      // [r+0]
2593 }
2594 
2595 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2596 /// represented as an indexed [r+r] operation.
2597 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2598                                                 SDValue &Index,
2599                                                 SelectionDAG &DAG) const {
2600   // Check to see if we can easily represent this as an [r+r] address.  This
2601   // will fail if it thinks that the address is more profitably represented as
2602   // reg+imm, e.g. where imm = 0.
2603   if (SelectAddressRegReg(N, Base, Index, DAG))
2604     return true;
2605 
2606   // If the address is the result of an add, we will utilize the fact that the
2607   // address calculation includes an implicit add.  However, we can reduce
2608   // register pressure if we do not materialize a constant just for use as the
2609   // index register.  We only get rid of the add if it is not an add of a
2610   // value and a 16-bit signed constant and both have a single use.
2611   int16_t imm = 0;
2612   if (N.getOpcode() == ISD::ADD &&
2613       (!isIntS16Immediate(N.getOperand(1), imm) ||
2614        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2615     Base = N.getOperand(0);
2616     Index = N.getOperand(1);
2617     return true;
2618   }
2619 
2620   // Otherwise, do it the hard way, using R0 as the base register.
2621   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2622                          N.getValueType());
2623   Index = N;
2624   return true;
2625 }
2626 
2627 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2628   Ty *PCRelCand = dyn_cast<Ty>(N);
2629   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2630 }
2631 
2632 /// Returns true if this address is a PC Relative address.
2633 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2634 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2635 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2636   // This is a materialize PC Relative node. Always select this as PC Relative.
2637   Base = N;
2638   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2639     return true;
2640   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2641       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2642       isValidPCRelNode<JumpTableSDNode>(N) ||
2643       isValidPCRelNode<BlockAddressSDNode>(N))
2644     return true;
2645   return false;
2646 }
2647 
2648 /// Returns true if we should use a direct load into vector instruction
2649 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2650 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2651 
2652   // If there are any other uses other than scalar to vector, then we should
2653   // keep it as a scalar load -> direct move pattern to prevent multiple
2654   // loads.
2655   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2656   if (!LD)
2657     return false;
2658 
2659   EVT MemVT = LD->getMemoryVT();
2660   if (!MemVT.isSimple())
2661     return false;
2662   switch(MemVT.getSimpleVT().SimpleTy) {
2663   case MVT::i64:
2664     break;
2665   case MVT::i32:
2666     if (!ST.hasP8Vector())
2667       return false;
2668     break;
2669   case MVT::i16:
2670   case MVT::i8:
2671     if (!ST.hasP9Vector())
2672       return false;
2673     break;
2674   default:
2675     return false;
2676   }
2677 
2678   SDValue LoadedVal(N, 0);
2679   if (!LoadedVal.hasOneUse())
2680     return false;
2681 
2682   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2683        UI != UE; ++UI)
2684     if (UI.getUse().get().getResNo() == 0 &&
2685         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2686         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2687       return false;
2688 
2689   return true;
2690 }
2691 
2692 /// getPreIndexedAddressParts - returns true by value, base pointer and
2693 /// offset pointer and addressing mode by reference if the node's address
2694 /// can be legally represented as pre-indexed load / store address.
2695 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2696                                                   SDValue &Offset,
2697                                                   ISD::MemIndexedMode &AM,
2698                                                   SelectionDAG &DAG) const {
2699   if (DisablePPCPreinc) return false;
2700 
2701   bool isLoad = true;
2702   SDValue Ptr;
2703   EVT VT;
2704   unsigned Alignment;
2705   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2706     Ptr = LD->getBasePtr();
2707     VT = LD->getMemoryVT();
2708     Alignment = LD->getAlignment();
2709   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2710     Ptr = ST->getBasePtr();
2711     VT  = ST->getMemoryVT();
2712     Alignment = ST->getAlignment();
2713     isLoad = false;
2714   } else
2715     return false;
2716 
2717   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2718   // instructions because we can fold these into a more efficient instruction
2719   // instead, (such as LXSD).
2720   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2721     return false;
2722   }
2723 
2724   // PowerPC doesn't have preinc load/store instructions for vectors
2725   if (VT.isVector())
2726     return false;
2727 
2728   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2729     // Common code will reject creating a pre-inc form if the base pointer
2730     // is a frame index, or if N is a store and the base pointer is either
2731     // the same as or a predecessor of the value being stored.  Check for
2732     // those situations here, and try with swapped Base/Offset instead.
2733     bool Swap = false;
2734 
2735     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2736       Swap = true;
2737     else if (!isLoad) {
2738       SDValue Val = cast<StoreSDNode>(N)->getValue();
2739       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2740         Swap = true;
2741     }
2742 
2743     if (Swap)
2744       std::swap(Base, Offset);
2745 
2746     AM = ISD::PRE_INC;
2747     return true;
2748   }
2749 
2750   // LDU/STU can only handle immediates that are a multiple of 4.
2751   if (VT != MVT::i64) {
2752     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2753       return false;
2754   } else {
2755     // LDU/STU need an address with at least 4-byte alignment.
2756     if (Alignment < 4)
2757       return false;
2758 
2759     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2760       return false;
2761   }
2762 
2763   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2764     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2765     // sext i32 to i64 when addr mode is r+i.
2766     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2767         LD->getExtensionType() == ISD::SEXTLOAD &&
2768         isa<ConstantSDNode>(Offset))
2769       return false;
2770   }
2771 
2772   AM = ISD::PRE_INC;
2773   return true;
2774 }
2775 
2776 //===----------------------------------------------------------------------===//
2777 //  LowerOperation implementation
2778 //===----------------------------------------------------------------------===//
2779 
2780 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2781 /// and LoOpFlags to the target MO flags.
2782 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2783                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2784                                const GlobalValue *GV = nullptr) {
2785   HiOpFlags = PPCII::MO_HA;
2786   LoOpFlags = PPCII::MO_LO;
2787 
2788   // Don't use the pic base if not in PIC relocation model.
2789   if (IsPIC) {
2790     HiOpFlags |= PPCII::MO_PIC_FLAG;
2791     LoOpFlags |= PPCII::MO_PIC_FLAG;
2792   }
2793 }
2794 
2795 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2796                              SelectionDAG &DAG) {
2797   SDLoc DL(HiPart);
2798   EVT PtrVT = HiPart.getValueType();
2799   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2800 
2801   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2802   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2803 
2804   // With PIC, the first instruction is actually "GR+hi(&G)".
2805   if (isPIC)
2806     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2807                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2808 
2809   // Generate non-pic code that has direct accesses to the constant pool.
2810   // The address of the global is just (hi(&g)+lo(&g)).
2811   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2812 }
2813 
2814 static void setUsesTOCBasePtr(MachineFunction &MF) {
2815   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2816   FuncInfo->setUsesTOCBasePtr();
2817 }
2818 
2819 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2820   setUsesTOCBasePtr(DAG.getMachineFunction());
2821 }
2822 
2823 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2824                                        SDValue GA) const {
2825   const bool Is64Bit = Subtarget.isPPC64();
2826   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2827   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2828                         : Subtarget.isAIXABI()
2829                               ? DAG.getRegister(PPC::R2, VT)
2830                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2831   SDValue Ops[] = { GA, Reg };
2832   return DAG.getMemIntrinsicNode(
2833       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2834       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2835       MachineMemOperand::MOLoad);
2836 }
2837 
2838 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2839                                              SelectionDAG &DAG) const {
2840   EVT PtrVT = Op.getValueType();
2841   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2842   const Constant *C = CP->getConstVal();
2843 
2844   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2845   // The actual address of the GlobalValue is stored in the TOC.
2846   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2847     if (Subtarget.isUsingPCRelativeCalls()) {
2848       SDLoc DL(CP);
2849       EVT Ty = getPointerTy(DAG.getDataLayout());
2850       SDValue ConstPool = DAG.getTargetConstantPool(
2851           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2852       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2853     }
2854     setUsesTOCBasePtr(DAG);
2855     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2856     return getTOCEntry(DAG, SDLoc(CP), GA);
2857   }
2858 
2859   unsigned MOHiFlag, MOLoFlag;
2860   bool IsPIC = isPositionIndependent();
2861   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2862 
2863   if (IsPIC && Subtarget.isSVR4ABI()) {
2864     SDValue GA =
2865         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2866     return getTOCEntry(DAG, SDLoc(CP), GA);
2867   }
2868 
2869   SDValue CPIHi =
2870       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2871   SDValue CPILo =
2872       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2873   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2874 }
2875 
2876 // For 64-bit PowerPC, prefer the more compact relative encodings.
2877 // This trades 32 bits per jump table entry for one or two instructions
2878 // on the jump site.
2879 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2880   if (isJumpTableRelative())
2881     return MachineJumpTableInfo::EK_LabelDifference32;
2882 
2883   return TargetLowering::getJumpTableEncoding();
2884 }
2885 
2886 bool PPCTargetLowering::isJumpTableRelative() const {
2887   if (UseAbsoluteJumpTables)
2888     return false;
2889   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2890     return true;
2891   return TargetLowering::isJumpTableRelative();
2892 }
2893 
2894 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2895                                                     SelectionDAG &DAG) const {
2896   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2897     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2898 
2899   switch (getTargetMachine().getCodeModel()) {
2900   case CodeModel::Small:
2901   case CodeModel::Medium:
2902     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2903   default:
2904     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2905                        getPointerTy(DAG.getDataLayout()));
2906   }
2907 }
2908 
2909 const MCExpr *
2910 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2911                                                 unsigned JTI,
2912                                                 MCContext &Ctx) const {
2913   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2914     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2915 
2916   switch (getTargetMachine().getCodeModel()) {
2917   case CodeModel::Small:
2918   case CodeModel::Medium:
2919     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2920   default:
2921     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2922   }
2923 }
2924 
2925 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2926   EVT PtrVT = Op.getValueType();
2927   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2928 
2929   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2930   if (Subtarget.isUsingPCRelativeCalls()) {
2931     SDLoc DL(JT);
2932     EVT Ty = getPointerTy(DAG.getDataLayout());
2933     SDValue GA =
2934         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2935     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2936     return MatAddr;
2937   }
2938 
2939   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2940   // The actual address of the GlobalValue is stored in the TOC.
2941   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2942     setUsesTOCBasePtr(DAG);
2943     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2944     return getTOCEntry(DAG, SDLoc(JT), GA);
2945   }
2946 
2947   unsigned MOHiFlag, MOLoFlag;
2948   bool IsPIC = isPositionIndependent();
2949   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2950 
2951   if (IsPIC && Subtarget.isSVR4ABI()) {
2952     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2953                                         PPCII::MO_PIC_FLAG);
2954     return getTOCEntry(DAG, SDLoc(GA), GA);
2955   }
2956 
2957   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2958   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2959   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2960 }
2961 
2962 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2963                                              SelectionDAG &DAG) const {
2964   EVT PtrVT = Op.getValueType();
2965   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2966   const BlockAddress *BA = BASDN->getBlockAddress();
2967 
2968   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2969   if (Subtarget.isUsingPCRelativeCalls()) {
2970     SDLoc DL(BASDN);
2971     EVT Ty = getPointerTy(DAG.getDataLayout());
2972     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2973                                            PPCII::MO_PCREL_FLAG);
2974     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2975     return MatAddr;
2976   }
2977 
2978   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2979   // The actual BlockAddress is stored in the TOC.
2980   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2981     setUsesTOCBasePtr(DAG);
2982     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2983     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2984   }
2985 
2986   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2987   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2988     return getTOCEntry(
2989         DAG, SDLoc(BASDN),
2990         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2991 
2992   unsigned MOHiFlag, MOLoFlag;
2993   bool IsPIC = isPositionIndependent();
2994   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2995   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2996   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2997   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2998 }
2999 
3000 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3001                                               SelectionDAG &DAG) const {
3002   // FIXME: TLS addresses currently use medium model code sequences,
3003   // which is the most useful form.  Eventually support for small and
3004   // large models could be added if users need it, at the cost of
3005   // additional complexity.
3006   if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS)
3007     report_fatal_error("Thread local storage is not supported with pc-relative"
3008                        " addressing - please compile with -mno-pcrel");
3009   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3010   if (DAG.getTarget().useEmulatedTLS())
3011     return LowerToTLSEmulatedModel(GA, DAG);
3012 
3013   SDLoc dl(GA);
3014   const GlobalValue *GV = GA->getGlobal();
3015   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3016   bool is64bit = Subtarget.isPPC64();
3017   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3018   PICLevel::Level picLevel = M->getPICLevel();
3019 
3020   const TargetMachine &TM = getTargetMachine();
3021   TLSModel::Model Model = TM.getTLSModel(GV);
3022 
3023   if (Model == TLSModel::LocalExec) {
3024     if (Subtarget.isUsingPCRelativeCalls()) {
3025       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3026       SDValue TGA = DAG.getTargetGlobalAddress(
3027           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3028       SDValue MatAddr =
3029           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3030       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3031     }
3032 
3033     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3034                                                PPCII::MO_TPREL_HA);
3035     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3036                                                PPCII::MO_TPREL_LO);
3037     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3038                              : DAG.getRegister(PPC::R2, MVT::i32);
3039 
3040     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3041     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3042   }
3043 
3044   if (Model == TLSModel::InitialExec) {
3045     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3046     SDValue TGA = DAG.getTargetGlobalAddress(
3047         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3048     SDValue TGATLS = DAG.getTargetGlobalAddress(
3049         GV, dl, PtrVT, 0,
3050         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3051     SDValue TPOffset;
3052     if (IsPCRel) {
3053       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3054       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3055                              MachinePointerInfo());
3056     } else {
3057       SDValue GOTPtr;
3058       if (is64bit) {
3059         setUsesTOCBasePtr(DAG);
3060         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3061         GOTPtr =
3062             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3063       } else {
3064         if (!TM.isPositionIndependent())
3065           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3066         else if (picLevel == PICLevel::SmallPIC)
3067           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3068         else
3069           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3070       }
3071       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3072     }
3073     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3074   }
3075 
3076   if (Model == TLSModel::GeneralDynamic) {
3077     if (Subtarget.isUsingPCRelativeCalls()) {
3078       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3079                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3080       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3081     }
3082 
3083     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3084     SDValue GOTPtr;
3085     if (is64bit) {
3086       setUsesTOCBasePtr(DAG);
3087       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3088       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3089                                    GOTReg, TGA);
3090     } else {
3091       if (picLevel == PICLevel::SmallPIC)
3092         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3093       else
3094         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3095     }
3096     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3097                        GOTPtr, TGA, TGA);
3098   }
3099 
3100   if (Model == TLSModel::LocalDynamic) {
3101     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3102     SDValue GOTPtr;
3103     if (is64bit) {
3104       setUsesTOCBasePtr(DAG);
3105       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3106       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3107                            GOTReg, TGA);
3108     } else {
3109       if (picLevel == PICLevel::SmallPIC)
3110         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3111       else
3112         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3113     }
3114     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3115                                   PtrVT, GOTPtr, TGA, TGA);
3116     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3117                                       PtrVT, TLSAddr, TGA);
3118     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3119   }
3120 
3121   llvm_unreachable("Unknown TLS model!");
3122 }
3123 
3124 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3125                                               SelectionDAG &DAG) const {
3126   EVT PtrVT = Op.getValueType();
3127   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3128   SDLoc DL(GSDN);
3129   const GlobalValue *GV = GSDN->getGlobal();
3130 
3131   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3132   // The actual address of the GlobalValue is stored in the TOC.
3133   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3134     if (Subtarget.isUsingPCRelativeCalls()) {
3135       EVT Ty = getPointerTy(DAG.getDataLayout());
3136       if (isAccessedAsGotIndirect(Op)) {
3137         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3138                                                 PPCII::MO_PCREL_FLAG |
3139                                                     PPCII::MO_GOT_FLAG);
3140         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3141         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3142                                    MachinePointerInfo());
3143         return Load;
3144       } else {
3145         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3146                                                 PPCII::MO_PCREL_FLAG);
3147         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3148       }
3149     }
3150     setUsesTOCBasePtr(DAG);
3151     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3152     return getTOCEntry(DAG, DL, GA);
3153   }
3154 
3155   unsigned MOHiFlag, MOLoFlag;
3156   bool IsPIC = isPositionIndependent();
3157   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3158 
3159   if (IsPIC && Subtarget.isSVR4ABI()) {
3160     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3161                                             GSDN->getOffset(),
3162                                             PPCII::MO_PIC_FLAG);
3163     return getTOCEntry(DAG, DL, GA);
3164   }
3165 
3166   SDValue GAHi =
3167     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3168   SDValue GALo =
3169     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3170 
3171   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3172 }
3173 
3174 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3175   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3176   SDLoc dl(Op);
3177 
3178   if (Op.getValueType() == MVT::v2i64) {
3179     // When the operands themselves are v2i64 values, we need to do something
3180     // special because VSX has no underlying comparison operations for these.
3181     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3182       // Equality can be handled by casting to the legal type for Altivec
3183       // comparisons, everything else needs to be expanded.
3184       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3185         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3186                  DAG.getSetCC(dl, MVT::v4i32,
3187                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3188                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3189                    CC));
3190       }
3191 
3192       return SDValue();
3193     }
3194 
3195     // We handle most of these in the usual way.
3196     return Op;
3197   }
3198 
3199   // If we're comparing for equality to zero, expose the fact that this is
3200   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3201   // fold the new nodes.
3202   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3203     return V;
3204 
3205   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3206     // Leave comparisons against 0 and -1 alone for now, since they're usually
3207     // optimized.  FIXME: revisit this when we can custom lower all setcc
3208     // optimizations.
3209     if (C->isAllOnesValue() || C->isNullValue())
3210       return SDValue();
3211   }
3212 
3213   // If we have an integer seteq/setne, turn it into a compare against zero
3214   // by xor'ing the rhs with the lhs, which is faster than setting a
3215   // condition register, reading it back out, and masking the correct bit.  The
3216   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3217   // the result to other bit-twiddling opportunities.
3218   EVT LHSVT = Op.getOperand(0).getValueType();
3219   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3220     EVT VT = Op.getValueType();
3221     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3222                                 Op.getOperand(1));
3223     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3224   }
3225   return SDValue();
3226 }
3227 
3228 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3229   SDNode *Node = Op.getNode();
3230   EVT VT = Node->getValueType(0);
3231   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3232   SDValue InChain = Node->getOperand(0);
3233   SDValue VAListPtr = Node->getOperand(1);
3234   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3235   SDLoc dl(Node);
3236 
3237   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3238 
3239   // gpr_index
3240   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3241                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3242   InChain = GprIndex.getValue(1);
3243 
3244   if (VT == MVT::i64) {
3245     // Check if GprIndex is even
3246     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3247                                  DAG.getConstant(1, dl, MVT::i32));
3248     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3249                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3250     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3251                                           DAG.getConstant(1, dl, MVT::i32));
3252     // Align GprIndex to be even if it isn't
3253     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3254                            GprIndex);
3255   }
3256 
3257   // fpr index is 1 byte after gpr
3258   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3259                                DAG.getConstant(1, dl, MVT::i32));
3260 
3261   // fpr
3262   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3263                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3264   InChain = FprIndex.getValue(1);
3265 
3266   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3267                                        DAG.getConstant(8, dl, MVT::i32));
3268 
3269   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3270                                         DAG.getConstant(4, dl, MVT::i32));
3271 
3272   // areas
3273   SDValue OverflowArea =
3274       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3275   InChain = OverflowArea.getValue(1);
3276 
3277   SDValue RegSaveArea =
3278       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3279   InChain = RegSaveArea.getValue(1);
3280 
3281   // select overflow_area if index > 8
3282   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3283                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3284 
3285   // adjustment constant gpr_index * 4/8
3286   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3287                                     VT.isInteger() ? GprIndex : FprIndex,
3288                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3289                                                     MVT::i32));
3290 
3291   // OurReg = RegSaveArea + RegConstant
3292   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3293                                RegConstant);
3294 
3295   // Floating types are 32 bytes into RegSaveArea
3296   if (VT.isFloatingPoint())
3297     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3298                          DAG.getConstant(32, dl, MVT::i32));
3299 
3300   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3301   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3302                                    VT.isInteger() ? GprIndex : FprIndex,
3303                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3304                                                    MVT::i32));
3305 
3306   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3307                               VT.isInteger() ? VAListPtr : FprPtr,
3308                               MachinePointerInfo(SV), MVT::i8);
3309 
3310   // determine if we should load from reg_save_area or overflow_area
3311   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3312 
3313   // increase overflow_area by 4/8 if gpr/fpr > 8
3314   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3315                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3316                                           dl, MVT::i32));
3317 
3318   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3319                              OverflowAreaPlusN);
3320 
3321   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3322                               MachinePointerInfo(), MVT::i32);
3323 
3324   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3325 }
3326 
3327 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3328   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3329 
3330   // We have to copy the entire va_list struct:
3331   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3332   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3333                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3334                        false, true, false, MachinePointerInfo(),
3335                        MachinePointerInfo());
3336 }
3337 
3338 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3339                                                   SelectionDAG &DAG) const {
3340   if (Subtarget.isAIXABI())
3341     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3342 
3343   return Op.getOperand(0);
3344 }
3345 
3346 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3347                                                 SelectionDAG &DAG) const {
3348   if (Subtarget.isAIXABI())
3349     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3350 
3351   SDValue Chain = Op.getOperand(0);
3352   SDValue Trmp = Op.getOperand(1); // trampoline
3353   SDValue FPtr = Op.getOperand(2); // nested function
3354   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3355   SDLoc dl(Op);
3356 
3357   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3358   bool isPPC64 = (PtrVT == MVT::i64);
3359   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3360 
3361   TargetLowering::ArgListTy Args;
3362   TargetLowering::ArgListEntry Entry;
3363 
3364   Entry.Ty = IntPtrTy;
3365   Entry.Node = Trmp; Args.push_back(Entry);
3366 
3367   // TrampSize == (isPPC64 ? 48 : 40);
3368   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3369                                isPPC64 ? MVT::i64 : MVT::i32);
3370   Args.push_back(Entry);
3371 
3372   Entry.Node = FPtr; Args.push_back(Entry);
3373   Entry.Node = Nest; Args.push_back(Entry);
3374 
3375   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3376   TargetLowering::CallLoweringInfo CLI(DAG);
3377   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3378       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3379       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3380 
3381   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3382   return CallResult.second;
3383 }
3384 
3385 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3386   MachineFunction &MF = DAG.getMachineFunction();
3387   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3388   EVT PtrVT = getPointerTy(MF.getDataLayout());
3389 
3390   SDLoc dl(Op);
3391 
3392   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3393     // vastart just stores the address of the VarArgsFrameIndex slot into the
3394     // memory location argument.
3395     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3396     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3397     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3398                         MachinePointerInfo(SV));
3399   }
3400 
3401   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3402   // We suppose the given va_list is already allocated.
3403   //
3404   // typedef struct {
3405   //  char gpr;     /* index into the array of 8 GPRs
3406   //                 * stored in the register save area
3407   //                 * gpr=0 corresponds to r3,
3408   //                 * gpr=1 to r4, etc.
3409   //                 */
3410   //  char fpr;     /* index into the array of 8 FPRs
3411   //                 * stored in the register save area
3412   //                 * fpr=0 corresponds to f1,
3413   //                 * fpr=1 to f2, etc.
3414   //                 */
3415   //  char *overflow_arg_area;
3416   //                /* location on stack that holds
3417   //                 * the next overflow argument
3418   //                 */
3419   //  char *reg_save_area;
3420   //               /* where r3:r10 and f1:f8 (if saved)
3421   //                * are stored
3422   //                */
3423   // } va_list[1];
3424 
3425   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3426   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3427   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3428                                             PtrVT);
3429   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3430                                  PtrVT);
3431 
3432   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3433   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3434 
3435   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3436   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3437 
3438   uint64_t FPROffset = 1;
3439   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3440 
3441   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3442 
3443   // Store first byte : number of int regs
3444   SDValue firstStore =
3445       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3446                         MachinePointerInfo(SV), MVT::i8);
3447   uint64_t nextOffset = FPROffset;
3448   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3449                                   ConstFPROffset);
3450 
3451   // Store second byte : number of float regs
3452   SDValue secondStore =
3453       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3454                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3455   nextOffset += StackOffset;
3456   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3457 
3458   // Store second word : arguments given on stack
3459   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3460                                     MachinePointerInfo(SV, nextOffset));
3461   nextOffset += FrameOffset;
3462   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3463 
3464   // Store third word : arguments given in registers
3465   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3466                       MachinePointerInfo(SV, nextOffset));
3467 }
3468 
3469 /// FPR - The set of FP registers that should be allocated for arguments
3470 /// on Darwin and AIX.
3471 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3472                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3473                                 PPC::F11, PPC::F12, PPC::F13};
3474 
3475 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3476 /// the stack.
3477 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3478                                        unsigned PtrByteSize) {
3479   unsigned ArgSize = ArgVT.getStoreSize();
3480   if (Flags.isByVal())
3481     ArgSize = Flags.getByValSize();
3482 
3483   // Round up to multiples of the pointer size, except for array members,
3484   // which are always packed.
3485   if (!Flags.isInConsecutiveRegs())
3486     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3487 
3488   return ArgSize;
3489 }
3490 
3491 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3492 /// on the stack.
3493 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3494                                          ISD::ArgFlagsTy Flags,
3495                                          unsigned PtrByteSize) {
3496   Align Alignment(PtrByteSize);
3497 
3498   // Altivec parameters are padded to a 16 byte boundary.
3499   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3500       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3501       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3502       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3503     Alignment = Align(16);
3504 
3505   // ByVal parameters are aligned as requested.
3506   if (Flags.isByVal()) {
3507     auto BVAlign = Flags.getNonZeroByValAlign();
3508     if (BVAlign > PtrByteSize) {
3509       if (BVAlign.value() % PtrByteSize != 0)
3510         llvm_unreachable(
3511             "ByVal alignment is not a multiple of the pointer size");
3512 
3513       Alignment = BVAlign;
3514     }
3515   }
3516 
3517   // Array members are always packed to their original alignment.
3518   if (Flags.isInConsecutiveRegs()) {
3519     // If the array member was split into multiple registers, the first
3520     // needs to be aligned to the size of the full type.  (Except for
3521     // ppcf128, which is only aligned as its f64 components.)
3522     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3523       Alignment = Align(OrigVT.getStoreSize());
3524     else
3525       Alignment = Align(ArgVT.getStoreSize());
3526   }
3527 
3528   return Alignment;
3529 }
3530 
3531 /// CalculateStackSlotUsed - Return whether this argument will use its
3532 /// stack slot (instead of being passed in registers).  ArgOffset,
3533 /// AvailableFPRs, and AvailableVRs must hold the current argument
3534 /// position, and will be updated to account for this argument.
3535 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3536                                    unsigned PtrByteSize, unsigned LinkageSize,
3537                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3538                                    unsigned &AvailableFPRs,
3539                                    unsigned &AvailableVRs) {
3540   bool UseMemory = false;
3541 
3542   // Respect alignment of argument on the stack.
3543   Align Alignment =
3544       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3545   ArgOffset = alignTo(ArgOffset, Alignment);
3546   // If there's no space left in the argument save area, we must
3547   // use memory (this check also catches zero-sized arguments).
3548   if (ArgOffset >= LinkageSize + ParamAreaSize)
3549     UseMemory = true;
3550 
3551   // Allocate argument on the stack.
3552   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3553   if (Flags.isInConsecutiveRegsLast())
3554     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3555   // If we overran the argument save area, we must use memory
3556   // (this check catches arguments passed partially in memory)
3557   if (ArgOffset > LinkageSize + ParamAreaSize)
3558     UseMemory = true;
3559 
3560   // However, if the argument is actually passed in an FPR or a VR,
3561   // we don't use memory after all.
3562   if (!Flags.isByVal()) {
3563     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3564       if (AvailableFPRs > 0) {
3565         --AvailableFPRs;
3566         return false;
3567       }
3568     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3569         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3570         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3571         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3572       if (AvailableVRs > 0) {
3573         --AvailableVRs;
3574         return false;
3575       }
3576   }
3577 
3578   return UseMemory;
3579 }
3580 
3581 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3582 /// ensure minimum alignment required for target.
3583 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3584                                      unsigned NumBytes) {
3585   return alignTo(NumBytes, Lowering->getStackAlign());
3586 }
3587 
3588 SDValue PPCTargetLowering::LowerFormalArguments(
3589     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3590     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3591     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3592   if (Subtarget.isAIXABI())
3593     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3594                                     InVals);
3595   if (Subtarget.is64BitELFABI())
3596     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3597                                        InVals);
3598   if (Subtarget.is32BitELFABI())
3599     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3600                                        InVals);
3601 
3602   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3603                                      InVals);
3604 }
3605 
3606 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3607     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3608     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3609     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3610 
3611   // 32-bit SVR4 ABI Stack Frame Layout:
3612   //              +-----------------------------------+
3613   //        +-->  |            Back chain             |
3614   //        |     +-----------------------------------+
3615   //        |     | Floating-point register save area |
3616   //        |     +-----------------------------------+
3617   //        |     |    General register save area     |
3618   //        |     +-----------------------------------+
3619   //        |     |          CR save word             |
3620   //        |     +-----------------------------------+
3621   //        |     |         VRSAVE save word          |
3622   //        |     +-----------------------------------+
3623   //        |     |         Alignment padding         |
3624   //        |     +-----------------------------------+
3625   //        |     |     Vector register save area     |
3626   //        |     +-----------------------------------+
3627   //        |     |       Local variable space        |
3628   //        |     +-----------------------------------+
3629   //        |     |        Parameter list area        |
3630   //        |     +-----------------------------------+
3631   //        |     |           LR save word            |
3632   //        |     +-----------------------------------+
3633   // SP-->  +---  |            Back chain             |
3634   //              +-----------------------------------+
3635   //
3636   // Specifications:
3637   //   System V Application Binary Interface PowerPC Processor Supplement
3638   //   AltiVec Technology Programming Interface Manual
3639 
3640   MachineFunction &MF = DAG.getMachineFunction();
3641   MachineFrameInfo &MFI = MF.getFrameInfo();
3642   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3643 
3644   EVT PtrVT = getPointerTy(MF.getDataLayout());
3645   // Potential tail calls could cause overwriting of argument stack slots.
3646   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3647                        (CallConv == CallingConv::Fast));
3648   const Align PtrAlign(4);
3649 
3650   // Assign locations to all of the incoming arguments.
3651   SmallVector<CCValAssign, 16> ArgLocs;
3652   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3653                  *DAG.getContext());
3654 
3655   // Reserve space for the linkage area on the stack.
3656   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3657   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3658   if (useSoftFloat())
3659     CCInfo.PreAnalyzeFormalArguments(Ins);
3660 
3661   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3662   CCInfo.clearWasPPCF128();
3663 
3664   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3665     CCValAssign &VA = ArgLocs[i];
3666 
3667     // Arguments stored in registers.
3668     if (VA.isRegLoc()) {
3669       const TargetRegisterClass *RC;
3670       EVT ValVT = VA.getValVT();
3671 
3672       switch (ValVT.getSimpleVT().SimpleTy) {
3673         default:
3674           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3675         case MVT::i1:
3676         case MVT::i32:
3677           RC = &PPC::GPRCRegClass;
3678           break;
3679         case MVT::f32:
3680           if (Subtarget.hasP8Vector())
3681             RC = &PPC::VSSRCRegClass;
3682           else if (Subtarget.hasSPE())
3683             RC = &PPC::GPRCRegClass;
3684           else
3685             RC = &PPC::F4RCRegClass;
3686           break;
3687         case MVT::f64:
3688           if (Subtarget.hasVSX())
3689             RC = &PPC::VSFRCRegClass;
3690           else if (Subtarget.hasSPE())
3691             // SPE passes doubles in GPR pairs.
3692             RC = &PPC::GPRCRegClass;
3693           else
3694             RC = &PPC::F8RCRegClass;
3695           break;
3696         case MVT::v16i8:
3697         case MVT::v8i16:
3698         case MVT::v4i32:
3699           RC = &PPC::VRRCRegClass;
3700           break;
3701         case MVT::v4f32:
3702           RC = &PPC::VRRCRegClass;
3703           break;
3704         case MVT::v2f64:
3705         case MVT::v2i64:
3706           RC = &PPC::VRRCRegClass;
3707           break;
3708       }
3709 
3710       SDValue ArgValue;
3711       // Transform the arguments stored in physical registers into
3712       // virtual ones.
3713       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3714         assert(i + 1 < e && "No second half of double precision argument");
3715         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3716         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3717         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3718         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3719         if (!Subtarget.isLittleEndian())
3720           std::swap (ArgValueLo, ArgValueHi);
3721         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3722                                ArgValueHi);
3723       } else {
3724         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3725         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3726                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3727         if (ValVT == MVT::i1)
3728           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3729       }
3730 
3731       InVals.push_back(ArgValue);
3732     } else {
3733       // Argument stored in memory.
3734       assert(VA.isMemLoc());
3735 
3736       // Get the extended size of the argument type in stack
3737       unsigned ArgSize = VA.getLocVT().getStoreSize();
3738       // Get the actual size of the argument type
3739       unsigned ObjSize = VA.getValVT().getStoreSize();
3740       unsigned ArgOffset = VA.getLocMemOffset();
3741       // Stack objects in PPC32 are right justified.
3742       ArgOffset += ArgSize - ObjSize;
3743       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3744 
3745       // Create load nodes to retrieve arguments from the stack.
3746       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3747       InVals.push_back(
3748           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3749     }
3750   }
3751 
3752   // Assign locations to all of the incoming aggregate by value arguments.
3753   // Aggregates passed by value are stored in the local variable space of the
3754   // caller's stack frame, right above the parameter list area.
3755   SmallVector<CCValAssign, 16> ByValArgLocs;
3756   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3757                       ByValArgLocs, *DAG.getContext());
3758 
3759   // Reserve stack space for the allocations in CCInfo.
3760   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3761 
3762   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3763 
3764   // Area that is at least reserved in the caller of this function.
3765   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3766   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3767 
3768   // Set the size that is at least reserved in caller of this function.  Tail
3769   // call optimized function's reserved stack space needs to be aligned so that
3770   // taking the difference between two stack areas will result in an aligned
3771   // stack.
3772   MinReservedArea =
3773       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3774   FuncInfo->setMinReservedArea(MinReservedArea);
3775 
3776   SmallVector<SDValue, 8> MemOps;
3777 
3778   // If the function takes variable number of arguments, make a frame index for
3779   // the start of the first vararg value... for expansion of llvm.va_start.
3780   if (isVarArg) {
3781     static const MCPhysReg GPArgRegs[] = {
3782       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3783       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3784     };
3785     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3786 
3787     static const MCPhysReg FPArgRegs[] = {
3788       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3789       PPC::F8
3790     };
3791     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3792 
3793     if (useSoftFloat() || hasSPE())
3794        NumFPArgRegs = 0;
3795 
3796     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3797     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3798 
3799     // Make room for NumGPArgRegs and NumFPArgRegs.
3800     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3801                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3802 
3803     FuncInfo->setVarArgsStackOffset(
3804       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3805                             CCInfo.getNextStackOffset(), true));
3806 
3807     FuncInfo->setVarArgsFrameIndex(
3808         MFI.CreateStackObject(Depth, Align(8), false));
3809     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3810 
3811     // The fixed integer arguments of a variadic function are stored to the
3812     // VarArgsFrameIndex on the stack so that they may be loaded by
3813     // dereferencing the result of va_next.
3814     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3815       // Get an existing live-in vreg, or add a new one.
3816       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3817       if (!VReg)
3818         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3819 
3820       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3821       SDValue Store =
3822           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3823       MemOps.push_back(Store);
3824       // Increment the address by four for the next argument to store
3825       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3826       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3827     }
3828 
3829     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3830     // is set.
3831     // The double arguments are stored to the VarArgsFrameIndex
3832     // on the stack.
3833     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3834       // Get an existing live-in vreg, or add a new one.
3835       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3836       if (!VReg)
3837         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3838 
3839       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3840       SDValue Store =
3841           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3842       MemOps.push_back(Store);
3843       // Increment the address by eight for the next argument to store
3844       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3845                                          PtrVT);
3846       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3847     }
3848   }
3849 
3850   if (!MemOps.empty())
3851     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3852 
3853   return Chain;
3854 }
3855 
3856 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3857 // value to MVT::i64 and then truncate to the correct register size.
3858 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3859                                              EVT ObjectVT, SelectionDAG &DAG,
3860                                              SDValue ArgVal,
3861                                              const SDLoc &dl) const {
3862   if (Flags.isSExt())
3863     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3864                          DAG.getValueType(ObjectVT));
3865   else if (Flags.isZExt())
3866     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3867                          DAG.getValueType(ObjectVT));
3868 
3869   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3870 }
3871 
3872 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3873     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3874     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3875     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3876   // TODO: add description of PPC stack frame format, or at least some docs.
3877   //
3878   bool isELFv2ABI = Subtarget.isELFv2ABI();
3879   bool isLittleEndian = Subtarget.isLittleEndian();
3880   MachineFunction &MF = DAG.getMachineFunction();
3881   MachineFrameInfo &MFI = MF.getFrameInfo();
3882   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3883 
3884   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3885          "fastcc not supported on varargs functions");
3886 
3887   EVT PtrVT = getPointerTy(MF.getDataLayout());
3888   // Potential tail calls could cause overwriting of argument stack slots.
3889   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3890                        (CallConv == CallingConv::Fast));
3891   unsigned PtrByteSize = 8;
3892   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3893 
3894   static const MCPhysReg GPR[] = {
3895     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3896     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3897   };
3898   static const MCPhysReg VR[] = {
3899     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3900     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3901   };
3902 
3903   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3904   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3905   const unsigned Num_VR_Regs  = array_lengthof(VR);
3906 
3907   // Do a first pass over the arguments to determine whether the ABI
3908   // guarantees that our caller has allocated the parameter save area
3909   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3910   // in the ELFv2 ABI, it is true if this is a vararg function or if
3911   // any parameter is located in a stack slot.
3912 
3913   bool HasParameterArea = !isELFv2ABI || isVarArg;
3914   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3915   unsigned NumBytes = LinkageSize;
3916   unsigned AvailableFPRs = Num_FPR_Regs;
3917   unsigned AvailableVRs = Num_VR_Regs;
3918   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3919     if (Ins[i].Flags.isNest())
3920       continue;
3921 
3922     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3923                                PtrByteSize, LinkageSize, ParamAreaSize,
3924                                NumBytes, AvailableFPRs, AvailableVRs))
3925       HasParameterArea = true;
3926   }
3927 
3928   // Add DAG nodes to load the arguments or copy them out of registers.  On
3929   // entry to a function on PPC, the arguments start after the linkage area,
3930   // although the first ones are often in registers.
3931 
3932   unsigned ArgOffset = LinkageSize;
3933   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3934   SmallVector<SDValue, 8> MemOps;
3935   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3936   unsigned CurArgIdx = 0;
3937   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3938     SDValue ArgVal;
3939     bool needsLoad = false;
3940     EVT ObjectVT = Ins[ArgNo].VT;
3941     EVT OrigVT = Ins[ArgNo].ArgVT;
3942     unsigned ObjSize = ObjectVT.getStoreSize();
3943     unsigned ArgSize = ObjSize;
3944     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3945     if (Ins[ArgNo].isOrigArg()) {
3946       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3947       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3948     }
3949     // We re-align the argument offset for each argument, except when using the
3950     // fast calling convention, when we need to make sure we do that only when
3951     // we'll actually use a stack slot.
3952     unsigned CurArgOffset;
3953     Align Alignment;
3954     auto ComputeArgOffset = [&]() {
3955       /* Respect alignment of argument on the stack.  */
3956       Alignment =
3957           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3958       ArgOffset = alignTo(ArgOffset, Alignment);
3959       CurArgOffset = ArgOffset;
3960     };
3961 
3962     if (CallConv != CallingConv::Fast) {
3963       ComputeArgOffset();
3964 
3965       /* Compute GPR index associated with argument offset.  */
3966       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3967       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3968     }
3969 
3970     // FIXME the codegen can be much improved in some cases.
3971     // We do not have to keep everything in memory.
3972     if (Flags.isByVal()) {
3973       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3974 
3975       if (CallConv == CallingConv::Fast)
3976         ComputeArgOffset();
3977 
3978       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3979       ObjSize = Flags.getByValSize();
3980       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3981       // Empty aggregate parameters do not take up registers.  Examples:
3982       //   struct { } a;
3983       //   union  { } b;
3984       //   int c[0];
3985       // etc.  However, we have to provide a place-holder in InVals, so
3986       // pretend we have an 8-byte item at the current address for that
3987       // purpose.
3988       if (!ObjSize) {
3989         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3990         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3991         InVals.push_back(FIN);
3992         continue;
3993       }
3994 
3995       // Create a stack object covering all stack doublewords occupied
3996       // by the argument.  If the argument is (fully or partially) on
3997       // the stack, or if the argument is fully in registers but the
3998       // caller has allocated the parameter save anyway, we can refer
3999       // directly to the caller's stack frame.  Otherwise, create a
4000       // local copy in our own frame.
4001       int FI;
4002       if (HasParameterArea ||
4003           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4004         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4005       else
4006         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4007       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4008 
4009       // Handle aggregates smaller than 8 bytes.
4010       if (ObjSize < PtrByteSize) {
4011         // The value of the object is its address, which differs from the
4012         // address of the enclosing doubleword on big-endian systems.
4013         SDValue Arg = FIN;
4014         if (!isLittleEndian) {
4015           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4016           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4017         }
4018         InVals.push_back(Arg);
4019 
4020         if (GPR_idx != Num_GPR_Regs) {
4021           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4022           FuncInfo->addLiveInAttr(VReg, Flags);
4023           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4024           SDValue Store;
4025 
4026           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4027             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4028                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4029             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4030                                       MachinePointerInfo(&*FuncArg), ObjType);
4031           } else {
4032             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4033             // store the whole register as-is to the parameter save area
4034             // slot.
4035             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4036                                  MachinePointerInfo(&*FuncArg));
4037           }
4038 
4039           MemOps.push_back(Store);
4040         }
4041         // Whether we copied from a register or not, advance the offset
4042         // into the parameter save area by a full doubleword.
4043         ArgOffset += PtrByteSize;
4044         continue;
4045       }
4046 
4047       // The value of the object is its address, which is the address of
4048       // its first stack doubleword.
4049       InVals.push_back(FIN);
4050 
4051       // Store whatever pieces of the object are in registers to memory.
4052       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4053         if (GPR_idx == Num_GPR_Regs)
4054           break;
4055 
4056         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4057         FuncInfo->addLiveInAttr(VReg, Flags);
4058         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4059         SDValue Addr = FIN;
4060         if (j) {
4061           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4062           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4063         }
4064         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4065                                      MachinePointerInfo(&*FuncArg, j));
4066         MemOps.push_back(Store);
4067         ++GPR_idx;
4068       }
4069       ArgOffset += ArgSize;
4070       continue;
4071     }
4072 
4073     switch (ObjectVT.getSimpleVT().SimpleTy) {
4074     default: llvm_unreachable("Unhandled argument type!");
4075     case MVT::i1:
4076     case MVT::i32:
4077     case MVT::i64:
4078       if (Flags.isNest()) {
4079         // The 'nest' parameter, if any, is passed in R11.
4080         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4081         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4082 
4083         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4084           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4085 
4086         break;
4087       }
4088 
4089       // These can be scalar arguments or elements of an integer array type
4090       // passed directly.  Clang may use those instead of "byval" aggregate
4091       // types to avoid forcing arguments to memory unnecessarily.
4092       if (GPR_idx != Num_GPR_Regs) {
4093         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4094         FuncInfo->addLiveInAttr(VReg, Flags);
4095         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4096 
4097         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4098           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4099           // value to MVT::i64 and then truncate to the correct register size.
4100           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4101       } else {
4102         if (CallConv == CallingConv::Fast)
4103           ComputeArgOffset();
4104 
4105         needsLoad = true;
4106         ArgSize = PtrByteSize;
4107       }
4108       if (CallConv != CallingConv::Fast || needsLoad)
4109         ArgOffset += 8;
4110       break;
4111 
4112     case MVT::f32:
4113     case MVT::f64:
4114       // These can be scalar arguments or elements of a float array type
4115       // passed directly.  The latter are used to implement ELFv2 homogenous
4116       // float aggregates.
4117       if (FPR_idx != Num_FPR_Regs) {
4118         unsigned VReg;
4119 
4120         if (ObjectVT == MVT::f32)
4121           VReg = MF.addLiveIn(FPR[FPR_idx],
4122                               Subtarget.hasP8Vector()
4123                                   ? &PPC::VSSRCRegClass
4124                                   : &PPC::F4RCRegClass);
4125         else
4126           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4127                                                 ? &PPC::VSFRCRegClass
4128                                                 : &PPC::F8RCRegClass);
4129 
4130         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4131         ++FPR_idx;
4132       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4133         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4134         // once we support fp <-> gpr moves.
4135 
4136         // This can only ever happen in the presence of f32 array types,
4137         // since otherwise we never run out of FPRs before running out
4138         // of GPRs.
4139         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4140         FuncInfo->addLiveInAttr(VReg, Flags);
4141         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4142 
4143         if (ObjectVT == MVT::f32) {
4144           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4145             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4146                                  DAG.getConstant(32, dl, MVT::i32));
4147           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4148         }
4149 
4150         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4151       } else {
4152         if (CallConv == CallingConv::Fast)
4153           ComputeArgOffset();
4154 
4155         needsLoad = true;
4156       }
4157 
4158       // When passing an array of floats, the array occupies consecutive
4159       // space in the argument area; only round up to the next doubleword
4160       // at the end of the array.  Otherwise, each float takes 8 bytes.
4161       if (CallConv != CallingConv::Fast || needsLoad) {
4162         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4163         ArgOffset += ArgSize;
4164         if (Flags.isInConsecutiveRegsLast())
4165           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4166       }
4167       break;
4168     case MVT::v4f32:
4169     case MVT::v4i32:
4170     case MVT::v8i16:
4171     case MVT::v16i8:
4172     case MVT::v2f64:
4173     case MVT::v2i64:
4174     case MVT::v1i128:
4175     case MVT::f128:
4176       // These can be scalar arguments or elements of a vector array type
4177       // passed directly.  The latter are used to implement ELFv2 homogenous
4178       // vector aggregates.
4179       if (VR_idx != Num_VR_Regs) {
4180         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4181         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4182         ++VR_idx;
4183       } else {
4184         if (CallConv == CallingConv::Fast)
4185           ComputeArgOffset();
4186         needsLoad = true;
4187       }
4188       if (CallConv != CallingConv::Fast || needsLoad)
4189         ArgOffset += 16;
4190       break;
4191     }
4192 
4193     // We need to load the argument to a virtual register if we determined
4194     // above that we ran out of physical registers of the appropriate type.
4195     if (needsLoad) {
4196       if (ObjSize < ArgSize && !isLittleEndian)
4197         CurArgOffset += ArgSize - ObjSize;
4198       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4199       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4200       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4201     }
4202 
4203     InVals.push_back(ArgVal);
4204   }
4205 
4206   // Area that is at least reserved in the caller of this function.
4207   unsigned MinReservedArea;
4208   if (HasParameterArea)
4209     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4210   else
4211     MinReservedArea = LinkageSize;
4212 
4213   // Set the size that is at least reserved in caller of this function.  Tail
4214   // call optimized functions' reserved stack space needs to be aligned so that
4215   // taking the difference between two stack areas will result in an aligned
4216   // stack.
4217   MinReservedArea =
4218       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4219   FuncInfo->setMinReservedArea(MinReservedArea);
4220 
4221   // If the function takes variable number of arguments, make a frame index for
4222   // the start of the first vararg value... for expansion of llvm.va_start.
4223   // On ELFv2ABI spec, it writes:
4224   // C programs that are intended to be *portable* across different compilers
4225   // and architectures must use the header file <stdarg.h> to deal with variable
4226   // argument lists.
4227   if (isVarArg && MFI.hasVAStart()) {
4228     int Depth = ArgOffset;
4229 
4230     FuncInfo->setVarArgsFrameIndex(
4231       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4232     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4233 
4234     // If this function is vararg, store any remaining integer argument regs
4235     // to their spots on the stack so that they may be loaded by dereferencing
4236     // the result of va_next.
4237     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4238          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4239       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4240       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4241       SDValue Store =
4242           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4243       MemOps.push_back(Store);
4244       // Increment the address by four for the next argument to store
4245       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4246       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4247     }
4248   }
4249 
4250   if (!MemOps.empty())
4251     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4252 
4253   return Chain;
4254 }
4255 
4256 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4257     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4258     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4259     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4260   // TODO: add description of PPC stack frame format, or at least some docs.
4261   //
4262   MachineFunction &MF = DAG.getMachineFunction();
4263   MachineFrameInfo &MFI = MF.getFrameInfo();
4264   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4265 
4266   EVT PtrVT = getPointerTy(MF.getDataLayout());
4267   bool isPPC64 = PtrVT == MVT::i64;
4268   // Potential tail calls could cause overwriting of argument stack slots.
4269   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4270                        (CallConv == CallingConv::Fast));
4271   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4272   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4273   unsigned ArgOffset = LinkageSize;
4274   // Area that is at least reserved in caller of this function.
4275   unsigned MinReservedArea = ArgOffset;
4276 
4277   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4278     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4279     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4280   };
4281   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4282     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4283     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4284   };
4285   static const MCPhysReg VR[] = {
4286     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4287     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4288   };
4289 
4290   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4291   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4292   const unsigned Num_VR_Regs  = array_lengthof( VR);
4293 
4294   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4295 
4296   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4297 
4298   // In 32-bit non-varargs functions, the stack space for vectors is after the
4299   // stack space for non-vectors.  We do not use this space unless we have
4300   // too many vectors to fit in registers, something that only occurs in
4301   // constructed examples:), but we have to walk the arglist to figure
4302   // that out...for the pathological case, compute VecArgOffset as the
4303   // start of the vector parameter area.  Computing VecArgOffset is the
4304   // entire point of the following loop.
4305   unsigned VecArgOffset = ArgOffset;
4306   if (!isVarArg && !isPPC64) {
4307     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4308          ++ArgNo) {
4309       EVT ObjectVT = Ins[ArgNo].VT;
4310       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4311 
4312       if (Flags.isByVal()) {
4313         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4314         unsigned ObjSize = Flags.getByValSize();
4315         unsigned ArgSize =
4316                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4317         VecArgOffset += ArgSize;
4318         continue;
4319       }
4320 
4321       switch(ObjectVT.getSimpleVT().SimpleTy) {
4322       default: llvm_unreachable("Unhandled argument type!");
4323       case MVT::i1:
4324       case MVT::i32:
4325       case MVT::f32:
4326         VecArgOffset += 4;
4327         break;
4328       case MVT::i64:  // PPC64
4329       case MVT::f64:
4330         // FIXME: We are guaranteed to be !isPPC64 at this point.
4331         // Does MVT::i64 apply?
4332         VecArgOffset += 8;
4333         break;
4334       case MVT::v4f32:
4335       case MVT::v4i32:
4336       case MVT::v8i16:
4337       case MVT::v16i8:
4338         // Nothing to do, we're only looking at Nonvector args here.
4339         break;
4340       }
4341     }
4342   }
4343   // We've found where the vector parameter area in memory is.  Skip the
4344   // first 12 parameters; these don't use that memory.
4345   VecArgOffset = ((VecArgOffset+15)/16)*16;
4346   VecArgOffset += 12*16;
4347 
4348   // Add DAG nodes to load the arguments or copy them out of registers.  On
4349   // entry to a function on PPC, the arguments start after the linkage area,
4350   // although the first ones are often in registers.
4351 
4352   SmallVector<SDValue, 8> MemOps;
4353   unsigned nAltivecParamsAtEnd = 0;
4354   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4355   unsigned CurArgIdx = 0;
4356   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4357     SDValue ArgVal;
4358     bool needsLoad = false;
4359     EVT ObjectVT = Ins[ArgNo].VT;
4360     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4361     unsigned ArgSize = ObjSize;
4362     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4363     if (Ins[ArgNo].isOrigArg()) {
4364       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4365       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4366     }
4367     unsigned CurArgOffset = ArgOffset;
4368 
4369     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4370     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4371         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4372       if (isVarArg || isPPC64) {
4373         MinReservedArea = ((MinReservedArea+15)/16)*16;
4374         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4375                                                   Flags,
4376                                                   PtrByteSize);
4377       } else  nAltivecParamsAtEnd++;
4378     } else
4379       // Calculate min reserved area.
4380       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4381                                                 Flags,
4382                                                 PtrByteSize);
4383 
4384     // FIXME the codegen can be much improved in some cases.
4385     // We do not have to keep everything in memory.
4386     if (Flags.isByVal()) {
4387       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4388 
4389       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4390       ObjSize = Flags.getByValSize();
4391       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4392       // Objects of size 1 and 2 are right justified, everything else is
4393       // left justified.  This means the memory address is adjusted forwards.
4394       if (ObjSize==1 || ObjSize==2) {
4395         CurArgOffset = CurArgOffset + (4 - ObjSize);
4396       }
4397       // The value of the object is its address.
4398       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4399       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4400       InVals.push_back(FIN);
4401       if (ObjSize==1 || ObjSize==2) {
4402         if (GPR_idx != Num_GPR_Regs) {
4403           unsigned VReg;
4404           if (isPPC64)
4405             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4406           else
4407             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4408           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4409           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4410           SDValue Store =
4411               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4412                                 MachinePointerInfo(&*FuncArg), ObjType);
4413           MemOps.push_back(Store);
4414           ++GPR_idx;
4415         }
4416 
4417         ArgOffset += PtrByteSize;
4418 
4419         continue;
4420       }
4421       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4422         // Store whatever pieces of the object are in registers
4423         // to memory.  ArgOffset will be the address of the beginning
4424         // of the object.
4425         if (GPR_idx != Num_GPR_Regs) {
4426           unsigned VReg;
4427           if (isPPC64)
4428             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4429           else
4430             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4431           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4432           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4433           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4434           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4435                                        MachinePointerInfo(&*FuncArg, j));
4436           MemOps.push_back(Store);
4437           ++GPR_idx;
4438           ArgOffset += PtrByteSize;
4439         } else {
4440           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4441           break;
4442         }
4443       }
4444       continue;
4445     }
4446 
4447     switch (ObjectVT.getSimpleVT().SimpleTy) {
4448     default: llvm_unreachable("Unhandled argument type!");
4449     case MVT::i1:
4450     case MVT::i32:
4451       if (!isPPC64) {
4452         if (GPR_idx != Num_GPR_Regs) {
4453           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4454           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4455 
4456           if (ObjectVT == MVT::i1)
4457             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4458 
4459           ++GPR_idx;
4460         } else {
4461           needsLoad = true;
4462           ArgSize = PtrByteSize;
4463         }
4464         // All int arguments reserve stack space in the Darwin ABI.
4465         ArgOffset += PtrByteSize;
4466         break;
4467       }
4468       LLVM_FALLTHROUGH;
4469     case MVT::i64:  // PPC64
4470       if (GPR_idx != Num_GPR_Regs) {
4471         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4472         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4473 
4474         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4475           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4476           // value to MVT::i64 and then truncate to the correct register size.
4477           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4478 
4479         ++GPR_idx;
4480       } else {
4481         needsLoad = true;
4482         ArgSize = PtrByteSize;
4483       }
4484       // All int arguments reserve stack space in the Darwin ABI.
4485       ArgOffset += 8;
4486       break;
4487 
4488     case MVT::f32:
4489     case MVT::f64:
4490       // Every 4 bytes of argument space consumes one of the GPRs available for
4491       // argument passing.
4492       if (GPR_idx != Num_GPR_Regs) {
4493         ++GPR_idx;
4494         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4495           ++GPR_idx;
4496       }
4497       if (FPR_idx != Num_FPR_Regs) {
4498         unsigned VReg;
4499 
4500         if (ObjectVT == MVT::f32)
4501           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4502         else
4503           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4504 
4505         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4506         ++FPR_idx;
4507       } else {
4508         needsLoad = true;
4509       }
4510 
4511       // All FP arguments reserve stack space in the Darwin ABI.
4512       ArgOffset += isPPC64 ? 8 : ObjSize;
4513       break;
4514     case MVT::v4f32:
4515     case MVT::v4i32:
4516     case MVT::v8i16:
4517     case MVT::v16i8:
4518       // Note that vector arguments in registers don't reserve stack space,
4519       // except in varargs functions.
4520       if (VR_idx != Num_VR_Regs) {
4521         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4522         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4523         if (isVarArg) {
4524           while ((ArgOffset % 16) != 0) {
4525             ArgOffset += PtrByteSize;
4526             if (GPR_idx != Num_GPR_Regs)
4527               GPR_idx++;
4528           }
4529           ArgOffset += 16;
4530           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4531         }
4532         ++VR_idx;
4533       } else {
4534         if (!isVarArg && !isPPC64) {
4535           // Vectors go after all the nonvectors.
4536           CurArgOffset = VecArgOffset;
4537           VecArgOffset += 16;
4538         } else {
4539           // Vectors are aligned.
4540           ArgOffset = ((ArgOffset+15)/16)*16;
4541           CurArgOffset = ArgOffset;
4542           ArgOffset += 16;
4543         }
4544         needsLoad = true;
4545       }
4546       break;
4547     }
4548 
4549     // We need to load the argument to a virtual register if we determined above
4550     // that we ran out of physical registers of the appropriate type.
4551     if (needsLoad) {
4552       int FI = MFI.CreateFixedObject(ObjSize,
4553                                      CurArgOffset + (ArgSize - ObjSize),
4554                                      isImmutable);
4555       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4556       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4557     }
4558 
4559     InVals.push_back(ArgVal);
4560   }
4561 
4562   // Allow for Altivec parameters at the end, if needed.
4563   if (nAltivecParamsAtEnd) {
4564     MinReservedArea = ((MinReservedArea+15)/16)*16;
4565     MinReservedArea += 16*nAltivecParamsAtEnd;
4566   }
4567 
4568   // Area that is at least reserved in the caller of this function.
4569   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4570 
4571   // Set the size that is at least reserved in caller of this function.  Tail
4572   // call optimized functions' reserved stack space needs to be aligned so that
4573   // taking the difference between two stack areas will result in an aligned
4574   // stack.
4575   MinReservedArea =
4576       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4577   FuncInfo->setMinReservedArea(MinReservedArea);
4578 
4579   // If the function takes variable number of arguments, make a frame index for
4580   // the start of the first vararg value... for expansion of llvm.va_start.
4581   if (isVarArg) {
4582     int Depth = ArgOffset;
4583 
4584     FuncInfo->setVarArgsFrameIndex(
4585       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4586                             Depth, true));
4587     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4588 
4589     // If this function is vararg, store any remaining integer argument regs
4590     // to their spots on the stack so that they may be loaded by dereferencing
4591     // the result of va_next.
4592     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4593       unsigned VReg;
4594 
4595       if (isPPC64)
4596         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4597       else
4598         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4599 
4600       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4601       SDValue Store =
4602           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4603       MemOps.push_back(Store);
4604       // Increment the address by four for the next argument to store
4605       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4606       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4607     }
4608   }
4609 
4610   if (!MemOps.empty())
4611     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4612 
4613   return Chain;
4614 }
4615 
4616 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4617 /// adjusted to accommodate the arguments for the tailcall.
4618 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4619                                    unsigned ParamSize) {
4620 
4621   if (!isTailCall) return 0;
4622 
4623   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4624   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4625   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4626   // Remember only if the new adjustment is bigger.
4627   if (SPDiff < FI->getTailCallSPDelta())
4628     FI->setTailCallSPDelta(SPDiff);
4629 
4630   return SPDiff;
4631 }
4632 
4633 static bool isFunctionGlobalAddress(SDValue Callee);
4634 
4635 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4636                               const TargetMachine &TM) {
4637   // It does not make sense to call callsShareTOCBase() with a caller that
4638   // is PC Relative since PC Relative callers do not have a TOC.
4639 #ifndef NDEBUG
4640   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4641   assert(!STICaller->isUsingPCRelativeCalls() &&
4642          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4643 #endif
4644 
4645   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4646   // don't have enough information to determine if the caller and callee share
4647   // the same  TOC base, so we have to pessimistically assume they don't for
4648   // correctness.
4649   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4650   if (!G)
4651     return false;
4652 
4653   const GlobalValue *GV = G->getGlobal();
4654 
4655   // If the callee is preemptable, then the static linker will use a plt-stub
4656   // which saves the toc to the stack, and needs a nop after the call
4657   // instruction to convert to a toc-restore.
4658   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4659     return false;
4660 
4661   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4662   // We may need a TOC restore in the situation where the caller requires a
4663   // valid TOC but the callee is PC Relative and does not.
4664   const Function *F = dyn_cast<Function>(GV);
4665   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4666 
4667   // If we have an Alias we can try to get the function from there.
4668   if (Alias) {
4669     const GlobalObject *GlobalObj = Alias->getBaseObject();
4670     F = dyn_cast<Function>(GlobalObj);
4671   }
4672 
4673   // If we still have no valid function pointer we do not have enough
4674   // information to determine if the callee uses PC Relative calls so we must
4675   // assume that it does.
4676   if (!F)
4677     return false;
4678 
4679   // If the callee uses PC Relative we cannot guarantee that the callee won't
4680   // clobber the TOC of the caller and so we must assume that the two
4681   // functions do not share a TOC base.
4682   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4683   if (STICallee->isUsingPCRelativeCalls())
4684     return false;
4685 
4686   // The medium and large code models are expected to provide a sufficiently
4687   // large TOC to provide all data addressing needs of a module with a
4688   // single TOC.
4689   if (CodeModel::Medium == TM.getCodeModel() ||
4690       CodeModel::Large == TM.getCodeModel())
4691     return true;
4692 
4693   // Otherwise we need to ensure callee and caller are in the same section,
4694   // since the linker may allocate multiple TOCs, and we don't know which
4695   // sections will belong to the same TOC base.
4696   if (!GV->isStrongDefinitionForLinker())
4697     return false;
4698 
4699   // Any explicitly-specified sections and section prefixes must also match.
4700   // Also, if we're using -ffunction-sections, then each function is always in
4701   // a different section (the same is true for COMDAT functions).
4702   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4703       GV->getSection() != Caller->getSection())
4704     return false;
4705   if (const auto *F = dyn_cast<Function>(GV)) {
4706     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4707       return false;
4708   }
4709 
4710   return true;
4711 }
4712 
4713 static bool
4714 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4715                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4716   assert(Subtarget.is64BitELFABI());
4717 
4718   const unsigned PtrByteSize = 8;
4719   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4720 
4721   static const MCPhysReg GPR[] = {
4722     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4723     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4724   };
4725   static const MCPhysReg VR[] = {
4726     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4727     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4728   };
4729 
4730   const unsigned NumGPRs = array_lengthof(GPR);
4731   const unsigned NumFPRs = 13;
4732   const unsigned NumVRs = array_lengthof(VR);
4733   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4734 
4735   unsigned NumBytes = LinkageSize;
4736   unsigned AvailableFPRs = NumFPRs;
4737   unsigned AvailableVRs = NumVRs;
4738 
4739   for (const ISD::OutputArg& Param : Outs) {
4740     if (Param.Flags.isNest()) continue;
4741 
4742     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4743                                LinkageSize, ParamAreaSize, NumBytes,
4744                                AvailableFPRs, AvailableVRs))
4745       return true;
4746   }
4747   return false;
4748 }
4749 
4750 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4751   if (CB.arg_size() != CallerFn->arg_size())
4752     return false;
4753 
4754   auto CalleeArgIter = CB.arg_begin();
4755   auto CalleeArgEnd = CB.arg_end();
4756   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4757 
4758   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4759     const Value* CalleeArg = *CalleeArgIter;
4760     const Value* CallerArg = &(*CallerArgIter);
4761     if (CalleeArg == CallerArg)
4762       continue;
4763 
4764     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4765     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4766     //      }
4767     // 1st argument of callee is undef and has the same type as caller.
4768     if (CalleeArg->getType() == CallerArg->getType() &&
4769         isa<UndefValue>(CalleeArg))
4770       continue;
4771 
4772     return false;
4773   }
4774 
4775   return true;
4776 }
4777 
4778 // Returns true if TCO is possible between the callers and callees
4779 // calling conventions.
4780 static bool
4781 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4782                                     CallingConv::ID CalleeCC) {
4783   // Tail calls are possible with fastcc and ccc.
4784   auto isTailCallableCC  = [] (CallingConv::ID CC){
4785       return  CC == CallingConv::C || CC == CallingConv::Fast;
4786   };
4787   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4788     return false;
4789 
4790   // We can safely tail call both fastcc and ccc callees from a c calling
4791   // convention caller. If the caller is fastcc, we may have less stack space
4792   // than a non-fastcc caller with the same signature so disable tail-calls in
4793   // that case.
4794   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4795 }
4796 
4797 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4798     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4799     const SmallVectorImpl<ISD::OutputArg> &Outs,
4800     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4801   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4802 
4803   if (DisableSCO && !TailCallOpt) return false;
4804 
4805   // Variadic argument functions are not supported.
4806   if (isVarArg) return false;
4807 
4808   auto &Caller = DAG.getMachineFunction().getFunction();
4809   // Check that the calling conventions are compatible for tco.
4810   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4811     return false;
4812 
4813   // Caller contains any byval parameter is not supported.
4814   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4815     return false;
4816 
4817   // Callee contains any byval parameter is not supported, too.
4818   // Note: This is a quick work around, because in some cases, e.g.
4819   // caller's stack size > callee's stack size, we are still able to apply
4820   // sibling call optimization. For example, gcc is able to do SCO for caller1
4821   // in the following example, but not for caller2.
4822   //   struct test {
4823   //     long int a;
4824   //     char ary[56];
4825   //   } gTest;
4826   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4827   //     b->a = v.a;
4828   //     return 0;
4829   //   }
4830   //   void caller1(struct test a, struct test c, struct test *b) {
4831   //     callee(gTest, b); }
4832   //   void caller2(struct test *b) { callee(gTest, b); }
4833   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4834     return false;
4835 
4836   // If callee and caller use different calling conventions, we cannot pass
4837   // parameters on stack since offsets for the parameter area may be different.
4838   if (Caller.getCallingConv() != CalleeCC &&
4839       needStackSlotPassParameters(Subtarget, Outs))
4840     return false;
4841 
4842   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4843   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4844   // callee potentially have different TOC bases then we cannot tail call since
4845   // we need to restore the TOC pointer after the call.
4846   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4847   // We cannot guarantee this for indirect calls or calls to external functions.
4848   // When PC-Relative addressing is used, the concept of the TOC is no longer
4849   // applicable so this check is not required.
4850   // Check first for indirect calls.
4851   if (!Subtarget.isUsingPCRelativeCalls() &&
4852       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4853     return false;
4854 
4855   // Check if we share the TOC base.
4856   if (!Subtarget.isUsingPCRelativeCalls() &&
4857       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4858     return false;
4859 
4860   // TCO allows altering callee ABI, so we don't have to check further.
4861   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4862     return true;
4863 
4864   if (DisableSCO) return false;
4865 
4866   // If callee use the same argument list that caller is using, then we can
4867   // apply SCO on this case. If it is not, then we need to check if callee needs
4868   // stack for passing arguments.
4869   // PC Relative tail calls may not have a CallBase.
4870   // If there is no CallBase we cannot verify if we have the same argument
4871   // list so assume that we don't have the same argument list.
4872   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4873       needStackSlotPassParameters(Subtarget, Outs))
4874     return false;
4875   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4876     return false;
4877 
4878   return true;
4879 }
4880 
4881 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4882 /// for tail call optimization. Targets which want to do tail call
4883 /// optimization should implement this function.
4884 bool
4885 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4886                                                      CallingConv::ID CalleeCC,
4887                                                      bool isVarArg,
4888                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4889                                                      SelectionDAG& DAG) const {
4890   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4891     return false;
4892 
4893   // Variable argument functions are not supported.
4894   if (isVarArg)
4895     return false;
4896 
4897   MachineFunction &MF = DAG.getMachineFunction();
4898   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4899   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4900     // Functions containing by val parameters are not supported.
4901     for (unsigned i = 0; i != Ins.size(); i++) {
4902        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4903        if (Flags.isByVal()) return false;
4904     }
4905 
4906     // Non-PIC/GOT tail calls are supported.
4907     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4908       return true;
4909 
4910     // At the moment we can only do local tail calls (in same module, hidden
4911     // or protected) if we are generating PIC.
4912     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4913       return G->getGlobal()->hasHiddenVisibility()
4914           || G->getGlobal()->hasProtectedVisibility();
4915   }
4916 
4917   return false;
4918 }
4919 
4920 /// isCallCompatibleAddress - Return the immediate to use if the specified
4921 /// 32-bit value is representable in the immediate field of a BxA instruction.
4922 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4923   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4924   if (!C) return nullptr;
4925 
4926   int Addr = C->getZExtValue();
4927   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4928       SignExtend32<26>(Addr) != Addr)
4929     return nullptr;  // Top 6 bits have to be sext of immediate.
4930 
4931   return DAG
4932       .getConstant(
4933           (int)C->getZExtValue() >> 2, SDLoc(Op),
4934           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4935       .getNode();
4936 }
4937 
4938 namespace {
4939 
4940 struct TailCallArgumentInfo {
4941   SDValue Arg;
4942   SDValue FrameIdxOp;
4943   int FrameIdx = 0;
4944 
4945   TailCallArgumentInfo() = default;
4946 };
4947 
4948 } // end anonymous namespace
4949 
4950 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4951 static void StoreTailCallArgumentsToStackSlot(
4952     SelectionDAG &DAG, SDValue Chain,
4953     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4954     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4955   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4956     SDValue Arg = TailCallArgs[i].Arg;
4957     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4958     int FI = TailCallArgs[i].FrameIdx;
4959     // Store relative to framepointer.
4960     MemOpChains.push_back(DAG.getStore(
4961         Chain, dl, Arg, FIN,
4962         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4963   }
4964 }
4965 
4966 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4967 /// the appropriate stack slot for the tail call optimized function call.
4968 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4969                                              SDValue OldRetAddr, SDValue OldFP,
4970                                              int SPDiff, const SDLoc &dl) {
4971   if (SPDiff) {
4972     // Calculate the new stack slot for the return address.
4973     MachineFunction &MF = DAG.getMachineFunction();
4974     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4975     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4976     bool isPPC64 = Subtarget.isPPC64();
4977     int SlotSize = isPPC64 ? 8 : 4;
4978     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4979     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4980                                                          NewRetAddrLoc, true);
4981     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4982     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4983     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4984                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4985   }
4986   return Chain;
4987 }
4988 
4989 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4990 /// the position of the argument.
4991 static void
4992 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4993                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4994                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4995   int Offset = ArgOffset + SPDiff;
4996   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4997   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4998   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4999   SDValue FIN = DAG.getFrameIndex(FI, VT);
5000   TailCallArgumentInfo Info;
5001   Info.Arg = Arg;
5002   Info.FrameIdxOp = FIN;
5003   Info.FrameIdx = FI;
5004   TailCallArguments.push_back(Info);
5005 }
5006 
5007 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5008 /// stack slot. Returns the chain as result and the loaded frame pointers in
5009 /// LROpOut/FPOpout. Used when tail calling.
5010 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5011     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5012     SDValue &FPOpOut, const SDLoc &dl) const {
5013   if (SPDiff) {
5014     // Load the LR and FP stack slot for later adjusting.
5015     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5016     LROpOut = getReturnAddrFrameIndex(DAG);
5017     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5018     Chain = SDValue(LROpOut.getNode(), 1);
5019   }
5020   return Chain;
5021 }
5022 
5023 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5024 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5025 /// specified by the specific parameter attribute. The copy will be passed as
5026 /// a byval function parameter.
5027 /// Sometimes what we are copying is the end of a larger object, the part that
5028 /// does not fit in registers.
5029 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5030                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5031                                          SelectionDAG &DAG, const SDLoc &dl) {
5032   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5033   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5034                        Flags.getNonZeroByValAlign(), false, false, false,
5035                        MachinePointerInfo(), MachinePointerInfo());
5036 }
5037 
5038 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5039 /// tail calls.
5040 static void LowerMemOpCallTo(
5041     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5042     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5043     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5044     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5045   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5046   if (!isTailCall) {
5047     if (isVector) {
5048       SDValue StackPtr;
5049       if (isPPC64)
5050         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5051       else
5052         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5053       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5054                            DAG.getConstant(ArgOffset, dl, PtrVT));
5055     }
5056     MemOpChains.push_back(
5057         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5058     // Calculate and remember argument location.
5059   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5060                                   TailCallArguments);
5061 }
5062 
5063 static void
5064 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5065                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5066                 SDValue FPOp,
5067                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5068   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5069   // might overwrite each other in case of tail call optimization.
5070   SmallVector<SDValue, 8> MemOpChains2;
5071   // Do not flag preceding copytoreg stuff together with the following stuff.
5072   InFlag = SDValue();
5073   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5074                                     MemOpChains2, dl);
5075   if (!MemOpChains2.empty())
5076     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5077 
5078   // Store the return address to the appropriate stack slot.
5079   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5080 
5081   // Emit callseq_end just before tailcall node.
5082   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5083                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5084   InFlag = Chain.getValue(1);
5085 }
5086 
5087 // Is this global address that of a function that can be called by name? (as
5088 // opposed to something that must hold a descriptor for an indirect call).
5089 static bool isFunctionGlobalAddress(SDValue Callee) {
5090   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5091     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5092         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5093       return false;
5094 
5095     return G->getGlobal()->getValueType()->isFunctionTy();
5096   }
5097 
5098   return false;
5099 }
5100 
5101 SDValue PPCTargetLowering::LowerCallResult(
5102     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5103     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5104     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5105   SmallVector<CCValAssign, 16> RVLocs;
5106   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5107                     *DAG.getContext());
5108 
5109   CCRetInfo.AnalyzeCallResult(
5110       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5111                ? RetCC_PPC_Cold
5112                : RetCC_PPC);
5113 
5114   // Copy all of the result registers out of their specified physreg.
5115   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5116     CCValAssign &VA = RVLocs[i];
5117     assert(VA.isRegLoc() && "Can only return in registers!");
5118 
5119     SDValue Val;
5120 
5121     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5122       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5123                                       InFlag);
5124       Chain = Lo.getValue(1);
5125       InFlag = Lo.getValue(2);
5126       VA = RVLocs[++i]; // skip ahead to next loc
5127       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5128                                       InFlag);
5129       Chain = Hi.getValue(1);
5130       InFlag = Hi.getValue(2);
5131       if (!Subtarget.isLittleEndian())
5132         std::swap (Lo, Hi);
5133       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5134     } else {
5135       Val = DAG.getCopyFromReg(Chain, dl,
5136                                VA.getLocReg(), VA.getLocVT(), InFlag);
5137       Chain = Val.getValue(1);
5138       InFlag = Val.getValue(2);
5139     }
5140 
5141     switch (VA.getLocInfo()) {
5142     default: llvm_unreachable("Unknown loc info!");
5143     case CCValAssign::Full: break;
5144     case CCValAssign::AExt:
5145       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5146       break;
5147     case CCValAssign::ZExt:
5148       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5149                         DAG.getValueType(VA.getValVT()));
5150       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5151       break;
5152     case CCValAssign::SExt:
5153       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5154                         DAG.getValueType(VA.getValVT()));
5155       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5156       break;
5157     }
5158 
5159     InVals.push_back(Val);
5160   }
5161 
5162   return Chain;
5163 }
5164 
5165 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5166                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5167   // PatchPoint calls are not indirect.
5168   if (isPatchPoint)
5169     return false;
5170 
5171   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5172     return false;
5173 
5174   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5175   // becuase the immediate function pointer points to a descriptor instead of
5176   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5177   // pointer immediate points to the global entry point, while the BLA would
5178   // need to jump to the local entry point (see rL211174).
5179   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5180       isBLACompatibleAddress(Callee, DAG))
5181     return false;
5182 
5183   return true;
5184 }
5185 
5186 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5187 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5188   return Subtarget.isAIXABI() ||
5189          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5190 }
5191 
5192 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5193                               const Function &Caller,
5194                               const SDValue &Callee,
5195                               const PPCSubtarget &Subtarget,
5196                               const TargetMachine &TM) {
5197   if (CFlags.IsTailCall)
5198     return PPCISD::TC_RETURN;
5199 
5200   // This is a call through a function pointer.
5201   if (CFlags.IsIndirect) {
5202     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5203     // indirect calls. The save of the caller's TOC pointer to the stack will be
5204     // inserted into the DAG as part of call lowering. The restore of the TOC
5205     // pointer is modeled by using a pseudo instruction for the call opcode that
5206     // represents the 2 instruction sequence of an indirect branch and link,
5207     // immediately followed by a load of the TOC pointer from the the stack save
5208     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5209     // as it is not saved or used.
5210     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5211                                                : PPCISD::BCTRL;
5212   }
5213 
5214   if (Subtarget.isUsingPCRelativeCalls()) {
5215     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5216     return PPCISD::CALL_NOTOC;
5217   }
5218 
5219   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5220   // immediately following the call instruction if the caller and callee may
5221   // have different TOC bases. At link time if the linker determines the calls
5222   // may not share a TOC base, the call is redirected to a trampoline inserted
5223   // by the linker. The trampoline will (among other things) save the callers
5224   // TOC pointer at an ABI designated offset in the linkage area and the linker
5225   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5226   // into gpr2.
5227   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5228     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5229                                                   : PPCISD::CALL_NOP;
5230 
5231   return PPCISD::CALL;
5232 }
5233 
5234 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5235                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5236   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5237     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5238       return SDValue(Dest, 0);
5239 
5240   // Returns true if the callee is local, and false otherwise.
5241   auto isLocalCallee = [&]() {
5242     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5243     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5244     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5245 
5246     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5247            !dyn_cast_or_null<GlobalIFunc>(GV);
5248   };
5249 
5250   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5251   // a static relocation model causes some versions of GNU LD (2.17.50, at
5252   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5253   // built with secure-PLT.
5254   bool UsePlt =
5255       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5256       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5257 
5258   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5259     const TargetMachine &TM = Subtarget.getTargetMachine();
5260     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5261     MCSymbolXCOFF *S =
5262         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5263 
5264     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5265     return DAG.getMCSymbol(S, PtrVT);
5266   };
5267 
5268   if (isFunctionGlobalAddress(Callee)) {
5269     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5270 
5271     if (Subtarget.isAIXABI()) {
5272       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5273       return getAIXFuncEntryPointSymbolSDNode(GV);
5274     }
5275     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5276                                       UsePlt ? PPCII::MO_PLT : 0);
5277   }
5278 
5279   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5280     const char *SymName = S->getSymbol();
5281     if (Subtarget.isAIXABI()) {
5282       // If there exists a user-declared function whose name is the same as the
5283       // ExternalSymbol's, then we pick up the user-declared version.
5284       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5285       if (const Function *F =
5286               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5287         return getAIXFuncEntryPointSymbolSDNode(F);
5288 
5289       // On AIX, direct function calls reference the symbol for the function's
5290       // entry point, which is named by prepending a "." before the function's
5291       // C-linkage name. A Qualname is returned here because an external
5292       // function entry point is a csect with XTY_ER property.
5293       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5294         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5295         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5296             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5297             SectionKind::getMetadata());
5298         return Sec->getQualNameSymbol();
5299       };
5300 
5301       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5302     }
5303     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5304                                        UsePlt ? PPCII::MO_PLT : 0);
5305   }
5306 
5307   // No transformation needed.
5308   assert(Callee.getNode() && "What no callee?");
5309   return Callee;
5310 }
5311 
5312 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5313   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5314          "Expected a CALLSEQ_STARTSDNode.");
5315 
5316   // The last operand is the chain, except when the node has glue. If the node
5317   // has glue, then the last operand is the glue, and the chain is the second
5318   // last operand.
5319   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5320   if (LastValue.getValueType() != MVT::Glue)
5321     return LastValue;
5322 
5323   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5324 }
5325 
5326 // Creates the node that moves a functions address into the count register
5327 // to prepare for an indirect call instruction.
5328 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5329                                 SDValue &Glue, SDValue &Chain,
5330                                 const SDLoc &dl) {
5331   SDValue MTCTROps[] = {Chain, Callee, Glue};
5332   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5333   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5334                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5335   // The glue is the second value produced.
5336   Glue = Chain.getValue(1);
5337 }
5338 
5339 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5340                                           SDValue &Glue, SDValue &Chain,
5341                                           SDValue CallSeqStart,
5342                                           const CallBase *CB, const SDLoc &dl,
5343                                           bool hasNest,
5344                                           const PPCSubtarget &Subtarget) {
5345   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5346   // entry point, but to the function descriptor (the function entry point
5347   // address is part of the function descriptor though).
5348   // The function descriptor is a three doubleword structure with the
5349   // following fields: function entry point, TOC base address and
5350   // environment pointer.
5351   // Thus for a call through a function pointer, the following actions need
5352   // to be performed:
5353   //   1. Save the TOC of the caller in the TOC save area of its stack
5354   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5355   //   2. Load the address of the function entry point from the function
5356   //      descriptor.
5357   //   3. Load the TOC of the callee from the function descriptor into r2.
5358   //   4. Load the environment pointer from the function descriptor into
5359   //      r11.
5360   //   5. Branch to the function entry point address.
5361   //   6. On return of the callee, the TOC of the caller needs to be
5362   //      restored (this is done in FinishCall()).
5363   //
5364   // The loads are scheduled at the beginning of the call sequence, and the
5365   // register copies are flagged together to ensure that no other
5366   // operations can be scheduled in between. E.g. without flagging the
5367   // copies together, a TOC access in the caller could be scheduled between
5368   // the assignment of the callee TOC and the branch to the callee, which leads
5369   // to incorrect code.
5370 
5371   // Start by loading the function address from the descriptor.
5372   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5373   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5374                       ? (MachineMemOperand::MODereferenceable |
5375                          MachineMemOperand::MOInvariant)
5376                       : MachineMemOperand::MONone;
5377 
5378   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5379 
5380   // Registers used in building the DAG.
5381   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5382   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5383 
5384   // Offsets of descriptor members.
5385   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5386   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5387 
5388   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5389   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5390 
5391   // One load for the functions entry point address.
5392   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5393                                     Alignment, MMOFlags);
5394 
5395   // One for loading the TOC anchor for the module that contains the called
5396   // function.
5397   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5398   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5399   SDValue TOCPtr =
5400       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5401                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5402 
5403   // One for loading the environment pointer.
5404   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5405   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5406   SDValue LoadEnvPtr =
5407       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5408                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5409 
5410 
5411   // Then copy the newly loaded TOC anchor to the TOC pointer.
5412   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5413   Chain = TOCVal.getValue(0);
5414   Glue = TOCVal.getValue(1);
5415 
5416   // If the function call has an explicit 'nest' parameter, it takes the
5417   // place of the environment pointer.
5418   assert((!hasNest || !Subtarget.isAIXABI()) &&
5419          "Nest parameter is not supported on AIX.");
5420   if (!hasNest) {
5421     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5422     Chain = EnvVal.getValue(0);
5423     Glue = EnvVal.getValue(1);
5424   }
5425 
5426   // The rest of the indirect call sequence is the same as the non-descriptor
5427   // DAG.
5428   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5429 }
5430 
5431 static void
5432 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5433                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5434                   SelectionDAG &DAG,
5435                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5436                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5437                   const PPCSubtarget &Subtarget) {
5438   const bool IsPPC64 = Subtarget.isPPC64();
5439   // MVT for a general purpose register.
5440   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5441 
5442   // First operand is always the chain.
5443   Ops.push_back(Chain);
5444 
5445   // If it's a direct call pass the callee as the second operand.
5446   if (!CFlags.IsIndirect)
5447     Ops.push_back(Callee);
5448   else {
5449     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5450 
5451     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5452     // on the stack (this would have been done in `LowerCall_64SVR4` or
5453     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5454     // represents both the indirect branch and a load that restores the TOC
5455     // pointer from the linkage area. The operand for the TOC restore is an add
5456     // of the TOC save offset to the stack pointer. This must be the second
5457     // operand: after the chain input but before any other variadic arguments.
5458     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5459     // saved or used.
5460     if (isTOCSaveRestoreRequired(Subtarget)) {
5461       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5462 
5463       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5464       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5465       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5466       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5467       Ops.push_back(AddTOC);
5468     }
5469 
5470     // Add the register used for the environment pointer.
5471     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5472       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5473                                     RegVT));
5474 
5475 
5476     // Add CTR register as callee so a bctr can be emitted later.
5477     if (CFlags.IsTailCall)
5478       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5479   }
5480 
5481   // If this is a tail call add stack pointer delta.
5482   if (CFlags.IsTailCall)
5483     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5484 
5485   // Add argument registers to the end of the list so that they are known live
5486   // into the call.
5487   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5488     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5489                                   RegsToPass[i].second.getValueType()));
5490 
5491   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5492   // no way to mark dependencies as implicit here.
5493   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5494   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5495        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5496     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5497 
5498   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5499   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5500     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5501 
5502   // Add a register mask operand representing the call-preserved registers.
5503   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5504   const uint32_t *Mask =
5505       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5506   assert(Mask && "Missing call preserved mask for calling convention");
5507   Ops.push_back(DAG.getRegisterMask(Mask));
5508 
5509   // If the glue is valid, it is the last operand.
5510   if (Glue.getNode())
5511     Ops.push_back(Glue);
5512 }
5513 
5514 SDValue PPCTargetLowering::FinishCall(
5515     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5516     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5517     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5518     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5519     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5520 
5521   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5522       Subtarget.isAIXABI())
5523     setUsesTOCBasePtr(DAG);
5524 
5525   unsigned CallOpc =
5526       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5527                     Subtarget, DAG.getTarget());
5528 
5529   if (!CFlags.IsIndirect)
5530     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5531   else if (Subtarget.usesFunctionDescriptors())
5532     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5533                                   dl, CFlags.HasNest, Subtarget);
5534   else
5535     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5536 
5537   // Build the operand list for the call instruction.
5538   SmallVector<SDValue, 8> Ops;
5539   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5540                     SPDiff, Subtarget);
5541 
5542   // Emit tail call.
5543   if (CFlags.IsTailCall) {
5544     // Indirect tail call when using PC Relative calls do not have the same
5545     // constraints.
5546     assert(((Callee.getOpcode() == ISD::Register &&
5547              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5548             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5549             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5550             isa<ConstantSDNode>(Callee) ||
5551             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5552            "Expecting a global address, external symbol, absolute value, "
5553            "register or an indirect tail call when PC Relative calls are "
5554            "used.");
5555     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5556     assert(CallOpc == PPCISD::TC_RETURN &&
5557            "Unexpected call opcode for a tail call.");
5558     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5559     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5560   }
5561 
5562   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5563   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5564   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5565   Glue = Chain.getValue(1);
5566 
5567   // When performing tail call optimization the callee pops its arguments off
5568   // the stack. Account for this here so these bytes can be pushed back on in
5569   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5570   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5571                          getTargetMachine().Options.GuaranteedTailCallOpt)
5572                             ? NumBytes
5573                             : 0;
5574 
5575   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5576                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5577                              Glue, dl);
5578   Glue = Chain.getValue(1);
5579 
5580   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5581                          DAG, InVals);
5582 }
5583 
5584 SDValue
5585 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5586                              SmallVectorImpl<SDValue> &InVals) const {
5587   SelectionDAG &DAG                     = CLI.DAG;
5588   SDLoc &dl                             = CLI.DL;
5589   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5590   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5591   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5592   SDValue Chain                         = CLI.Chain;
5593   SDValue Callee                        = CLI.Callee;
5594   bool &isTailCall                      = CLI.IsTailCall;
5595   CallingConv::ID CallConv              = CLI.CallConv;
5596   bool isVarArg                         = CLI.IsVarArg;
5597   bool isPatchPoint                     = CLI.IsPatchPoint;
5598   const CallBase *CB                    = CLI.CB;
5599 
5600   if (isTailCall) {
5601     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5602       isTailCall = false;
5603     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5604       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5605           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5606     else
5607       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5608                                                      Ins, DAG);
5609     if (isTailCall) {
5610       ++NumTailCalls;
5611       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5612         ++NumSiblingCalls;
5613 
5614       // PC Relative calls no longer guarantee that the callee is a Global
5615       // Address Node. The callee could be an indirect tail call in which
5616       // case the SDValue for the callee could be a load (to load the address
5617       // of a function pointer) or it may be a register copy (to move the
5618       // address of the callee from a function parameter into a virtual
5619       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5620       assert((Subtarget.isUsingPCRelativeCalls() ||
5621               isa<GlobalAddressSDNode>(Callee)) &&
5622              "Callee should be an llvm::Function object.");
5623 
5624       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5625                         << "\nTCO callee: ");
5626       LLVM_DEBUG(Callee.dump());
5627     }
5628   }
5629 
5630   if (!isTailCall && CB && CB->isMustTailCall())
5631     report_fatal_error("failed to perform tail call elimination on a call "
5632                        "site marked musttail");
5633 
5634   // When long calls (i.e. indirect calls) are always used, calls are always
5635   // made via function pointer. If we have a function name, first translate it
5636   // into a pointer.
5637   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5638       !isTailCall)
5639     Callee = LowerGlobalAddress(Callee, DAG);
5640 
5641   CallFlags CFlags(
5642       CallConv, isTailCall, isVarArg, isPatchPoint,
5643       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5644       // hasNest
5645       Subtarget.is64BitELFABI() &&
5646           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5647       CLI.NoMerge);
5648 
5649   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5650     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5651                             InVals, CB);
5652 
5653   if (Subtarget.isSVR4ABI())
5654     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5655                             InVals, CB);
5656 
5657   if (Subtarget.isAIXABI())
5658     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5659                          InVals, CB);
5660 
5661   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5662                           InVals, CB);
5663 }
5664 
5665 SDValue PPCTargetLowering::LowerCall_32SVR4(
5666     SDValue Chain, SDValue Callee, CallFlags CFlags,
5667     const SmallVectorImpl<ISD::OutputArg> &Outs,
5668     const SmallVectorImpl<SDValue> &OutVals,
5669     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5670     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5671     const CallBase *CB) const {
5672   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5673   // of the 32-bit SVR4 ABI stack frame layout.
5674 
5675   const CallingConv::ID CallConv = CFlags.CallConv;
5676   const bool IsVarArg = CFlags.IsVarArg;
5677   const bool IsTailCall = CFlags.IsTailCall;
5678 
5679   assert((CallConv == CallingConv::C ||
5680           CallConv == CallingConv::Cold ||
5681           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5682 
5683   const Align PtrAlign(4);
5684 
5685   MachineFunction &MF = DAG.getMachineFunction();
5686 
5687   // Mark this function as potentially containing a function that contains a
5688   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5689   // and restoring the callers stack pointer in this functions epilog. This is
5690   // done because by tail calling the called function might overwrite the value
5691   // in this function's (MF) stack pointer stack slot 0(SP).
5692   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5693       CallConv == CallingConv::Fast)
5694     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5695 
5696   // Count how many bytes are to be pushed on the stack, including the linkage
5697   // area, parameter list area and the part of the local variable space which
5698   // contains copies of aggregates which are passed by value.
5699 
5700   // Assign locations to all of the outgoing arguments.
5701   SmallVector<CCValAssign, 16> ArgLocs;
5702   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5703 
5704   // Reserve space for the linkage area on the stack.
5705   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5706                        PtrAlign);
5707   if (useSoftFloat())
5708     CCInfo.PreAnalyzeCallOperands(Outs);
5709 
5710   if (IsVarArg) {
5711     // Handle fixed and variable vector arguments differently.
5712     // Fixed vector arguments go into registers as long as registers are
5713     // available. Variable vector arguments always go into memory.
5714     unsigned NumArgs = Outs.size();
5715 
5716     for (unsigned i = 0; i != NumArgs; ++i) {
5717       MVT ArgVT = Outs[i].VT;
5718       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5719       bool Result;
5720 
5721       if (Outs[i].IsFixed) {
5722         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5723                                CCInfo);
5724       } else {
5725         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5726                                       ArgFlags, CCInfo);
5727       }
5728 
5729       if (Result) {
5730 #ifndef NDEBUG
5731         errs() << "Call operand #" << i << " has unhandled type "
5732              << EVT(ArgVT).getEVTString() << "\n";
5733 #endif
5734         llvm_unreachable(nullptr);
5735       }
5736     }
5737   } else {
5738     // All arguments are treated the same.
5739     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5740   }
5741   CCInfo.clearWasPPCF128();
5742 
5743   // Assign locations to all of the outgoing aggregate by value arguments.
5744   SmallVector<CCValAssign, 16> ByValArgLocs;
5745   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5746 
5747   // Reserve stack space for the allocations in CCInfo.
5748   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5749 
5750   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5751 
5752   // Size of the linkage area, parameter list area and the part of the local
5753   // space variable where copies of aggregates which are passed by value are
5754   // stored.
5755   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5756 
5757   // Calculate by how many bytes the stack has to be adjusted in case of tail
5758   // call optimization.
5759   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5760 
5761   // Adjust the stack pointer for the new arguments...
5762   // These operations are automatically eliminated by the prolog/epilog pass
5763   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5764   SDValue CallSeqStart = Chain;
5765 
5766   // Load the return address and frame pointer so it can be moved somewhere else
5767   // later.
5768   SDValue LROp, FPOp;
5769   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5770 
5771   // Set up a copy of the stack pointer for use loading and storing any
5772   // arguments that may not fit in the registers available for argument
5773   // passing.
5774   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5775 
5776   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5777   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5778   SmallVector<SDValue, 8> MemOpChains;
5779 
5780   bool seenFloatArg = false;
5781   // Walk the register/memloc assignments, inserting copies/loads.
5782   // i - Tracks the index into the list of registers allocated for the call
5783   // RealArgIdx - Tracks the index into the list of actual function arguments
5784   // j - Tracks the index into the list of byval arguments
5785   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5786        i != e;
5787        ++i, ++RealArgIdx) {
5788     CCValAssign &VA = ArgLocs[i];
5789     SDValue Arg = OutVals[RealArgIdx];
5790     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5791 
5792     if (Flags.isByVal()) {
5793       // Argument is an aggregate which is passed by value, thus we need to
5794       // create a copy of it in the local variable space of the current stack
5795       // frame (which is the stack frame of the caller) and pass the address of
5796       // this copy to the callee.
5797       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5798       CCValAssign &ByValVA = ByValArgLocs[j++];
5799       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5800 
5801       // Memory reserved in the local variable space of the callers stack frame.
5802       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5803 
5804       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5805       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5806                            StackPtr, PtrOff);
5807 
5808       // Create a copy of the argument in the local area of the current
5809       // stack frame.
5810       SDValue MemcpyCall =
5811         CreateCopyOfByValArgument(Arg, PtrOff,
5812                                   CallSeqStart.getNode()->getOperand(0),
5813                                   Flags, DAG, dl);
5814 
5815       // This must go outside the CALLSEQ_START..END.
5816       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5817                                                      SDLoc(MemcpyCall));
5818       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5819                              NewCallSeqStart.getNode());
5820       Chain = CallSeqStart = NewCallSeqStart;
5821 
5822       // Pass the address of the aggregate copy on the stack either in a
5823       // physical register or in the parameter list area of the current stack
5824       // frame to the callee.
5825       Arg = PtrOff;
5826     }
5827 
5828     // When useCRBits() is true, there can be i1 arguments.
5829     // It is because getRegisterType(MVT::i1) => MVT::i1,
5830     // and for other integer types getRegisterType() => MVT::i32.
5831     // Extend i1 and ensure callee will get i32.
5832     if (Arg.getValueType() == MVT::i1)
5833       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5834                         dl, MVT::i32, Arg);
5835 
5836     if (VA.isRegLoc()) {
5837       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5838       // Put argument in a physical register.
5839       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5840         bool IsLE = Subtarget.isLittleEndian();
5841         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5842                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5843         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5844         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5845                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5846         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5847                              SVal.getValue(0)));
5848       } else
5849         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5850     } else {
5851       // Put argument in the parameter list area of the current stack frame.
5852       assert(VA.isMemLoc());
5853       unsigned LocMemOffset = VA.getLocMemOffset();
5854 
5855       if (!IsTailCall) {
5856         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5857         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5858                              StackPtr, PtrOff);
5859 
5860         MemOpChains.push_back(
5861             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5862       } else {
5863         // Calculate and remember argument location.
5864         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5865                                  TailCallArguments);
5866       }
5867     }
5868   }
5869 
5870   if (!MemOpChains.empty())
5871     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5872 
5873   // Build a sequence of copy-to-reg nodes chained together with token chain
5874   // and flag operands which copy the outgoing args into the appropriate regs.
5875   SDValue InFlag;
5876   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5877     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5878                              RegsToPass[i].second, InFlag);
5879     InFlag = Chain.getValue(1);
5880   }
5881 
5882   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5883   // registers.
5884   if (IsVarArg) {
5885     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5886     SDValue Ops[] = { Chain, InFlag };
5887 
5888     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5889                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5890 
5891     InFlag = Chain.getValue(1);
5892   }
5893 
5894   if (IsTailCall)
5895     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5896                     TailCallArguments);
5897 
5898   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5899                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5900 }
5901 
5902 // Copy an argument into memory, being careful to do this outside the
5903 // call sequence for the call to which the argument belongs.
5904 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5905     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5906     SelectionDAG &DAG, const SDLoc &dl) const {
5907   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5908                         CallSeqStart.getNode()->getOperand(0),
5909                         Flags, DAG, dl);
5910   // The MEMCPY must go outside the CALLSEQ_START..END.
5911   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5912   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5913                                                  SDLoc(MemcpyCall));
5914   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5915                          NewCallSeqStart.getNode());
5916   return NewCallSeqStart;
5917 }
5918 
5919 SDValue PPCTargetLowering::LowerCall_64SVR4(
5920     SDValue Chain, SDValue Callee, CallFlags CFlags,
5921     const SmallVectorImpl<ISD::OutputArg> &Outs,
5922     const SmallVectorImpl<SDValue> &OutVals,
5923     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5924     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5925     const CallBase *CB) const {
5926   bool isELFv2ABI = Subtarget.isELFv2ABI();
5927   bool isLittleEndian = Subtarget.isLittleEndian();
5928   unsigned NumOps = Outs.size();
5929   bool IsSibCall = false;
5930   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5931 
5932   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5933   unsigned PtrByteSize = 8;
5934 
5935   MachineFunction &MF = DAG.getMachineFunction();
5936 
5937   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5938     IsSibCall = true;
5939 
5940   // Mark this function as potentially containing a function that contains a
5941   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5942   // and restoring the callers stack pointer in this functions epilog. This is
5943   // done because by tail calling the called function might overwrite the value
5944   // in this function's (MF) stack pointer stack slot 0(SP).
5945   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5946     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5947 
5948   assert(!(IsFastCall && CFlags.IsVarArg) &&
5949          "fastcc not supported on varargs functions");
5950 
5951   // Count how many bytes are to be pushed on the stack, including the linkage
5952   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5953   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5954   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5955   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5956   unsigned NumBytes = LinkageSize;
5957   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5958 
5959   static const MCPhysReg GPR[] = {
5960     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5961     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5962   };
5963   static const MCPhysReg VR[] = {
5964     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5965     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5966   };
5967 
5968   const unsigned NumGPRs = array_lengthof(GPR);
5969   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5970   const unsigned NumVRs  = array_lengthof(VR);
5971 
5972   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5973   // can be passed to the callee in registers.
5974   // For the fast calling convention, there is another check below.
5975   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5976   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5977   if (!HasParameterArea) {
5978     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5979     unsigned AvailableFPRs = NumFPRs;
5980     unsigned AvailableVRs = NumVRs;
5981     unsigned NumBytesTmp = NumBytes;
5982     for (unsigned i = 0; i != NumOps; ++i) {
5983       if (Outs[i].Flags.isNest()) continue;
5984       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5985                                  PtrByteSize, LinkageSize, ParamAreaSize,
5986                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5987         HasParameterArea = true;
5988     }
5989   }
5990 
5991   // When using the fast calling convention, we don't provide backing for
5992   // arguments that will be in registers.
5993   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5994 
5995   // Avoid allocating parameter area for fastcc functions if all the arguments
5996   // can be passed in the registers.
5997   if (IsFastCall)
5998     HasParameterArea = false;
5999 
6000   // Add up all the space actually used.
6001   for (unsigned i = 0; i != NumOps; ++i) {
6002     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6003     EVT ArgVT = Outs[i].VT;
6004     EVT OrigVT = Outs[i].ArgVT;
6005 
6006     if (Flags.isNest())
6007       continue;
6008 
6009     if (IsFastCall) {
6010       if (Flags.isByVal()) {
6011         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6012         if (NumGPRsUsed > NumGPRs)
6013           HasParameterArea = true;
6014       } else {
6015         switch (ArgVT.getSimpleVT().SimpleTy) {
6016         default: llvm_unreachable("Unexpected ValueType for argument!");
6017         case MVT::i1:
6018         case MVT::i32:
6019         case MVT::i64:
6020           if (++NumGPRsUsed <= NumGPRs)
6021             continue;
6022           break;
6023         case MVT::v4i32:
6024         case MVT::v8i16:
6025         case MVT::v16i8:
6026         case MVT::v2f64:
6027         case MVT::v2i64:
6028         case MVT::v1i128:
6029         case MVT::f128:
6030           if (++NumVRsUsed <= NumVRs)
6031             continue;
6032           break;
6033         case MVT::v4f32:
6034           if (++NumVRsUsed <= NumVRs)
6035             continue;
6036           break;
6037         case MVT::f32:
6038         case MVT::f64:
6039           if (++NumFPRsUsed <= NumFPRs)
6040             continue;
6041           break;
6042         }
6043         HasParameterArea = true;
6044       }
6045     }
6046 
6047     /* Respect alignment of argument on the stack.  */
6048     auto Alignement =
6049         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6050     NumBytes = alignTo(NumBytes, Alignement);
6051 
6052     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6053     if (Flags.isInConsecutiveRegsLast())
6054       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6055   }
6056 
6057   unsigned NumBytesActuallyUsed = NumBytes;
6058 
6059   // In the old ELFv1 ABI,
6060   // the prolog code of the callee may store up to 8 GPR argument registers to
6061   // the stack, allowing va_start to index over them in memory if its varargs.
6062   // Because we cannot tell if this is needed on the caller side, we have to
6063   // conservatively assume that it is needed.  As such, make sure we have at
6064   // least enough stack space for the caller to store the 8 GPRs.
6065   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6066   // really requires memory operands, e.g. a vararg function.
6067   if (HasParameterArea)
6068     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6069   else
6070     NumBytes = LinkageSize;
6071 
6072   // Tail call needs the stack to be aligned.
6073   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6074     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6075 
6076   int SPDiff = 0;
6077 
6078   // Calculate by how many bytes the stack has to be adjusted in case of tail
6079   // call optimization.
6080   if (!IsSibCall)
6081     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6082 
6083   // To protect arguments on the stack from being clobbered in a tail call,
6084   // force all the loads to happen before doing any other lowering.
6085   if (CFlags.IsTailCall)
6086     Chain = DAG.getStackArgumentTokenFactor(Chain);
6087 
6088   // Adjust the stack pointer for the new arguments...
6089   // These operations are automatically eliminated by the prolog/epilog pass
6090   if (!IsSibCall)
6091     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6092   SDValue CallSeqStart = Chain;
6093 
6094   // Load the return address and frame pointer so it can be move somewhere else
6095   // later.
6096   SDValue LROp, FPOp;
6097   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6098 
6099   // Set up a copy of the stack pointer for use loading and storing any
6100   // arguments that may not fit in the registers available for argument
6101   // passing.
6102   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6103 
6104   // Figure out which arguments are going to go in registers, and which in
6105   // memory.  Also, if this is a vararg function, floating point operations
6106   // must be stored to our stack, and loaded into integer regs as well, if
6107   // any integer regs are available for argument passing.
6108   unsigned ArgOffset = LinkageSize;
6109 
6110   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6111   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6112 
6113   SmallVector<SDValue, 8> MemOpChains;
6114   for (unsigned i = 0; i != NumOps; ++i) {
6115     SDValue Arg = OutVals[i];
6116     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6117     EVT ArgVT = Outs[i].VT;
6118     EVT OrigVT = Outs[i].ArgVT;
6119 
6120     // PtrOff will be used to store the current argument to the stack if a
6121     // register cannot be found for it.
6122     SDValue PtrOff;
6123 
6124     // We re-align the argument offset for each argument, except when using the
6125     // fast calling convention, when we need to make sure we do that only when
6126     // we'll actually use a stack slot.
6127     auto ComputePtrOff = [&]() {
6128       /* Respect alignment of argument on the stack.  */
6129       auto Alignment =
6130           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6131       ArgOffset = alignTo(ArgOffset, Alignment);
6132 
6133       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6134 
6135       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6136     };
6137 
6138     if (!IsFastCall) {
6139       ComputePtrOff();
6140 
6141       /* Compute GPR index associated with argument offset.  */
6142       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6143       GPR_idx = std::min(GPR_idx, NumGPRs);
6144     }
6145 
6146     // Promote integers to 64-bit values.
6147     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6148       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6149       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6150       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6151     }
6152 
6153     // FIXME memcpy is used way more than necessary.  Correctness first.
6154     // Note: "by value" is code for passing a structure by value, not
6155     // basic types.
6156     if (Flags.isByVal()) {
6157       // Note: Size includes alignment padding, so
6158       //   struct x { short a; char b; }
6159       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6160       // These are the proper values we need for right-justifying the
6161       // aggregate in a parameter register.
6162       unsigned Size = Flags.getByValSize();
6163 
6164       // An empty aggregate parameter takes up no storage and no
6165       // registers.
6166       if (Size == 0)
6167         continue;
6168 
6169       if (IsFastCall)
6170         ComputePtrOff();
6171 
6172       // All aggregates smaller than 8 bytes must be passed right-justified.
6173       if (Size==1 || Size==2 || Size==4) {
6174         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6175         if (GPR_idx != NumGPRs) {
6176           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6177                                         MachinePointerInfo(), VT);
6178           MemOpChains.push_back(Load.getValue(1));
6179           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6180 
6181           ArgOffset += PtrByteSize;
6182           continue;
6183         }
6184       }
6185 
6186       if (GPR_idx == NumGPRs && Size < 8) {
6187         SDValue AddPtr = PtrOff;
6188         if (!isLittleEndian) {
6189           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6190                                           PtrOff.getValueType());
6191           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6192         }
6193         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6194                                                           CallSeqStart,
6195                                                           Flags, DAG, dl);
6196         ArgOffset += PtrByteSize;
6197         continue;
6198       }
6199       // Copy entire object into memory.  There are cases where gcc-generated
6200       // code assumes it is there, even if it could be put entirely into
6201       // registers.  (This is not what the doc says.)
6202 
6203       // FIXME: The above statement is likely due to a misunderstanding of the
6204       // documents.  All arguments must be copied into the parameter area BY
6205       // THE CALLEE in the event that the callee takes the address of any
6206       // formal argument.  That has not yet been implemented.  However, it is
6207       // reasonable to use the stack area as a staging area for the register
6208       // load.
6209 
6210       // Skip this for small aggregates, as we will use the same slot for a
6211       // right-justified copy, below.
6212       if (Size >= 8)
6213         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6214                                                           CallSeqStart,
6215                                                           Flags, DAG, dl);
6216 
6217       // When a register is available, pass a small aggregate right-justified.
6218       if (Size < 8 && GPR_idx != NumGPRs) {
6219         // The easiest way to get this right-justified in a register
6220         // is to copy the structure into the rightmost portion of a
6221         // local variable slot, then load the whole slot into the
6222         // register.
6223         // FIXME: The memcpy seems to produce pretty awful code for
6224         // small aggregates, particularly for packed ones.
6225         // FIXME: It would be preferable to use the slot in the
6226         // parameter save area instead of a new local variable.
6227         SDValue AddPtr = PtrOff;
6228         if (!isLittleEndian) {
6229           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6230           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6231         }
6232         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6233                                                           CallSeqStart,
6234                                                           Flags, DAG, dl);
6235 
6236         // Load the slot into the register.
6237         SDValue Load =
6238             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6239         MemOpChains.push_back(Load.getValue(1));
6240         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6241 
6242         // Done with this argument.
6243         ArgOffset += PtrByteSize;
6244         continue;
6245       }
6246 
6247       // For aggregates larger than PtrByteSize, copy the pieces of the
6248       // object that fit into registers from the parameter save area.
6249       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6250         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6251         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6252         if (GPR_idx != NumGPRs) {
6253           SDValue Load =
6254               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6255           MemOpChains.push_back(Load.getValue(1));
6256           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6257           ArgOffset += PtrByteSize;
6258         } else {
6259           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6260           break;
6261         }
6262       }
6263       continue;
6264     }
6265 
6266     switch (Arg.getSimpleValueType().SimpleTy) {
6267     default: llvm_unreachable("Unexpected ValueType for argument!");
6268     case MVT::i1:
6269     case MVT::i32:
6270     case MVT::i64:
6271       if (Flags.isNest()) {
6272         // The 'nest' parameter, if any, is passed in R11.
6273         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6274         break;
6275       }
6276 
6277       // These can be scalar arguments or elements of an integer array type
6278       // passed directly.  Clang may use those instead of "byval" aggregate
6279       // types to avoid forcing arguments to memory unnecessarily.
6280       if (GPR_idx != NumGPRs) {
6281         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6282       } else {
6283         if (IsFastCall)
6284           ComputePtrOff();
6285 
6286         assert(HasParameterArea &&
6287                "Parameter area must exist to pass an argument in memory.");
6288         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6289                          true, CFlags.IsTailCall, false, MemOpChains,
6290                          TailCallArguments, dl);
6291         if (IsFastCall)
6292           ArgOffset += PtrByteSize;
6293       }
6294       if (!IsFastCall)
6295         ArgOffset += PtrByteSize;
6296       break;
6297     case MVT::f32:
6298     case MVT::f64: {
6299       // These can be scalar arguments or elements of a float array type
6300       // passed directly.  The latter are used to implement ELFv2 homogenous
6301       // float aggregates.
6302 
6303       // Named arguments go into FPRs first, and once they overflow, the
6304       // remaining arguments go into GPRs and then the parameter save area.
6305       // Unnamed arguments for vararg functions always go to GPRs and
6306       // then the parameter save area.  For now, put all arguments to vararg
6307       // routines always in both locations (FPR *and* GPR or stack slot).
6308       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6309       bool NeededLoad = false;
6310 
6311       // First load the argument into the next available FPR.
6312       if (FPR_idx != NumFPRs)
6313         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6314 
6315       // Next, load the argument into GPR or stack slot if needed.
6316       if (!NeedGPROrStack)
6317         ;
6318       else if (GPR_idx != NumGPRs && !IsFastCall) {
6319         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6320         // once we support fp <-> gpr moves.
6321 
6322         // In the non-vararg case, this can only ever happen in the
6323         // presence of f32 array types, since otherwise we never run
6324         // out of FPRs before running out of GPRs.
6325         SDValue ArgVal;
6326 
6327         // Double values are always passed in a single GPR.
6328         if (Arg.getValueType() != MVT::f32) {
6329           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6330 
6331         // Non-array float values are extended and passed in a GPR.
6332         } else if (!Flags.isInConsecutiveRegs()) {
6333           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6334           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6335 
6336         // If we have an array of floats, we collect every odd element
6337         // together with its predecessor into one GPR.
6338         } else if (ArgOffset % PtrByteSize != 0) {
6339           SDValue Lo, Hi;
6340           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6341           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6342           if (!isLittleEndian)
6343             std::swap(Lo, Hi);
6344           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6345 
6346         // The final element, if even, goes into the first half of a GPR.
6347         } else if (Flags.isInConsecutiveRegsLast()) {
6348           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6349           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6350           if (!isLittleEndian)
6351             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6352                                  DAG.getConstant(32, dl, MVT::i32));
6353 
6354         // Non-final even elements are skipped; they will be handled
6355         // together the with subsequent argument on the next go-around.
6356         } else
6357           ArgVal = SDValue();
6358 
6359         if (ArgVal.getNode())
6360           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6361       } else {
6362         if (IsFastCall)
6363           ComputePtrOff();
6364 
6365         // Single-precision floating-point values are mapped to the
6366         // second (rightmost) word of the stack doubleword.
6367         if (Arg.getValueType() == MVT::f32 &&
6368             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6369           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6370           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6371         }
6372 
6373         assert(HasParameterArea &&
6374                "Parameter area must exist to pass an argument in memory.");
6375         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6376                          true, CFlags.IsTailCall, false, MemOpChains,
6377                          TailCallArguments, dl);
6378 
6379         NeededLoad = true;
6380       }
6381       // When passing an array of floats, the array occupies consecutive
6382       // space in the argument area; only round up to the next doubleword
6383       // at the end of the array.  Otherwise, each float takes 8 bytes.
6384       if (!IsFastCall || NeededLoad) {
6385         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6386                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6387         if (Flags.isInConsecutiveRegsLast())
6388           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6389       }
6390       break;
6391     }
6392     case MVT::v4f32:
6393     case MVT::v4i32:
6394     case MVT::v8i16:
6395     case MVT::v16i8:
6396     case MVT::v2f64:
6397     case MVT::v2i64:
6398     case MVT::v1i128:
6399     case MVT::f128:
6400       // These can be scalar arguments or elements of a vector array type
6401       // passed directly.  The latter are used to implement ELFv2 homogenous
6402       // vector aggregates.
6403 
6404       // For a varargs call, named arguments go into VRs or on the stack as
6405       // usual; unnamed arguments always go to the stack or the corresponding
6406       // GPRs when within range.  For now, we always put the value in both
6407       // locations (or even all three).
6408       if (CFlags.IsVarArg) {
6409         assert(HasParameterArea &&
6410                "Parameter area must exist if we have a varargs call.");
6411         // We could elide this store in the case where the object fits
6412         // entirely in R registers.  Maybe later.
6413         SDValue Store =
6414             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6415         MemOpChains.push_back(Store);
6416         if (VR_idx != NumVRs) {
6417           SDValue Load =
6418               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6419           MemOpChains.push_back(Load.getValue(1));
6420           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6421         }
6422         ArgOffset += 16;
6423         for (unsigned i=0; i<16; i+=PtrByteSize) {
6424           if (GPR_idx == NumGPRs)
6425             break;
6426           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6427                                    DAG.getConstant(i, dl, PtrVT));
6428           SDValue Load =
6429               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6430           MemOpChains.push_back(Load.getValue(1));
6431           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6432         }
6433         break;
6434       }
6435 
6436       // Non-varargs Altivec params go into VRs or on the stack.
6437       if (VR_idx != NumVRs) {
6438         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6439       } else {
6440         if (IsFastCall)
6441           ComputePtrOff();
6442 
6443         assert(HasParameterArea &&
6444                "Parameter area must exist to pass an argument in memory.");
6445         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6446                          true, CFlags.IsTailCall, true, MemOpChains,
6447                          TailCallArguments, dl);
6448         if (IsFastCall)
6449           ArgOffset += 16;
6450       }
6451 
6452       if (!IsFastCall)
6453         ArgOffset += 16;
6454       break;
6455     }
6456   }
6457 
6458   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6459          "mismatch in size of parameter area");
6460   (void)NumBytesActuallyUsed;
6461 
6462   if (!MemOpChains.empty())
6463     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6464 
6465   // Check if this is an indirect call (MTCTR/BCTRL).
6466   // See prepareDescriptorIndirectCall and buildCallOperands for more
6467   // information about calls through function pointers in the 64-bit SVR4 ABI.
6468   if (CFlags.IsIndirect) {
6469     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6470     // caller in the TOC save area.
6471     if (isTOCSaveRestoreRequired(Subtarget)) {
6472       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6473       // Load r2 into a virtual register and store it to the TOC save area.
6474       setUsesTOCBasePtr(DAG);
6475       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6476       // TOC save area offset.
6477       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6478       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6479       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6480       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6481                            MachinePointerInfo::getStack(
6482                                DAG.getMachineFunction(), TOCSaveOffset));
6483     }
6484     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6485     // This does not mean the MTCTR instruction must use R12; it's easier
6486     // to model this as an extra parameter, so do that.
6487     if (isELFv2ABI && !CFlags.IsPatchPoint)
6488       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6489   }
6490 
6491   // Build a sequence of copy-to-reg nodes chained together with token chain
6492   // and flag operands which copy the outgoing args into the appropriate regs.
6493   SDValue InFlag;
6494   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6495     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6496                              RegsToPass[i].second, InFlag);
6497     InFlag = Chain.getValue(1);
6498   }
6499 
6500   if (CFlags.IsTailCall && !IsSibCall)
6501     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6502                     TailCallArguments);
6503 
6504   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6505                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6506 }
6507 
6508 SDValue PPCTargetLowering::LowerCall_Darwin(
6509     SDValue Chain, SDValue Callee, CallFlags CFlags,
6510     const SmallVectorImpl<ISD::OutputArg> &Outs,
6511     const SmallVectorImpl<SDValue> &OutVals,
6512     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6513     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6514     const CallBase *CB) const {
6515   unsigned NumOps = Outs.size();
6516 
6517   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6518   bool isPPC64 = PtrVT == MVT::i64;
6519   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6520 
6521   MachineFunction &MF = DAG.getMachineFunction();
6522 
6523   // Mark this function as potentially containing a function that contains a
6524   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6525   // and restoring the callers stack pointer in this functions epilog. This is
6526   // done because by tail calling the called function might overwrite the value
6527   // in this function's (MF) stack pointer stack slot 0(SP).
6528   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6529       CFlags.CallConv == CallingConv::Fast)
6530     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6531 
6532   // Count how many bytes are to be pushed on the stack, including the linkage
6533   // area, and parameter passing area.  We start with 24/48 bytes, which is
6534   // prereserved space for [SP][CR][LR][3 x unused].
6535   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6536   unsigned NumBytes = LinkageSize;
6537 
6538   // Add up all the space actually used.
6539   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6540   // they all go in registers, but we must reserve stack space for them for
6541   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6542   // assigned stack space in order, with padding so Altivec parameters are
6543   // 16-byte aligned.
6544   unsigned nAltivecParamsAtEnd = 0;
6545   for (unsigned i = 0; i != NumOps; ++i) {
6546     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6547     EVT ArgVT = Outs[i].VT;
6548     // Varargs Altivec parameters are padded to a 16 byte boundary.
6549     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6550         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6551         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6552       if (!CFlags.IsVarArg && !isPPC64) {
6553         // Non-varargs Altivec parameters go after all the non-Altivec
6554         // parameters; handle those later so we know how much padding we need.
6555         nAltivecParamsAtEnd++;
6556         continue;
6557       }
6558       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6559       NumBytes = ((NumBytes+15)/16)*16;
6560     }
6561     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6562   }
6563 
6564   // Allow for Altivec parameters at the end, if needed.
6565   if (nAltivecParamsAtEnd) {
6566     NumBytes = ((NumBytes+15)/16)*16;
6567     NumBytes += 16*nAltivecParamsAtEnd;
6568   }
6569 
6570   // The prolog code of the callee may store up to 8 GPR argument registers to
6571   // the stack, allowing va_start to index over them in memory if its varargs.
6572   // Because we cannot tell if this is needed on the caller side, we have to
6573   // conservatively assume that it is needed.  As such, make sure we have at
6574   // least enough stack space for the caller to store the 8 GPRs.
6575   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6576 
6577   // Tail call needs the stack to be aligned.
6578   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6579       CFlags.CallConv == CallingConv::Fast)
6580     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6581 
6582   // Calculate by how many bytes the stack has to be adjusted in case of tail
6583   // call optimization.
6584   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6585 
6586   // To protect arguments on the stack from being clobbered in a tail call,
6587   // force all the loads to happen before doing any other lowering.
6588   if (CFlags.IsTailCall)
6589     Chain = DAG.getStackArgumentTokenFactor(Chain);
6590 
6591   // Adjust the stack pointer for the new arguments...
6592   // These operations are automatically eliminated by the prolog/epilog pass
6593   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6594   SDValue CallSeqStart = Chain;
6595 
6596   // Load the return address and frame pointer so it can be move somewhere else
6597   // later.
6598   SDValue LROp, FPOp;
6599   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6600 
6601   // Set up a copy of the stack pointer for use loading and storing any
6602   // arguments that may not fit in the registers available for argument
6603   // passing.
6604   SDValue StackPtr;
6605   if (isPPC64)
6606     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6607   else
6608     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6609 
6610   // Figure out which arguments are going to go in registers, and which in
6611   // memory.  Also, if this is a vararg function, floating point operations
6612   // must be stored to our stack, and loaded into integer regs as well, if
6613   // any integer regs are available for argument passing.
6614   unsigned ArgOffset = LinkageSize;
6615   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6616 
6617   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6618     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6619     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6620   };
6621   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6622     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6623     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6624   };
6625   static const MCPhysReg VR[] = {
6626     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6627     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6628   };
6629   const unsigned NumGPRs = array_lengthof(GPR_32);
6630   const unsigned NumFPRs = 13;
6631   const unsigned NumVRs  = array_lengthof(VR);
6632 
6633   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6634 
6635   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6636   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6637 
6638   SmallVector<SDValue, 8> MemOpChains;
6639   for (unsigned i = 0; i != NumOps; ++i) {
6640     SDValue Arg = OutVals[i];
6641     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6642 
6643     // PtrOff will be used to store the current argument to the stack if a
6644     // register cannot be found for it.
6645     SDValue PtrOff;
6646 
6647     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6648 
6649     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6650 
6651     // On PPC64, promote integers to 64-bit values.
6652     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6653       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6654       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6655       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6656     }
6657 
6658     // FIXME memcpy is used way more than necessary.  Correctness first.
6659     // Note: "by value" is code for passing a structure by value, not
6660     // basic types.
6661     if (Flags.isByVal()) {
6662       unsigned Size = Flags.getByValSize();
6663       // Very small objects are passed right-justified.  Everything else is
6664       // passed left-justified.
6665       if (Size==1 || Size==2) {
6666         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6667         if (GPR_idx != NumGPRs) {
6668           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6669                                         MachinePointerInfo(), VT);
6670           MemOpChains.push_back(Load.getValue(1));
6671           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6672 
6673           ArgOffset += PtrByteSize;
6674         } else {
6675           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6676                                           PtrOff.getValueType());
6677           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6678           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6679                                                             CallSeqStart,
6680                                                             Flags, DAG, dl);
6681           ArgOffset += PtrByteSize;
6682         }
6683         continue;
6684       }
6685       // Copy entire object into memory.  There are cases where gcc-generated
6686       // code assumes it is there, even if it could be put entirely into
6687       // registers.  (This is not what the doc says.)
6688       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6689                                                         CallSeqStart,
6690                                                         Flags, DAG, dl);
6691 
6692       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6693       // copy the pieces of the object that fit into registers from the
6694       // parameter save area.
6695       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6696         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6697         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6698         if (GPR_idx != NumGPRs) {
6699           SDValue Load =
6700               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6701           MemOpChains.push_back(Load.getValue(1));
6702           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6703           ArgOffset += PtrByteSize;
6704         } else {
6705           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6706           break;
6707         }
6708       }
6709       continue;
6710     }
6711 
6712     switch (Arg.getSimpleValueType().SimpleTy) {
6713     default: llvm_unreachable("Unexpected ValueType for argument!");
6714     case MVT::i1:
6715     case MVT::i32:
6716     case MVT::i64:
6717       if (GPR_idx != NumGPRs) {
6718         if (Arg.getValueType() == MVT::i1)
6719           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6720 
6721         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6722       } else {
6723         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6724                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6725                          TailCallArguments, dl);
6726       }
6727       ArgOffset += PtrByteSize;
6728       break;
6729     case MVT::f32:
6730     case MVT::f64:
6731       if (FPR_idx != NumFPRs) {
6732         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6733 
6734         if (CFlags.IsVarArg) {
6735           SDValue Store =
6736               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6737           MemOpChains.push_back(Store);
6738 
6739           // Float varargs are always shadowed in available integer registers
6740           if (GPR_idx != NumGPRs) {
6741             SDValue Load =
6742                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6743             MemOpChains.push_back(Load.getValue(1));
6744             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6745           }
6746           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6747             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6748             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6749             SDValue Load =
6750                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6751             MemOpChains.push_back(Load.getValue(1));
6752             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6753           }
6754         } else {
6755           // If we have any FPRs remaining, we may also have GPRs remaining.
6756           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6757           // GPRs.
6758           if (GPR_idx != NumGPRs)
6759             ++GPR_idx;
6760           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6761               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6762             ++GPR_idx;
6763         }
6764       } else
6765         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6766                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6767                          TailCallArguments, dl);
6768       if (isPPC64)
6769         ArgOffset += 8;
6770       else
6771         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6772       break;
6773     case MVT::v4f32:
6774     case MVT::v4i32:
6775     case MVT::v8i16:
6776     case MVT::v16i8:
6777       if (CFlags.IsVarArg) {
6778         // These go aligned on the stack, or in the corresponding R registers
6779         // when within range.  The Darwin PPC ABI doc claims they also go in
6780         // V registers; in fact gcc does this only for arguments that are
6781         // prototyped, not for those that match the ...  We do it for all
6782         // arguments, seems to work.
6783         while (ArgOffset % 16 !=0) {
6784           ArgOffset += PtrByteSize;
6785           if (GPR_idx != NumGPRs)
6786             GPR_idx++;
6787         }
6788         // We could elide this store in the case where the object fits
6789         // entirely in R registers.  Maybe later.
6790         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6791                              DAG.getConstant(ArgOffset, dl, PtrVT));
6792         SDValue Store =
6793             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6794         MemOpChains.push_back(Store);
6795         if (VR_idx != NumVRs) {
6796           SDValue Load =
6797               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6798           MemOpChains.push_back(Load.getValue(1));
6799           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6800         }
6801         ArgOffset += 16;
6802         for (unsigned i=0; i<16; i+=PtrByteSize) {
6803           if (GPR_idx == NumGPRs)
6804             break;
6805           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6806                                    DAG.getConstant(i, dl, PtrVT));
6807           SDValue Load =
6808               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6809           MemOpChains.push_back(Load.getValue(1));
6810           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6811         }
6812         break;
6813       }
6814 
6815       // Non-varargs Altivec params generally go in registers, but have
6816       // stack space allocated at the end.
6817       if (VR_idx != NumVRs) {
6818         // Doesn't have GPR space allocated.
6819         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6820       } else if (nAltivecParamsAtEnd==0) {
6821         // We are emitting Altivec params in order.
6822         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6823                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6824                          TailCallArguments, dl);
6825         ArgOffset += 16;
6826       }
6827       break;
6828     }
6829   }
6830   // If all Altivec parameters fit in registers, as they usually do,
6831   // they get stack space following the non-Altivec parameters.  We
6832   // don't track this here because nobody below needs it.
6833   // If there are more Altivec parameters than fit in registers emit
6834   // the stores here.
6835   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6836     unsigned j = 0;
6837     // Offset is aligned; skip 1st 12 params which go in V registers.
6838     ArgOffset = ((ArgOffset+15)/16)*16;
6839     ArgOffset += 12*16;
6840     for (unsigned i = 0; i != NumOps; ++i) {
6841       SDValue Arg = OutVals[i];
6842       EVT ArgType = Outs[i].VT;
6843       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6844           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6845         if (++j > NumVRs) {
6846           SDValue PtrOff;
6847           // We are emitting Altivec params in order.
6848           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6849                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6850                            TailCallArguments, dl);
6851           ArgOffset += 16;
6852         }
6853       }
6854     }
6855   }
6856 
6857   if (!MemOpChains.empty())
6858     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6859 
6860   // On Darwin, R12 must contain the address of an indirect callee.  This does
6861   // not mean the MTCTR instruction must use R12; it's easier to model this as
6862   // an extra parameter, so do that.
6863   if (CFlags.IsIndirect) {
6864     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6865     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6866                                                    PPC::R12), Callee));
6867   }
6868 
6869   // Build a sequence of copy-to-reg nodes chained together with token chain
6870   // and flag operands which copy the outgoing args into the appropriate regs.
6871   SDValue InFlag;
6872   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6873     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6874                              RegsToPass[i].second, InFlag);
6875     InFlag = Chain.getValue(1);
6876   }
6877 
6878   if (CFlags.IsTailCall)
6879     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6880                     TailCallArguments);
6881 
6882   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6883                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6884 }
6885 
6886 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6887                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6888                    CCState &State) {
6889 
6890   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6891       State.getMachineFunction().getSubtarget());
6892   const bool IsPPC64 = Subtarget.isPPC64();
6893   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6894   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6895 
6896   assert((!ValVT.isInteger() ||
6897           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6898          "Integer argument exceeds register size: should have been legalized");
6899 
6900   if (ValVT == MVT::f128)
6901     report_fatal_error("f128 is unimplemented on AIX.");
6902 
6903   if (ArgFlags.isNest())
6904     report_fatal_error("Nest arguments are unimplemented.");
6905 
6906   if (ValVT.isVector() || LocVT.isVector())
6907     report_fatal_error("Vector arguments are unimplemented on AIX.");
6908 
6909   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6910                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6911                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6912   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6913                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6914                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6915 
6916   if (ArgFlags.isByVal()) {
6917     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6918       report_fatal_error("Pass-by-value arguments with alignment greater than "
6919                          "register width are not supported.");
6920 
6921     const unsigned ByValSize = ArgFlags.getByValSize();
6922 
6923     // An empty aggregate parameter takes up no storage and no registers,
6924     // but needs a MemLoc for a stack slot for the formal arguments side.
6925     if (ByValSize == 0) {
6926       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6927                                        State.getNextStackOffset(), RegVT,
6928                                        LocInfo));
6929       return false;
6930     }
6931 
6932     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6933     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6934     for (const unsigned E = Offset + StackSize; Offset < E;
6935          Offset += PtrAlign.value()) {
6936       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6937         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6938       else {
6939         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6940                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6941                                          LocInfo));
6942         break;
6943       }
6944     }
6945     return false;
6946   }
6947 
6948   // Arguments always reserve parameter save area.
6949   switch (ValVT.SimpleTy) {
6950   default:
6951     report_fatal_error("Unhandled value type for argument.");
6952   case MVT::i64:
6953     // i64 arguments should have been split to i32 for PPC32.
6954     assert(IsPPC64 && "PPC32 should have split i64 values.");
6955     LLVM_FALLTHROUGH;
6956   case MVT::i1:
6957   case MVT::i32: {
6958     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6959     // AIX integer arguments are always passed in register width.
6960     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6961       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6962                                   : CCValAssign::LocInfo::ZExt;
6963     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6964       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6965     else
6966       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6967 
6968     return false;
6969   }
6970   case MVT::f32:
6971   case MVT::f64: {
6972     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6973     const unsigned StoreSize = LocVT.getStoreSize();
6974     // Floats are always 4-byte aligned in the PSA on AIX.
6975     // This includes f64 in 64-bit mode for ABI compatibility.
6976     const unsigned Offset =
6977         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6978     unsigned FReg = State.AllocateReg(FPR);
6979     if (FReg)
6980       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6981 
6982     // Reserve and initialize GPRs or initialize the PSA as required.
6983     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6984       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6985         assert(FReg && "An FPR should be available when a GPR is reserved.");
6986         if (State.isVarArg()) {
6987           // Successfully reserved GPRs are only initialized for vararg calls.
6988           // Custom handling is required for:
6989           //   f64 in PPC32 needs to be split into 2 GPRs.
6990           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6991           State.addLoc(
6992               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6993         }
6994       } else {
6995         // If there are insufficient GPRs, the PSA needs to be initialized.
6996         // Initialization occurs even if an FPR was initialized for
6997         // compatibility with the AIX XL compiler. The full memory for the
6998         // argument will be initialized even if a prior word is saved in GPR.
6999         // A custom memLoc is used when the argument also passes in FPR so
7000         // that the callee handling can skip over it easily.
7001         State.addLoc(
7002             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7003                                              LocInfo)
7004                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7005         break;
7006       }
7007     }
7008 
7009     return false;
7010   }
7011   }
7012   return true;
7013 }
7014 
7015 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7016                                                     bool IsPPC64) {
7017   assert((IsPPC64 || SVT != MVT::i64) &&
7018          "i64 should have been split for 32-bit codegen.");
7019 
7020   switch (SVT) {
7021   default:
7022     report_fatal_error("Unexpected value type for formal argument");
7023   case MVT::i1:
7024   case MVT::i32:
7025   case MVT::i64:
7026     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7027   case MVT::f32:
7028     return &PPC::F4RCRegClass;
7029   case MVT::f64:
7030     return &PPC::F8RCRegClass;
7031   }
7032 }
7033 
7034 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7035                                         SelectionDAG &DAG, SDValue ArgValue,
7036                                         MVT LocVT, const SDLoc &dl) {
7037   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7038   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7039 
7040   if (Flags.isSExt())
7041     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7042                            DAG.getValueType(ValVT));
7043   else if (Flags.isZExt())
7044     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7045                            DAG.getValueType(ValVT));
7046 
7047   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7048 }
7049 
7050 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7051   const unsigned LASize = FL->getLinkageSize();
7052 
7053   if (PPC::GPRCRegClass.contains(Reg)) {
7054     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7055            "Reg must be a valid argument register!");
7056     return LASize + 4 * (Reg - PPC::R3);
7057   }
7058 
7059   if (PPC::G8RCRegClass.contains(Reg)) {
7060     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7061            "Reg must be a valid argument register!");
7062     return LASize + 8 * (Reg - PPC::X3);
7063   }
7064 
7065   llvm_unreachable("Only general purpose registers expected.");
7066 }
7067 
7068 //   AIX ABI Stack Frame Layout:
7069 //
7070 //   Low Memory +--------------------------------------------+
7071 //   SP   +---> | Back chain                                 | ---+
7072 //        |     +--------------------------------------------+    |
7073 //        |     | Saved Condition Register                   |    |
7074 //        |     +--------------------------------------------+    |
7075 //        |     | Saved Linkage Register                     |    |
7076 //        |     +--------------------------------------------+    | Linkage Area
7077 //        |     | Reserved for compilers                     |    |
7078 //        |     +--------------------------------------------+    |
7079 //        |     | Reserved for binders                       |    |
7080 //        |     +--------------------------------------------+    |
7081 //        |     | Saved TOC pointer                          | ---+
7082 //        |     +--------------------------------------------+
7083 //        |     | Parameter save area                        |
7084 //        |     +--------------------------------------------+
7085 //        |     | Alloca space                               |
7086 //        |     +--------------------------------------------+
7087 //        |     | Local variable space                       |
7088 //        |     +--------------------------------------------+
7089 //        |     | Float/int conversion temporary             |
7090 //        |     +--------------------------------------------+
7091 //        |     | Save area for AltiVec registers            |
7092 //        |     +--------------------------------------------+
7093 //        |     | AltiVec alignment padding                  |
7094 //        |     +--------------------------------------------+
7095 //        |     | Save area for VRSAVE register              |
7096 //        |     +--------------------------------------------+
7097 //        |     | Save area for General Purpose registers    |
7098 //        |     +--------------------------------------------+
7099 //        |     | Save area for Floating Point registers     |
7100 //        |     +--------------------------------------------+
7101 //        +---- | Back chain                                 |
7102 // High Memory  +--------------------------------------------+
7103 //
7104 //  Specifications:
7105 //  AIX 7.2 Assembler Language Reference
7106 //  Subroutine linkage convention
7107 
7108 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7109     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7110     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7111     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7112 
7113   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7114           CallConv == CallingConv::Fast) &&
7115          "Unexpected calling convention!");
7116 
7117   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7118     report_fatal_error("Tail call support is unimplemented on AIX.");
7119 
7120   if (useSoftFloat())
7121     report_fatal_error("Soft float support is unimplemented on AIX.");
7122 
7123   const PPCSubtarget &Subtarget =
7124       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7125 
7126   const bool IsPPC64 = Subtarget.isPPC64();
7127   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7128 
7129   // Assign locations to all of the incoming arguments.
7130   SmallVector<CCValAssign, 16> ArgLocs;
7131   MachineFunction &MF = DAG.getMachineFunction();
7132   MachineFrameInfo &MFI = MF.getFrameInfo();
7133   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7134 
7135   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7136   // Reserve space for the linkage area on the stack.
7137   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7138   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7139   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7140 
7141   SmallVector<SDValue, 8> MemOps;
7142 
7143   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7144     CCValAssign &VA = ArgLocs[I++];
7145     MVT LocVT = VA.getLocVT();
7146     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7147 
7148     // For compatibility with the AIX XL compiler, the float args in the
7149     // parameter save area are initialized even if the argument is available
7150     // in register.  The caller is required to initialize both the register
7151     // and memory, however, the callee can choose to expect it in either.
7152     // The memloc is dismissed here because the argument is retrieved from
7153     // the register.
7154     if (VA.isMemLoc() && VA.needsCustom())
7155       continue;
7156 
7157     if (Flags.isByVal() && VA.isMemLoc()) {
7158       const unsigned Size =
7159           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7160                   PtrByteSize);
7161       const int FI = MF.getFrameInfo().CreateFixedObject(
7162           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7163           /* IsAliased */ true);
7164       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7165       InVals.push_back(FIN);
7166 
7167       continue;
7168     }
7169 
7170     if (Flags.isByVal()) {
7171       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7172 
7173       const MCPhysReg ArgReg = VA.getLocReg();
7174       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7175 
7176       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7177         report_fatal_error("Over aligned byvals not supported yet.");
7178 
7179       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7180       const int FI = MF.getFrameInfo().CreateFixedObject(
7181           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7182           /* IsAliased */ true);
7183       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7184       InVals.push_back(FIN);
7185 
7186       // Add live ins for all the RegLocs for the same ByVal.
7187       const TargetRegisterClass *RegClass =
7188           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7189 
7190       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7191                                                unsigned Offset) {
7192         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7193         // Since the callers side has left justified the aggregate in the
7194         // register, we can simply store the entire register into the stack
7195         // slot.
7196         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7197         // The store to the fixedstack object is needed becuase accessing a
7198         // field of the ByVal will use a gep and load. Ideally we will optimize
7199         // to extracting the value from the register directly, and elide the
7200         // stores when the arguments address is not taken, but that will need to
7201         // be future work.
7202         SDValue Store = DAG.getStore(
7203             CopyFrom.getValue(1), dl, CopyFrom,
7204             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7205             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7206 
7207         MemOps.push_back(Store);
7208       };
7209 
7210       unsigned Offset = 0;
7211       HandleRegLoc(VA.getLocReg(), Offset);
7212       Offset += PtrByteSize;
7213       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7214            Offset += PtrByteSize) {
7215         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7216                "RegLocs should be for ByVal argument.");
7217 
7218         const CCValAssign RL = ArgLocs[I++];
7219         HandleRegLoc(RL.getLocReg(), Offset);
7220       }
7221 
7222       if (Offset != StackSize) {
7223         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7224                "Expected MemLoc for remaining bytes.");
7225         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7226         // Consume the MemLoc.The InVal has already been emitted, so nothing
7227         // more needs to be done.
7228         ++I;
7229       }
7230 
7231       continue;
7232     }
7233 
7234     EVT ValVT = VA.getValVT();
7235     if (VA.isRegLoc() && !VA.needsCustom()) {
7236       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7237       unsigned VReg =
7238           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7239       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7240       if (ValVT.isScalarInteger() &&
7241           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7242         ArgValue =
7243             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7244       }
7245       InVals.push_back(ArgValue);
7246       continue;
7247     }
7248     if (VA.isMemLoc()) {
7249       const unsigned LocSize = LocVT.getStoreSize();
7250       const unsigned ValSize = ValVT.getStoreSize();
7251       assert((ValSize <= LocSize) &&
7252              "Object size is larger than size of MemLoc");
7253       int CurArgOffset = VA.getLocMemOffset();
7254       // Objects are right-justified because AIX is big-endian.
7255       if (LocSize > ValSize)
7256         CurArgOffset += LocSize - ValSize;
7257       // Potential tail calls could cause overwriting of argument stack slots.
7258       const bool IsImmutable =
7259           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7260             (CallConv == CallingConv::Fast));
7261       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7262       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7263       SDValue ArgValue =
7264           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7265       InVals.push_back(ArgValue);
7266       continue;
7267     }
7268   }
7269 
7270   // On AIX a minimum of 8 words is saved to the parameter save area.
7271   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7272   // Area that is at least reserved in the caller of this function.
7273   unsigned CallerReservedArea =
7274       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7275 
7276   // Set the size that is at least reserved in caller of this function. Tail
7277   // call optimized function's reserved stack space needs to be aligned so
7278   // that taking the difference between two stack areas will result in an
7279   // aligned stack.
7280   CallerReservedArea =
7281       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7282   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7283   FuncInfo->setMinReservedArea(CallerReservedArea);
7284 
7285   if (isVarArg) {
7286     FuncInfo->setVarArgsFrameIndex(
7287         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7288     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7289 
7290     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7291                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7292 
7293     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7294                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7295     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7296 
7297     // The fixed integer arguments of a variadic function are stored to the
7298     // VarArgsFrameIndex on the stack so that they may be loaded by
7299     // dereferencing the result of va_next.
7300     for (unsigned GPRIndex =
7301              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7302          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7303 
7304       const unsigned VReg =
7305           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7306                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7307 
7308       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7309       SDValue Store =
7310           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7311       MemOps.push_back(Store);
7312       // Increment the address for the next argument to store.
7313       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7314       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7315     }
7316   }
7317 
7318   if (!MemOps.empty())
7319     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7320 
7321   return Chain;
7322 }
7323 
7324 SDValue PPCTargetLowering::LowerCall_AIX(
7325     SDValue Chain, SDValue Callee, CallFlags CFlags,
7326     const SmallVectorImpl<ISD::OutputArg> &Outs,
7327     const SmallVectorImpl<SDValue> &OutVals,
7328     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7329     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7330     const CallBase *CB) const {
7331   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7332   // AIX ABI stack frame layout.
7333 
7334   assert((CFlags.CallConv == CallingConv::C ||
7335           CFlags.CallConv == CallingConv::Cold ||
7336           CFlags.CallConv == CallingConv::Fast) &&
7337          "Unexpected calling convention!");
7338 
7339   if (CFlags.IsPatchPoint)
7340     report_fatal_error("This call type is unimplemented on AIX.");
7341 
7342   const PPCSubtarget& Subtarget =
7343       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7344   if (Subtarget.hasAltivec())
7345     report_fatal_error("Altivec support is unimplemented on AIX.");
7346 
7347   MachineFunction &MF = DAG.getMachineFunction();
7348   SmallVector<CCValAssign, 16> ArgLocs;
7349   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7350                  *DAG.getContext());
7351 
7352   // Reserve space for the linkage save area (LSA) on the stack.
7353   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7354   //   [SP][CR][LR][2 x reserved][TOC].
7355   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7356   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7357   const bool IsPPC64 = Subtarget.isPPC64();
7358   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7359   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7360   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7361   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7362 
7363   // The prolog code of the callee may store up to 8 GPR argument registers to
7364   // the stack, allowing va_start to index over them in memory if the callee
7365   // is variadic.
7366   // Because we cannot tell if this is needed on the caller side, we have to
7367   // conservatively assume that it is needed.  As such, make sure we have at
7368   // least enough stack space for the caller to store the 8 GPRs.
7369   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7370   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7371                                      CCInfo.getNextStackOffset());
7372 
7373   // Adjust the stack pointer for the new arguments...
7374   // These operations are automatically eliminated by the prolog/epilog pass.
7375   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7376   SDValue CallSeqStart = Chain;
7377 
7378   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7379   SmallVector<SDValue, 8> MemOpChains;
7380 
7381   // Set up a copy of the stack pointer for loading and storing any
7382   // arguments that may not fit in the registers available for argument
7383   // passing.
7384   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7385                                    : DAG.getRegister(PPC::R1, MVT::i32);
7386 
7387   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7388     const unsigned ValNo = ArgLocs[I].getValNo();
7389     SDValue Arg = OutVals[ValNo];
7390     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7391 
7392     if (Flags.isByVal()) {
7393       const unsigned ByValSize = Flags.getByValSize();
7394 
7395       // Nothing to do for zero-sized ByVals on the caller side.
7396       if (!ByValSize) {
7397         ++I;
7398         continue;
7399       }
7400 
7401       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7402         return DAG.getExtLoad(
7403             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7404             (LoadOffset != 0)
7405                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7406                 : Arg,
7407             MachinePointerInfo(), VT);
7408       };
7409 
7410       unsigned LoadOffset = 0;
7411 
7412       // Initialize registers, which are fully occupied by the by-val argument.
7413       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7414         SDValue Load = GetLoad(PtrVT, LoadOffset);
7415         MemOpChains.push_back(Load.getValue(1));
7416         LoadOffset += PtrByteSize;
7417         const CCValAssign &ByValVA = ArgLocs[I++];
7418         assert(ByValVA.getValNo() == ValNo &&
7419                "Unexpected location for pass-by-value argument.");
7420         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7421       }
7422 
7423       if (LoadOffset == ByValSize)
7424         continue;
7425 
7426       // There must be one more loc to handle the remainder.
7427       assert(ArgLocs[I].getValNo() == ValNo &&
7428              "Expected additional location for by-value argument.");
7429 
7430       if (ArgLocs[I].isMemLoc()) {
7431         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7432         const CCValAssign &ByValVA = ArgLocs[I++];
7433         ISD::ArgFlagsTy MemcpyFlags = Flags;
7434         // Only memcpy the bytes that don't pass in register.
7435         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7436         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7437             (LoadOffset != 0)
7438                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7439                 : Arg,
7440             DAG.getObjectPtrOffset(dl, StackPtr,
7441                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7442             CallSeqStart, MemcpyFlags, DAG, dl);
7443         continue;
7444       }
7445 
7446       // Initialize the final register residue.
7447       // Any residue that occupies the final by-val arg register must be
7448       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7449       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7450       // 2 and 1 byte loads.
7451       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7452       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7453              "Unexpected register residue for by-value argument.");
7454       SDValue ResidueVal;
7455       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7456         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7457         const MVT VT =
7458             N == 1 ? MVT::i8
7459                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7460         SDValue Load = GetLoad(VT, LoadOffset);
7461         MemOpChains.push_back(Load.getValue(1));
7462         LoadOffset += N;
7463         Bytes += N;
7464 
7465         // By-val arguments are passed left-justfied in register.
7466         // Every load here needs to be shifted, otherwise a full register load
7467         // should have been used.
7468         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7469                "Unexpected load emitted during handling of pass-by-value "
7470                "argument.");
7471         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7472         EVT ShiftAmountTy =
7473             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7474         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7475         SDValue ShiftedLoad =
7476             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7477         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7478                                               ShiftedLoad)
7479                                 : ShiftedLoad;
7480       }
7481 
7482       const CCValAssign &ByValVA = ArgLocs[I++];
7483       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7484       continue;
7485     }
7486 
7487     CCValAssign &VA = ArgLocs[I++];
7488     const MVT LocVT = VA.getLocVT();
7489     const MVT ValVT = VA.getValVT();
7490 
7491     switch (VA.getLocInfo()) {
7492     default:
7493       report_fatal_error("Unexpected argument extension type.");
7494     case CCValAssign::Full:
7495       break;
7496     case CCValAssign::ZExt:
7497       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7498       break;
7499     case CCValAssign::SExt:
7500       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7501       break;
7502     }
7503 
7504     if (VA.isRegLoc() && !VA.needsCustom()) {
7505       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7506       continue;
7507     }
7508 
7509     if (VA.isMemLoc()) {
7510       SDValue PtrOff =
7511           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7512       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7513       MemOpChains.push_back(
7514           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7515 
7516       continue;
7517     }
7518 
7519     // Custom handling is used for GPR initializations for vararg float
7520     // arguments.
7521     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7522            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7523            "Unexpected register handling for calling convention.");
7524 
7525     SDValue ArgAsInt =
7526         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7527 
7528     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7529       // f32 in 32-bit GPR
7530       // f64 in 64-bit GPR
7531       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7532     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7533       // f32 in 64-bit GPR.
7534       RegsToPass.push_back(std::make_pair(
7535           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7536     else {
7537       // f64 in two 32-bit GPRs
7538       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7539       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7540              "Unexpected custom register for argument!");
7541       CCValAssign &GPR1 = VA;
7542       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7543                                      DAG.getConstant(32, dl, MVT::i8));
7544       RegsToPass.push_back(std::make_pair(
7545           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7546 
7547       if (I != E) {
7548         // If only 1 GPR was available, there will only be one custom GPR and
7549         // the argument will also pass in memory.
7550         CCValAssign &PeekArg = ArgLocs[I];
7551         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7552           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7553           CCValAssign &GPR2 = ArgLocs[I++];
7554           RegsToPass.push_back(std::make_pair(
7555               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7556         }
7557       }
7558     }
7559   }
7560 
7561   if (!MemOpChains.empty())
7562     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7563 
7564   // For indirect calls, we need to save the TOC base to the stack for
7565   // restoration after the call.
7566   if (CFlags.IsIndirect) {
7567     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7568     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7569     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7570     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7571     const unsigned TOCSaveOffset =
7572         Subtarget.getFrameLowering()->getTOCSaveOffset();
7573 
7574     setUsesTOCBasePtr(DAG);
7575     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7576     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7577     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7578     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7579     Chain = DAG.getStore(
7580         Val.getValue(1), dl, Val, AddPtr,
7581         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7582   }
7583 
7584   // Build a sequence of copy-to-reg nodes chained together with token chain
7585   // and flag operands which copy the outgoing args into the appropriate regs.
7586   SDValue InFlag;
7587   for (auto Reg : RegsToPass) {
7588     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7589     InFlag = Chain.getValue(1);
7590   }
7591 
7592   const int SPDiff = 0;
7593   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7594                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7595 }
7596 
7597 bool
7598 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7599                                   MachineFunction &MF, bool isVarArg,
7600                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7601                                   LLVMContext &Context) const {
7602   SmallVector<CCValAssign, 16> RVLocs;
7603   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7604   return CCInfo.CheckReturn(
7605       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7606                 ? RetCC_PPC_Cold
7607                 : RetCC_PPC);
7608 }
7609 
7610 SDValue
7611 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7612                                bool isVarArg,
7613                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7614                                const SmallVectorImpl<SDValue> &OutVals,
7615                                const SDLoc &dl, SelectionDAG &DAG) const {
7616   SmallVector<CCValAssign, 16> RVLocs;
7617   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7618                  *DAG.getContext());
7619   CCInfo.AnalyzeReturn(Outs,
7620                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7621                            ? RetCC_PPC_Cold
7622                            : RetCC_PPC);
7623 
7624   SDValue Flag;
7625   SmallVector<SDValue, 4> RetOps(1, Chain);
7626 
7627   // Copy the result values into the output registers.
7628   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7629     CCValAssign &VA = RVLocs[i];
7630     assert(VA.isRegLoc() && "Can only return in registers!");
7631 
7632     SDValue Arg = OutVals[RealResIdx];
7633 
7634     switch (VA.getLocInfo()) {
7635     default: llvm_unreachable("Unknown loc info!");
7636     case CCValAssign::Full: break;
7637     case CCValAssign::AExt:
7638       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7639       break;
7640     case CCValAssign::ZExt:
7641       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7642       break;
7643     case CCValAssign::SExt:
7644       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7645       break;
7646     }
7647     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7648       bool isLittleEndian = Subtarget.isLittleEndian();
7649       // Legalize ret f64 -> ret 2 x i32.
7650       SDValue SVal =
7651           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7652                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7653       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7654       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7655       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7656                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7657       Flag = Chain.getValue(1);
7658       VA = RVLocs[++i]; // skip ahead to next loc
7659       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7660     } else
7661       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7662     Flag = Chain.getValue(1);
7663     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7664   }
7665 
7666   RetOps[0] = Chain;  // Update chain.
7667 
7668   // Add the flag if we have it.
7669   if (Flag.getNode())
7670     RetOps.push_back(Flag);
7671 
7672   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7673 }
7674 
7675 SDValue
7676 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7677                                                 SelectionDAG &DAG) const {
7678   SDLoc dl(Op);
7679 
7680   // Get the correct type for integers.
7681   EVT IntVT = Op.getValueType();
7682 
7683   // Get the inputs.
7684   SDValue Chain = Op.getOperand(0);
7685   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7686   // Build a DYNAREAOFFSET node.
7687   SDValue Ops[2] = {Chain, FPSIdx};
7688   SDVTList VTs = DAG.getVTList(IntVT);
7689   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7690 }
7691 
7692 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7693                                              SelectionDAG &DAG) const {
7694   // When we pop the dynamic allocation we need to restore the SP link.
7695   SDLoc dl(Op);
7696 
7697   // Get the correct type for pointers.
7698   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7699 
7700   // Construct the stack pointer operand.
7701   bool isPPC64 = Subtarget.isPPC64();
7702   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7703   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7704 
7705   // Get the operands for the STACKRESTORE.
7706   SDValue Chain = Op.getOperand(0);
7707   SDValue SaveSP = Op.getOperand(1);
7708 
7709   // Load the old link SP.
7710   SDValue LoadLinkSP =
7711       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7712 
7713   // Restore the stack pointer.
7714   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7715 
7716   // Store the old link SP.
7717   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7718 }
7719 
7720 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7721   MachineFunction &MF = DAG.getMachineFunction();
7722   bool isPPC64 = Subtarget.isPPC64();
7723   EVT PtrVT = getPointerTy(MF.getDataLayout());
7724 
7725   // Get current frame pointer save index.  The users of this index will be
7726   // primarily DYNALLOC instructions.
7727   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7728   int RASI = FI->getReturnAddrSaveIndex();
7729 
7730   // If the frame pointer save index hasn't been defined yet.
7731   if (!RASI) {
7732     // Find out what the fix offset of the frame pointer save area.
7733     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7734     // Allocate the frame index for frame pointer save area.
7735     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7736     // Save the result.
7737     FI->setReturnAddrSaveIndex(RASI);
7738   }
7739   return DAG.getFrameIndex(RASI, PtrVT);
7740 }
7741 
7742 SDValue
7743 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7744   MachineFunction &MF = DAG.getMachineFunction();
7745   bool isPPC64 = Subtarget.isPPC64();
7746   EVT PtrVT = getPointerTy(MF.getDataLayout());
7747 
7748   // Get current frame pointer save index.  The users of this index will be
7749   // primarily DYNALLOC instructions.
7750   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7751   int FPSI = FI->getFramePointerSaveIndex();
7752 
7753   // If the frame pointer save index hasn't been defined yet.
7754   if (!FPSI) {
7755     // Find out what the fix offset of the frame pointer save area.
7756     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7757     // Allocate the frame index for frame pointer save area.
7758     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7759     // Save the result.
7760     FI->setFramePointerSaveIndex(FPSI);
7761   }
7762   return DAG.getFrameIndex(FPSI, PtrVT);
7763 }
7764 
7765 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7766                                                    SelectionDAG &DAG) const {
7767   MachineFunction &MF = DAG.getMachineFunction();
7768   // Get the inputs.
7769   SDValue Chain = Op.getOperand(0);
7770   SDValue Size  = Op.getOperand(1);
7771   SDLoc dl(Op);
7772 
7773   // Get the correct type for pointers.
7774   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7775   // Negate the size.
7776   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7777                                 DAG.getConstant(0, dl, PtrVT), Size);
7778   // Construct a node for the frame pointer save index.
7779   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7780   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7781   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7782   if (hasInlineStackProbe(MF))
7783     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7784   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7785 }
7786 
7787 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7788                                                      SelectionDAG &DAG) const {
7789   MachineFunction &MF = DAG.getMachineFunction();
7790 
7791   bool isPPC64 = Subtarget.isPPC64();
7792   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7793 
7794   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7795   return DAG.getFrameIndex(FI, PtrVT);
7796 }
7797 
7798 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7799                                                SelectionDAG &DAG) const {
7800   SDLoc DL(Op);
7801   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7802                      DAG.getVTList(MVT::i32, MVT::Other),
7803                      Op.getOperand(0), Op.getOperand(1));
7804 }
7805 
7806 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7807                                                 SelectionDAG &DAG) const {
7808   SDLoc DL(Op);
7809   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7810                      Op.getOperand(0), Op.getOperand(1));
7811 }
7812 
7813 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7814 
7815   assert(Op.getValueType() == MVT::i1 &&
7816          "Custom lowering only for i1 loads");
7817 
7818   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7819 
7820   SDLoc dl(Op);
7821   LoadSDNode *LD = cast<LoadSDNode>(Op);
7822 
7823   SDValue Chain = LD->getChain();
7824   SDValue BasePtr = LD->getBasePtr();
7825   MachineMemOperand *MMO = LD->getMemOperand();
7826 
7827   SDValue NewLD =
7828       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7829                      BasePtr, MVT::i8, MMO);
7830   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7831 
7832   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7833   return DAG.getMergeValues(Ops, dl);
7834 }
7835 
7836 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7837   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7838          "Custom lowering only for i1 stores");
7839 
7840   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7841 
7842   SDLoc dl(Op);
7843   StoreSDNode *ST = cast<StoreSDNode>(Op);
7844 
7845   SDValue Chain = ST->getChain();
7846   SDValue BasePtr = ST->getBasePtr();
7847   SDValue Value = ST->getValue();
7848   MachineMemOperand *MMO = ST->getMemOperand();
7849 
7850   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7851                       Value);
7852   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7853 }
7854 
7855 // FIXME: Remove this once the ANDI glue bug is fixed:
7856 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7857   assert(Op.getValueType() == MVT::i1 &&
7858          "Custom lowering only for i1 results");
7859 
7860   SDLoc DL(Op);
7861   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7862 }
7863 
7864 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7865                                                SelectionDAG &DAG) const {
7866 
7867   // Implements a vector truncate that fits in a vector register as a shuffle.
7868   // We want to legalize vector truncates down to where the source fits in
7869   // a vector register (and target is therefore smaller than vector register
7870   // size).  At that point legalization will try to custom lower the sub-legal
7871   // result and get here - where we can contain the truncate as a single target
7872   // operation.
7873 
7874   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7875   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7876   //
7877   // We will implement it for big-endian ordering as this (where x denotes
7878   // undefined):
7879   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7880   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7881   //
7882   // The same operation in little-endian ordering will be:
7883   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7884   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7885 
7886   EVT TrgVT = Op.getValueType();
7887   assert(TrgVT.isVector() && "Vector type expected.");
7888   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7889   EVT EltVT = TrgVT.getVectorElementType();
7890   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7891       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7892       !isPowerOf2_32(EltVT.getSizeInBits()))
7893     return SDValue();
7894 
7895   SDValue N1 = Op.getOperand(0);
7896   EVT SrcVT = N1.getValueType();
7897   unsigned SrcSize = SrcVT.getSizeInBits();
7898   if (SrcSize > 256 ||
7899       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7900       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7901     return SDValue();
7902   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7903     return SDValue();
7904 
7905   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7906   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7907 
7908   SDLoc DL(Op);
7909   SDValue Op1, Op2;
7910   if (SrcSize == 256) {
7911     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7912     EVT SplitVT =
7913         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7914     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7915     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7916                       DAG.getConstant(0, DL, VecIdxTy));
7917     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7918                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7919   }
7920   else {
7921     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7922     Op2 = DAG.getUNDEF(WideVT);
7923   }
7924 
7925   // First list the elements we want to keep.
7926   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7927   SmallVector<int, 16> ShuffV;
7928   if (Subtarget.isLittleEndian())
7929     for (unsigned i = 0; i < TrgNumElts; ++i)
7930       ShuffV.push_back(i * SizeMult);
7931   else
7932     for (unsigned i = 1; i <= TrgNumElts; ++i)
7933       ShuffV.push_back(i * SizeMult - 1);
7934 
7935   // Populate the remaining elements with undefs.
7936   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7937     // ShuffV.push_back(i + WideNumElts);
7938     ShuffV.push_back(WideNumElts + 1);
7939 
7940   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7941   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7942   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7943 }
7944 
7945 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7946 /// possible.
7947 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7948   // Not FP, or using SPE? Not a fsel.
7949   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7950       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7951     return Op;
7952 
7953   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7954 
7955   EVT ResVT = Op.getValueType();
7956   EVT CmpVT = Op.getOperand(0).getValueType();
7957   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7958   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7959   SDLoc dl(Op);
7960   SDNodeFlags Flags = Op.getNode()->getFlags();
7961 
7962   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7963   // presence of infinities.
7964   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7965     switch (CC) {
7966     default:
7967       break;
7968     case ISD::SETOGT:
7969     case ISD::SETGT:
7970       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7971     case ISD::SETOLT:
7972     case ISD::SETLT:
7973       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7974     }
7975   }
7976 
7977   // We might be able to do better than this under some circumstances, but in
7978   // general, fsel-based lowering of select is a finite-math-only optimization.
7979   // For more information, see section F.3 of the 2.06 ISA specification.
7980   // With ISA 3.0
7981   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7982       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7983     return Op;
7984 
7985   // If the RHS of the comparison is a 0.0, we don't need to do the
7986   // subtraction at all.
7987   SDValue Sel1;
7988   if (isFloatingPointZero(RHS))
7989     switch (CC) {
7990     default: break;       // SETUO etc aren't handled by fsel.
7991     case ISD::SETNE:
7992       std::swap(TV, FV);
7993       LLVM_FALLTHROUGH;
7994     case ISD::SETEQ:
7995       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7996         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7997       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7998       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7999         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8000       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8001                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8002     case ISD::SETULT:
8003     case ISD::SETLT:
8004       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8005       LLVM_FALLTHROUGH;
8006     case ISD::SETOGE:
8007     case ISD::SETGE:
8008       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8009         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8010       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8011     case ISD::SETUGT:
8012     case ISD::SETGT:
8013       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8014       LLVM_FALLTHROUGH;
8015     case ISD::SETOLE:
8016     case ISD::SETLE:
8017       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8018         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8019       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8020                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8021     }
8022 
8023   SDValue Cmp;
8024   switch (CC) {
8025   default: break;       // SETUO etc aren't handled by fsel.
8026   case ISD::SETNE:
8027     std::swap(TV, FV);
8028     LLVM_FALLTHROUGH;
8029   case ISD::SETEQ:
8030     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8031     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8032       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8033     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8034     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8035       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8036     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8037                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8038   case ISD::SETULT:
8039   case ISD::SETLT:
8040     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8041     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8042       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8043     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8044   case ISD::SETOGE:
8045   case ISD::SETGE:
8046     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8047     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8048       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8049     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8050   case ISD::SETUGT:
8051   case ISD::SETGT:
8052     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8053     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8054       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8055     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8056   case ISD::SETOLE:
8057   case ISD::SETLE:
8058     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8059     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8060       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8061     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8062   }
8063   return Op;
8064 }
8065 
8066 static unsigned getPPCStrictOpcode(unsigned Opc) {
8067   switch (Opc) {
8068   default:
8069     llvm_unreachable("No strict version of this opcode!");
8070   case PPCISD::FCTIDZ:
8071     return PPCISD::STRICT_FCTIDZ;
8072   case PPCISD::FCTIWZ:
8073     return PPCISD::STRICT_FCTIWZ;
8074   case PPCISD::FCTIDUZ:
8075     return PPCISD::STRICT_FCTIDUZ;
8076   case PPCISD::FCTIWUZ:
8077     return PPCISD::STRICT_FCTIWUZ;
8078   case PPCISD::FCFID:
8079     return PPCISD::STRICT_FCFID;
8080   case PPCISD::FCFIDU:
8081     return PPCISD::STRICT_FCFIDU;
8082   case PPCISD::FCFIDS:
8083     return PPCISD::STRICT_FCFIDS;
8084   case PPCISD::FCFIDUS:
8085     return PPCISD::STRICT_FCFIDUS;
8086   }
8087 }
8088 
8089 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8090                               const PPCSubtarget &Subtarget) {
8091   SDLoc dl(Op);
8092   bool IsStrict = Op->isStrictFPOpcode();
8093   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8094                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8095 
8096   // TODO: Any other flags to propagate?
8097   SDNodeFlags Flags;
8098   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8099 
8100   // For strict nodes, source is the second operand.
8101   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8102   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8103   assert(Src.getValueType().isFloatingPoint());
8104   if (Src.getValueType() == MVT::f32) {
8105     if (IsStrict) {
8106       Src =
8107           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8108                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8109       Chain = Src.getValue(1);
8110     } else
8111       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8112   }
8113   SDValue Conv;
8114   unsigned Opc = ISD::DELETED_NODE;
8115   switch (Op.getSimpleValueType().SimpleTy) {
8116   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8117   case MVT::i32:
8118     Opc = IsSigned ? PPCISD::FCTIWZ
8119                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8120     break;
8121   case MVT::i64:
8122     assert((IsSigned || Subtarget.hasFPCVT()) &&
8123            "i64 FP_TO_UINT is supported only with FPCVT");
8124     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8125   }
8126   if (IsStrict) {
8127     Opc = getPPCStrictOpcode(Opc);
8128     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8129                        {Chain, Src}, Flags);
8130   } else {
8131     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8132   }
8133   return Conv;
8134 }
8135 
8136 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8137                                                SelectionDAG &DAG,
8138                                                const SDLoc &dl) const {
8139   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8140   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8141                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8142   bool IsStrict = Op->isStrictFPOpcode();
8143 
8144   // Convert the FP value to an int value through memory.
8145   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8146                   (IsSigned || Subtarget.hasFPCVT());
8147   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8148   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8149   MachinePointerInfo MPI =
8150       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8151 
8152   // Emit a store to the stack slot.
8153   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8154   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8155   if (i32Stack) {
8156     MachineFunction &MF = DAG.getMachineFunction();
8157     Alignment = Align(4);
8158     MachineMemOperand *MMO =
8159         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8160     SDValue Ops[] = { Chain, Tmp, FIPtr };
8161     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8162               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8163   } else
8164     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8165 
8166   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8167   // add in a bias on big endian.
8168   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8169     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8170                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8171     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8172   }
8173 
8174   RLI.Chain = Chain;
8175   RLI.Ptr = FIPtr;
8176   RLI.MPI = MPI;
8177   RLI.Alignment = Alignment;
8178 }
8179 
8180 /// Custom lowers floating point to integer conversions to use
8181 /// the direct move instructions available in ISA 2.07 to avoid the
8182 /// need for load/store combinations.
8183 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8184                                                     SelectionDAG &DAG,
8185                                                     const SDLoc &dl) const {
8186   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8187   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8188   if (Op->isStrictFPOpcode())
8189     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8190   else
8191     return Mov;
8192 }
8193 
8194 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8195                                           const SDLoc &dl) const {
8196   bool IsStrict = Op->isStrictFPOpcode();
8197   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8198                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8199   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8200   EVT SrcVT = Src.getValueType();
8201   EVT DstVT = Op.getValueType();
8202 
8203   // FP to INT conversions are legal for f128.
8204   if (SrcVT == MVT::f128)
8205     return Op;
8206 
8207   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8208   // PPC (the libcall is not available).
8209   if (SrcVT == MVT::ppcf128) {
8210     if (DstVT == MVT::i32) {
8211       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8212       // set other fast-math flags to FP operations in both strict and
8213       // non-strict cases. (FP_TO_SINT, FSUB)
8214       SDNodeFlags Flags;
8215       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8216 
8217       if (IsSigned) {
8218         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8219                                  DAG.getIntPtrConstant(0, dl));
8220         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8221                                  DAG.getIntPtrConstant(1, dl));
8222 
8223         // Add the two halves of the long double in round-to-zero mode, and use
8224         // a smaller FP_TO_SINT.
8225         if (IsStrict) {
8226           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8227                                     DAG.getVTList(MVT::f64, MVT::Other),
8228                                     {Op.getOperand(0), Lo, Hi}, Flags);
8229           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8230                              DAG.getVTList(MVT::i32, MVT::Other),
8231                              {Res.getValue(1), Res}, Flags);
8232         } else {
8233           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8234           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8235         }
8236       } else {
8237         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8238         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8239         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8240         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8241         if (IsStrict) {
8242           // Sel = Src < 0x80000000
8243           // FltOfs = select Sel, 0.0, 0x80000000
8244           // IntOfs = select Sel, 0, 0x80000000
8245           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8246           SDValue Chain = Op.getOperand(0);
8247           EVT SetCCVT =
8248               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8249           EVT DstSetCCVT =
8250               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8251           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8252                                      SDNodeFlags(), Chain, true);
8253           Chain = Sel.getValue(1);
8254 
8255           SDValue FltOfs = DAG.getSelect(
8256               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8257           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8258 
8259           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8260                                     DAG.getVTList(SrcVT, MVT::Other),
8261                                     {Chain, Src, FltOfs}, Flags);
8262           Chain = Val.getValue(1);
8263           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8264                                      DAG.getVTList(DstVT, MVT::Other),
8265                                      {Chain, Val}, Flags);
8266           Chain = SInt.getValue(1);
8267           SDValue IntOfs = DAG.getSelect(
8268               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8269           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8270           return DAG.getMergeValues({Result, Chain}, dl);
8271         } else {
8272           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8273           // FIXME: generated code sucks.
8274           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8275           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8276           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8277           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8278           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8279         }
8280       }
8281     }
8282 
8283     return SDValue();
8284   }
8285 
8286   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8287     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8288 
8289   ReuseLoadInfo RLI;
8290   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8291 
8292   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8293                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8294 }
8295 
8296 // We're trying to insert a regular store, S, and then a load, L. If the
8297 // incoming value, O, is a load, we might just be able to have our load use the
8298 // address used by O. However, we don't know if anything else will store to
8299 // that address before we can load from it. To prevent this situation, we need
8300 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8301 // the same chain operand as O, we create a token factor from the chain results
8302 // of O and L, and we replace all uses of O's chain result with that token
8303 // factor (see spliceIntoChain below for this last part).
8304 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8305                                             ReuseLoadInfo &RLI,
8306                                             SelectionDAG &DAG,
8307                                             ISD::LoadExtType ET) const {
8308   // Conservatively skip reusing for constrained FP nodes.
8309   if (Op->isStrictFPOpcode())
8310     return false;
8311 
8312   SDLoc dl(Op);
8313   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8314                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8315   if (ET == ISD::NON_EXTLOAD &&
8316       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8317       isOperationLegalOrCustom(Op.getOpcode(),
8318                                Op.getOperand(0).getValueType())) {
8319 
8320     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8321     return true;
8322   }
8323 
8324   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8325   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8326       LD->isNonTemporal())
8327     return false;
8328   if (LD->getMemoryVT() != MemVT)
8329     return false;
8330 
8331   RLI.Ptr = LD->getBasePtr();
8332   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8333     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8334            "Non-pre-inc AM on PPC?");
8335     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8336                           LD->getOffset());
8337   }
8338 
8339   RLI.Chain = LD->getChain();
8340   RLI.MPI = LD->getPointerInfo();
8341   RLI.IsDereferenceable = LD->isDereferenceable();
8342   RLI.IsInvariant = LD->isInvariant();
8343   RLI.Alignment = LD->getAlign();
8344   RLI.AAInfo = LD->getAAInfo();
8345   RLI.Ranges = LD->getRanges();
8346 
8347   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8348   return true;
8349 }
8350 
8351 // Given the head of the old chain, ResChain, insert a token factor containing
8352 // it and NewResChain, and make users of ResChain now be users of that token
8353 // factor.
8354 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8355 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8356                                         SDValue NewResChain,
8357                                         SelectionDAG &DAG) const {
8358   if (!ResChain)
8359     return;
8360 
8361   SDLoc dl(NewResChain);
8362 
8363   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8364                            NewResChain, DAG.getUNDEF(MVT::Other));
8365   assert(TF.getNode() != NewResChain.getNode() &&
8366          "A new TF really is required here");
8367 
8368   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8369   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8370 }
8371 
8372 /// Analyze profitability of direct move
8373 /// prefer float load to int load plus direct move
8374 /// when there is no integer use of int load
8375 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8376   SDNode *Origin = Op.getOperand(0).getNode();
8377   if (Origin->getOpcode() != ISD::LOAD)
8378     return true;
8379 
8380   // If there is no LXSIBZX/LXSIHZX, like Power8,
8381   // prefer direct move if the memory size is 1 or 2 bytes.
8382   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8383   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8384     return true;
8385 
8386   for (SDNode::use_iterator UI = Origin->use_begin(),
8387                             UE = Origin->use_end();
8388        UI != UE; ++UI) {
8389 
8390     // Only look at the users of the loaded value.
8391     if (UI.getUse().get().getResNo() != 0)
8392       continue;
8393 
8394     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8395         UI->getOpcode() != ISD::UINT_TO_FP &&
8396         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8397         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8398       return true;
8399   }
8400 
8401   return false;
8402 }
8403 
8404 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8405                               const PPCSubtarget &Subtarget,
8406                               SDValue Chain = SDValue()) {
8407   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8408                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8409   SDLoc dl(Op);
8410 
8411   // TODO: Any other flags to propagate?
8412   SDNodeFlags Flags;
8413   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8414 
8415   // If we have FCFIDS, then use it when converting to single-precision.
8416   // Otherwise, convert to double-precision and then round.
8417   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8418   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8419                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8420   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8421   if (Op->isStrictFPOpcode()) {
8422     if (!Chain)
8423       Chain = Op.getOperand(0);
8424     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8425                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8426   } else
8427     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8428 }
8429 
8430 /// Custom lowers integer to floating point conversions to use
8431 /// the direct move instructions available in ISA 2.07 to avoid the
8432 /// need for load/store combinations.
8433 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8434                                                     SelectionDAG &DAG,
8435                                                     const SDLoc &dl) const {
8436   assert((Op.getValueType() == MVT::f32 ||
8437           Op.getValueType() == MVT::f64) &&
8438          "Invalid floating point type as target of conversion");
8439   assert(Subtarget.hasFPCVT() &&
8440          "Int to FP conversions with direct moves require FPCVT");
8441   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8442   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8443   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8444                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8445   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8446   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8447   return convertIntToFP(Op, Mov, DAG, Subtarget);
8448 }
8449 
8450 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8451 
8452   EVT VecVT = Vec.getValueType();
8453   assert(VecVT.isVector() && "Expected a vector type.");
8454   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8455 
8456   EVT EltVT = VecVT.getVectorElementType();
8457   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8458   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8459 
8460   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8461   SmallVector<SDValue, 16> Ops(NumConcat);
8462   Ops[0] = Vec;
8463   SDValue UndefVec = DAG.getUNDEF(VecVT);
8464   for (unsigned i = 1; i < NumConcat; ++i)
8465     Ops[i] = UndefVec;
8466 
8467   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8468 }
8469 
8470 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8471                                                 const SDLoc &dl) const {
8472   bool IsStrict = Op->isStrictFPOpcode();
8473   unsigned Opc = Op.getOpcode();
8474   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8475   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8476           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8477          "Unexpected conversion type");
8478   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8479          "Supports conversions to v2f64/v4f32 only.");
8480 
8481   // TODO: Any other flags to propagate?
8482   SDNodeFlags Flags;
8483   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8484 
8485   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8486   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8487 
8488   SDValue Wide = widenVec(DAG, Src, dl);
8489   EVT WideVT = Wide.getValueType();
8490   unsigned WideNumElts = WideVT.getVectorNumElements();
8491   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8492 
8493   SmallVector<int, 16> ShuffV;
8494   for (unsigned i = 0; i < WideNumElts; ++i)
8495     ShuffV.push_back(i + WideNumElts);
8496 
8497   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8498   int SaveElts = FourEltRes ? 4 : 2;
8499   if (Subtarget.isLittleEndian())
8500     for (int i = 0; i < SaveElts; i++)
8501       ShuffV[i * Stride] = i;
8502   else
8503     for (int i = 1; i <= SaveElts; i++)
8504       ShuffV[i * Stride - 1] = i - 1;
8505 
8506   SDValue ShuffleSrc2 =
8507       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8508   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8509 
8510   SDValue Extend;
8511   if (SignedConv) {
8512     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8513     EVT ExtVT = Src.getValueType();
8514     if (Subtarget.hasP9Altivec())
8515       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8516                                IntermediateVT.getVectorNumElements());
8517 
8518     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8519                          DAG.getValueType(ExtVT));
8520   } else
8521     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8522 
8523   if (IsStrict)
8524     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8525                        {Op.getOperand(0), Extend}, Flags);
8526 
8527   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8528 }
8529 
8530 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8531                                           SelectionDAG &DAG) const {
8532   SDLoc dl(Op);
8533   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8534                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8535   bool IsStrict = Op->isStrictFPOpcode();
8536   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8537   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8538 
8539   // TODO: Any other flags to propagate?
8540   SDNodeFlags Flags;
8541   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8542 
8543   EVT InVT = Src.getValueType();
8544   EVT OutVT = Op.getValueType();
8545   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8546       isOperationCustom(Op.getOpcode(), InVT))
8547     return LowerINT_TO_FPVector(Op, DAG, dl);
8548 
8549   // Conversions to f128 are legal.
8550   if (Op.getValueType() == MVT::f128)
8551     return Op;
8552 
8553   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8554   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8555     return SDValue();
8556 
8557   if (Src.getValueType() == MVT::i1)
8558     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8559                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8560                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8561 
8562   // If we have direct moves, we can do all the conversion, skip the store/load
8563   // however, without FPCVT we can't do most conversions.
8564   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8565       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8566     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8567 
8568   assert((IsSigned || Subtarget.hasFPCVT()) &&
8569          "UINT_TO_FP is supported only with FPCVT");
8570 
8571   if (Src.getValueType() == MVT::i64) {
8572     SDValue SINT = Src;
8573     // When converting to single-precision, we actually need to convert
8574     // to double-precision first and then round to single-precision.
8575     // To avoid double-rounding effects during that operation, we have
8576     // to prepare the input operand.  Bits that might be truncated when
8577     // converting to double-precision are replaced by a bit that won't
8578     // be lost at this stage, but is below the single-precision rounding
8579     // position.
8580     //
8581     // However, if -enable-unsafe-fp-math is in effect, accept double
8582     // rounding to avoid the extra overhead.
8583     if (Op.getValueType() == MVT::f32 &&
8584         !Subtarget.hasFPCVT() &&
8585         !DAG.getTarget().Options.UnsafeFPMath) {
8586 
8587       // Twiddle input to make sure the low 11 bits are zero.  (If this
8588       // is the case, we are guaranteed the value will fit into the 53 bit
8589       // mantissa of an IEEE double-precision value without rounding.)
8590       // If any of those low 11 bits were not zero originally, make sure
8591       // bit 12 (value 2048) is set instead, so that the final rounding
8592       // to single-precision gets the correct result.
8593       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8594                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8595       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8596                           Round, DAG.getConstant(2047, dl, MVT::i64));
8597       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8598       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8599                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8600 
8601       // However, we cannot use that value unconditionally: if the magnitude
8602       // of the input value is small, the bit-twiddling we did above might
8603       // end up visibly changing the output.  Fortunately, in that case, we
8604       // don't need to twiddle bits since the original input will convert
8605       // exactly to double-precision floating-point already.  Therefore,
8606       // construct a conditional to use the original value if the top 11
8607       // bits are all sign-bit copies, and use the rounded value computed
8608       // above otherwise.
8609       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8610                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8611       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8612                          Cond, DAG.getConstant(1, dl, MVT::i64));
8613       Cond = DAG.getSetCC(
8614           dl,
8615           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8616           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8617 
8618       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8619     }
8620 
8621     ReuseLoadInfo RLI;
8622     SDValue Bits;
8623 
8624     MachineFunction &MF = DAG.getMachineFunction();
8625     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8626       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8627                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8628       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8629     } else if (Subtarget.hasLFIWAX() &&
8630                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8631       MachineMemOperand *MMO =
8632         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8633                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8634       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8635       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8636                                      DAG.getVTList(MVT::f64, MVT::Other),
8637                                      Ops, MVT::i32, MMO);
8638       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8639     } else if (Subtarget.hasFPCVT() &&
8640                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8641       MachineMemOperand *MMO =
8642         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8643                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8644       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8645       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8646                                      DAG.getVTList(MVT::f64, MVT::Other),
8647                                      Ops, MVT::i32, MMO);
8648       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8649     } else if (((Subtarget.hasLFIWAX() &&
8650                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8651                 (Subtarget.hasFPCVT() &&
8652                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8653                SINT.getOperand(0).getValueType() == MVT::i32) {
8654       MachineFrameInfo &MFI = MF.getFrameInfo();
8655       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8656 
8657       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8658       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8659 
8660       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8661                                    MachinePointerInfo::getFixedStack(
8662                                        DAG.getMachineFunction(), FrameIdx));
8663       Chain = Store;
8664 
8665       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8666              "Expected an i32 store");
8667 
8668       RLI.Ptr = FIdx;
8669       RLI.Chain = Chain;
8670       RLI.MPI =
8671           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8672       RLI.Alignment = Align(4);
8673 
8674       MachineMemOperand *MMO =
8675         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8676                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8677       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8678       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8679                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8680                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8681                                      Ops, MVT::i32, MMO);
8682       Chain = Bits.getValue(1);
8683     } else
8684       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8685 
8686     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8687     if (IsStrict)
8688       Chain = FP.getValue(1);
8689 
8690     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8691       if (IsStrict)
8692         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8693                          DAG.getVTList(MVT::f32, MVT::Other),
8694                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8695       else
8696         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8697                          DAG.getIntPtrConstant(0, dl));
8698     }
8699     return FP;
8700   }
8701 
8702   assert(Src.getValueType() == MVT::i32 &&
8703          "Unhandled INT_TO_FP type in custom expander!");
8704   // Since we only generate this in 64-bit mode, we can take advantage of
8705   // 64-bit registers.  In particular, sign extend the input value into the
8706   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8707   // then lfd it and fcfid it.
8708   MachineFunction &MF = DAG.getMachineFunction();
8709   MachineFrameInfo &MFI = MF.getFrameInfo();
8710   EVT PtrVT = getPointerTy(MF.getDataLayout());
8711 
8712   SDValue Ld;
8713   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8714     ReuseLoadInfo RLI;
8715     bool ReusingLoad;
8716     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8717       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8718       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8719 
8720       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8721                                    MachinePointerInfo::getFixedStack(
8722                                        DAG.getMachineFunction(), FrameIdx));
8723       Chain = Store;
8724 
8725       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8726              "Expected an i32 store");
8727 
8728       RLI.Ptr = FIdx;
8729       RLI.Chain = Chain;
8730       RLI.MPI =
8731           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8732       RLI.Alignment = Align(4);
8733     }
8734 
8735     MachineMemOperand *MMO =
8736       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8737                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8738     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8739     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8740                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8741                                  MVT::i32, MMO);
8742     Chain = Ld.getValue(1);
8743     if (ReusingLoad)
8744       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8745   } else {
8746     assert(Subtarget.isPPC64() &&
8747            "i32->FP without LFIWAX supported only on PPC64");
8748 
8749     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8750     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8751 
8752     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8753 
8754     // STD the extended value into the stack slot.
8755     SDValue Store = DAG.getStore(
8756         Chain, dl, Ext64, FIdx,
8757         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8758     Chain = Store;
8759 
8760     // Load the value as a double.
8761     Ld = DAG.getLoad(
8762         MVT::f64, dl, Chain, FIdx,
8763         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8764     Chain = Ld.getValue(1);
8765   }
8766 
8767   // FCFID it and return it.
8768   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8769   if (IsStrict)
8770     Chain = FP.getValue(1);
8771   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8772     if (IsStrict)
8773       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8774                        DAG.getVTList(MVT::f32, MVT::Other),
8775                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8776     else
8777       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8778                        DAG.getIntPtrConstant(0, dl));
8779   }
8780   return FP;
8781 }
8782 
8783 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8784                                             SelectionDAG &DAG) const {
8785   SDLoc dl(Op);
8786   /*
8787    The rounding mode is in bits 30:31 of FPSR, and has the following
8788    settings:
8789      00 Round to nearest
8790      01 Round to 0
8791      10 Round to +inf
8792      11 Round to -inf
8793 
8794   FLT_ROUNDS, on the other hand, expects the following:
8795     -1 Undefined
8796      0 Round to 0
8797      1 Round to nearest
8798      2 Round to +inf
8799      3 Round to -inf
8800 
8801   To perform the conversion, we do:
8802     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8803   */
8804 
8805   MachineFunction &MF = DAG.getMachineFunction();
8806   EVT VT = Op.getValueType();
8807   EVT PtrVT = getPointerTy(MF.getDataLayout());
8808 
8809   // Save FP Control Word to register
8810   SDValue Chain = Op.getOperand(0);
8811   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8812   Chain = MFFS.getValue(1);
8813 
8814   // Save FP register to stack slot
8815   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8816   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8817   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8818 
8819   // Load FP Control Word from low 32 bits of stack slot.
8820   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8821   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8822   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8823   Chain = CWD.getValue(1);
8824 
8825   // Transform as necessary
8826   SDValue CWD1 =
8827     DAG.getNode(ISD::AND, dl, MVT::i32,
8828                 CWD, DAG.getConstant(3, dl, MVT::i32));
8829   SDValue CWD2 =
8830     DAG.getNode(ISD::SRL, dl, MVT::i32,
8831                 DAG.getNode(ISD::AND, dl, MVT::i32,
8832                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8833                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8834                             DAG.getConstant(3, dl, MVT::i32)),
8835                 DAG.getConstant(1, dl, MVT::i32));
8836 
8837   SDValue RetVal =
8838     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8839 
8840   RetVal =
8841       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8842                   dl, VT, RetVal);
8843 
8844   return DAG.getMergeValues({RetVal, Chain}, dl);
8845 }
8846 
8847 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8848   EVT VT = Op.getValueType();
8849   unsigned BitWidth = VT.getSizeInBits();
8850   SDLoc dl(Op);
8851   assert(Op.getNumOperands() == 3 &&
8852          VT == Op.getOperand(1).getValueType() &&
8853          "Unexpected SHL!");
8854 
8855   // Expand into a bunch of logical ops.  Note that these ops
8856   // depend on the PPC behavior for oversized shift amounts.
8857   SDValue Lo = Op.getOperand(0);
8858   SDValue Hi = Op.getOperand(1);
8859   SDValue Amt = Op.getOperand(2);
8860   EVT AmtVT = Amt.getValueType();
8861 
8862   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8863                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8864   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8865   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8866   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8867   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8868                              DAG.getConstant(-BitWidth, dl, AmtVT));
8869   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8870   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8871   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8872   SDValue OutOps[] = { OutLo, OutHi };
8873   return DAG.getMergeValues(OutOps, dl);
8874 }
8875 
8876 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8877   EVT VT = Op.getValueType();
8878   SDLoc dl(Op);
8879   unsigned BitWidth = VT.getSizeInBits();
8880   assert(Op.getNumOperands() == 3 &&
8881          VT == Op.getOperand(1).getValueType() &&
8882          "Unexpected SRL!");
8883 
8884   // Expand into a bunch of logical ops.  Note that these ops
8885   // depend on the PPC behavior for oversized shift amounts.
8886   SDValue Lo = Op.getOperand(0);
8887   SDValue Hi = Op.getOperand(1);
8888   SDValue Amt = Op.getOperand(2);
8889   EVT AmtVT = Amt.getValueType();
8890 
8891   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8892                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8893   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8894   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8895   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8896   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8897                              DAG.getConstant(-BitWidth, dl, AmtVT));
8898   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8899   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8900   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8901   SDValue OutOps[] = { OutLo, OutHi };
8902   return DAG.getMergeValues(OutOps, dl);
8903 }
8904 
8905 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8906   SDLoc dl(Op);
8907   EVT VT = Op.getValueType();
8908   unsigned BitWidth = VT.getSizeInBits();
8909   assert(Op.getNumOperands() == 3 &&
8910          VT == Op.getOperand(1).getValueType() &&
8911          "Unexpected SRA!");
8912 
8913   // Expand into a bunch of logical ops, followed by a select_cc.
8914   SDValue Lo = Op.getOperand(0);
8915   SDValue Hi = Op.getOperand(1);
8916   SDValue Amt = Op.getOperand(2);
8917   EVT AmtVT = Amt.getValueType();
8918 
8919   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8920                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8921   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8922   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8923   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8924   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8925                              DAG.getConstant(-BitWidth, dl, AmtVT));
8926   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8927   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8928   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8929                                   Tmp4, Tmp6, ISD::SETLE);
8930   SDValue OutOps[] = { OutLo, OutHi };
8931   return DAG.getMergeValues(OutOps, dl);
8932 }
8933 
8934 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8935                                             SelectionDAG &DAG) const {
8936   SDLoc dl(Op);
8937   EVT VT = Op.getValueType();
8938   unsigned BitWidth = VT.getSizeInBits();
8939 
8940   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8941   SDValue X = Op.getOperand(0);
8942   SDValue Y = Op.getOperand(1);
8943   SDValue Z = Op.getOperand(2);
8944   EVT AmtVT = Z.getValueType();
8945 
8946   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8947   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8948   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8949   // on PowerPC shift by BW being well defined.
8950   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8951                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8952   SDValue SubZ =
8953       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8954   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8955   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8956   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8957 }
8958 
8959 //===----------------------------------------------------------------------===//
8960 // Vector related lowering.
8961 //
8962 
8963 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8964 /// element size of SplatSize. Cast the result to VT.
8965 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8966                                       SelectionDAG &DAG, const SDLoc &dl) {
8967   static const MVT VTys[] = { // canonical VT to use for each size.
8968     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8969   };
8970 
8971   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8972 
8973   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8974   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8975     SplatSize = 1;
8976     Val = 0xFF;
8977   }
8978 
8979   EVT CanonicalVT = VTys[SplatSize-1];
8980 
8981   // Build a canonical splat for this value.
8982   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8983 }
8984 
8985 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8986 /// specified intrinsic ID.
8987 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8988                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8989   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8990   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8991                      DAG.getConstant(IID, dl, MVT::i32), Op);
8992 }
8993 
8994 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8995 /// specified intrinsic ID.
8996 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8997                                 SelectionDAG &DAG, const SDLoc &dl,
8998                                 EVT DestVT = MVT::Other) {
8999   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9000   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9001                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9002 }
9003 
9004 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9005 /// specified intrinsic ID.
9006 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9007                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9008                                 EVT DestVT = MVT::Other) {
9009   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9010   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9011                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9012 }
9013 
9014 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9015 /// amount.  The result has the specified value type.
9016 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9017                            SelectionDAG &DAG, const SDLoc &dl) {
9018   // Force LHS/RHS to be the right type.
9019   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9020   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9021 
9022   int Ops[16];
9023   for (unsigned i = 0; i != 16; ++i)
9024     Ops[i] = i + Amt;
9025   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9026   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9027 }
9028 
9029 /// Do we have an efficient pattern in a .td file for this node?
9030 ///
9031 /// \param V - pointer to the BuildVectorSDNode being matched
9032 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9033 ///
9034 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9035 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9036 /// the opposite is true (expansion is beneficial) are:
9037 /// - The node builds a vector out of integers that are not 32 or 64-bits
9038 /// - The node builds a vector out of constants
9039 /// - The node is a "load-and-splat"
9040 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9041 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9042                                             bool HasDirectMove,
9043                                             bool HasP8Vector) {
9044   EVT VecVT = V->getValueType(0);
9045   bool RightType = VecVT == MVT::v2f64 ||
9046     (HasP8Vector && VecVT == MVT::v4f32) ||
9047     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9048   if (!RightType)
9049     return false;
9050 
9051   bool IsSplat = true;
9052   bool IsLoad = false;
9053   SDValue Op0 = V->getOperand(0);
9054 
9055   // This function is called in a block that confirms the node is not a constant
9056   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9057   // different constants.
9058   if (V->isConstant())
9059     return false;
9060   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9061     if (V->getOperand(i).isUndef())
9062       return false;
9063     // We want to expand nodes that represent load-and-splat even if the
9064     // loaded value is a floating point truncation or conversion to int.
9065     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9066         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9067          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9068         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9069          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9070         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9071          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9072       IsLoad = true;
9073     // If the operands are different or the input is not a load and has more
9074     // uses than just this BV node, then it isn't a splat.
9075     if (V->getOperand(i) != Op0 ||
9076         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9077       IsSplat = false;
9078   }
9079   return !(IsSplat && IsLoad);
9080 }
9081 
9082 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9083 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9084 
9085   SDLoc dl(Op);
9086   SDValue Op0 = Op->getOperand(0);
9087 
9088   if ((Op.getValueType() != MVT::f128) ||
9089       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9090       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9091       (Op0.getOperand(1).getValueType() != MVT::i64))
9092     return SDValue();
9093 
9094   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9095                      Op0.getOperand(1));
9096 }
9097 
9098 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9099   const SDValue *InputLoad = &Op;
9100   if (InputLoad->getOpcode() == ISD::BITCAST)
9101     InputLoad = &InputLoad->getOperand(0);
9102   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9103       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9104     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9105     InputLoad = &InputLoad->getOperand(0);
9106   }
9107   if (InputLoad->getOpcode() != ISD::LOAD)
9108     return nullptr;
9109   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9110   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9111 }
9112 
9113 // Convert the argument APFloat to a single precision APFloat if there is no
9114 // loss in information during the conversion to single precision APFloat and the
9115 // resulting number is not a denormal number. Return true if successful.
9116 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9117   APFloat APFloatToConvert = ArgAPFloat;
9118   bool LosesInfo = true;
9119   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9120                            &LosesInfo);
9121   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9122   if (Success)
9123     ArgAPFloat = APFloatToConvert;
9124   return Success;
9125 }
9126 
9127 // Bitcast the argument APInt to a double and convert it to a single precision
9128 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9129 // argument if there is no loss in information during the conversion from
9130 // double to single precision APFloat and the resulting number is not a denormal
9131 // number. Return true if successful.
9132 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9133   double DpValue = ArgAPInt.bitsToDouble();
9134   APFloat APFloatDp(DpValue);
9135   bool Success = convertToNonDenormSingle(APFloatDp);
9136   if (Success)
9137     ArgAPInt = APFloatDp.bitcastToAPInt();
9138   return Success;
9139 }
9140 
9141 // If this is a case we can't handle, return null and let the default
9142 // expansion code take care of it.  If we CAN select this case, and if it
9143 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9144 // this case more efficiently than a constant pool load, lower it to the
9145 // sequence of ops that should be used.
9146 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9147                                              SelectionDAG &DAG) const {
9148   SDLoc dl(Op);
9149   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9150   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9151 
9152   // Check if this is a splat of a constant value.
9153   APInt APSplatBits, APSplatUndef;
9154   unsigned SplatBitSize;
9155   bool HasAnyUndefs;
9156   bool BVNIsConstantSplat =
9157       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9158                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9159 
9160   // If it is a splat of a double, check if we can shrink it to a 32 bit
9161   // non-denormal float which when converted back to double gives us the same
9162   // double. This is to exploit the XXSPLTIDP instruction.
9163   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9164       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9165       convertToNonDenormSingle(APSplatBits)) {
9166     SDValue SplatNode = DAG.getNode(
9167         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9168         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9169     return DAG.getBitcast(Op.getValueType(), SplatNode);
9170   }
9171 
9172   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9173 
9174     bool IsPermutedLoad = false;
9175     const SDValue *InputLoad =
9176         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9177     // Handle load-and-splat patterns as we have instructions that will do this
9178     // in one go.
9179     if (InputLoad && DAG.isSplatValue(Op, true)) {
9180       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9181 
9182       // We have handling for 4 and 8 byte elements.
9183       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9184 
9185       // Checking for a single use of this load, we have to check for vector
9186       // width (128 bits) / ElementSize uses (since each operand of the
9187       // BUILD_VECTOR is a separate use of the value.
9188       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9189           ((Subtarget.hasVSX() && ElementSize == 64) ||
9190            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9191         SDValue Ops[] = {
9192           LD->getChain(),    // Chain
9193           LD->getBasePtr(),  // Ptr
9194           DAG.getValueType(Op.getValueType()) // VT
9195         };
9196         return
9197           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9198                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9199                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9200       }
9201     }
9202 
9203     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9204     // lowered to VSX instructions under certain conditions.
9205     // Without VSX, there is no pattern more efficient than expanding the node.
9206     if (Subtarget.hasVSX() &&
9207         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9208                                         Subtarget.hasP8Vector()))
9209       return Op;
9210     return SDValue();
9211   }
9212 
9213   uint64_t SplatBits = APSplatBits.getZExtValue();
9214   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9215   unsigned SplatSize = SplatBitSize / 8;
9216 
9217   // First, handle single instruction cases.
9218 
9219   // All zeros?
9220   if (SplatBits == 0) {
9221     // Canonicalize all zero vectors to be v4i32.
9222     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9223       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9224       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9225     }
9226     return Op;
9227   }
9228 
9229   // We have XXSPLTIW for constant splats four bytes wide.
9230   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9231   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9232   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9233   // turned into a 4-byte splat of 0xABABABAB.
9234   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9235     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
9236                                   Op.getValueType(), DAG, dl);
9237 
9238   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9239     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9240                                   dl);
9241 
9242   // We have XXSPLTIB for constant splats one byte wide.
9243   if (Subtarget.hasP9Vector() && SplatSize == 1)
9244     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9245                                   dl);
9246 
9247   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9248   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9249                     (32-SplatBitSize));
9250   if (SextVal >= -16 && SextVal <= 15)
9251     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9252                                   dl);
9253 
9254   // Two instruction sequences.
9255 
9256   // If this value is in the range [-32,30] and is even, use:
9257   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9258   // If this value is in the range [17,31] and is odd, use:
9259   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9260   // If this value is in the range [-31,-17] and is odd, use:
9261   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9262   // Note the last two are three-instruction sequences.
9263   if (SextVal >= -32 && SextVal <= 31) {
9264     // To avoid having these optimizations undone by constant folding,
9265     // we convert to a pseudo that will be expanded later into one of
9266     // the above forms.
9267     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9268     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9269               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9270     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9271     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9272     if (VT == Op.getValueType())
9273       return RetVal;
9274     else
9275       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9276   }
9277 
9278   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9279   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9280   // for fneg/fabs.
9281   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9282     // Make -1 and vspltisw -1:
9283     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9284 
9285     // Make the VSLW intrinsic, computing 0x8000_0000.
9286     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9287                                    OnesV, DAG, dl);
9288 
9289     // xor by OnesV to invert it.
9290     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9291     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9292   }
9293 
9294   // Check to see if this is a wide variety of vsplti*, binop self cases.
9295   static const signed char SplatCsts[] = {
9296     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9297     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9298   };
9299 
9300   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9301     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9302     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9303     int i = SplatCsts[idx];
9304 
9305     // Figure out what shift amount will be used by altivec if shifted by i in
9306     // this splat size.
9307     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9308 
9309     // vsplti + shl self.
9310     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9311       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9312       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9313         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9314         Intrinsic::ppc_altivec_vslw
9315       };
9316       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9317       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9318     }
9319 
9320     // vsplti + srl self.
9321     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9322       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9323       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9324         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9325         Intrinsic::ppc_altivec_vsrw
9326       };
9327       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9328       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9329     }
9330 
9331     // vsplti + sra self.
9332     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9333       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9334       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9335         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9336         Intrinsic::ppc_altivec_vsraw
9337       };
9338       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9339       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9340     }
9341 
9342     // vsplti + rol self.
9343     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9344                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9345       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9346       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9347         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9348         Intrinsic::ppc_altivec_vrlw
9349       };
9350       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9351       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9352     }
9353 
9354     // t = vsplti c, result = vsldoi t, t, 1
9355     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9356       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9357       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9358       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9359     }
9360     // t = vsplti c, result = vsldoi t, t, 2
9361     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9362       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9363       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9364       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9365     }
9366     // t = vsplti c, result = vsldoi t, t, 3
9367     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9368       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9369       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9370       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9371     }
9372   }
9373 
9374   return SDValue();
9375 }
9376 
9377 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9378 /// the specified operations to build the shuffle.
9379 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9380                                       SDValue RHS, SelectionDAG &DAG,
9381                                       const SDLoc &dl) {
9382   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9383   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9384   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9385 
9386   enum {
9387     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9388     OP_VMRGHW,
9389     OP_VMRGLW,
9390     OP_VSPLTISW0,
9391     OP_VSPLTISW1,
9392     OP_VSPLTISW2,
9393     OP_VSPLTISW3,
9394     OP_VSLDOI4,
9395     OP_VSLDOI8,
9396     OP_VSLDOI12
9397   };
9398 
9399   if (OpNum == OP_COPY) {
9400     if (LHSID == (1*9+2)*9+3) return LHS;
9401     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9402     return RHS;
9403   }
9404 
9405   SDValue OpLHS, OpRHS;
9406   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9407   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9408 
9409   int ShufIdxs[16];
9410   switch (OpNum) {
9411   default: llvm_unreachable("Unknown i32 permute!");
9412   case OP_VMRGHW:
9413     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9414     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9415     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9416     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9417     break;
9418   case OP_VMRGLW:
9419     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9420     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9421     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9422     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9423     break;
9424   case OP_VSPLTISW0:
9425     for (unsigned i = 0; i != 16; ++i)
9426       ShufIdxs[i] = (i&3)+0;
9427     break;
9428   case OP_VSPLTISW1:
9429     for (unsigned i = 0; i != 16; ++i)
9430       ShufIdxs[i] = (i&3)+4;
9431     break;
9432   case OP_VSPLTISW2:
9433     for (unsigned i = 0; i != 16; ++i)
9434       ShufIdxs[i] = (i&3)+8;
9435     break;
9436   case OP_VSPLTISW3:
9437     for (unsigned i = 0; i != 16; ++i)
9438       ShufIdxs[i] = (i&3)+12;
9439     break;
9440   case OP_VSLDOI4:
9441     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9442   case OP_VSLDOI8:
9443     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9444   case OP_VSLDOI12:
9445     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9446   }
9447   EVT VT = OpLHS.getValueType();
9448   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9449   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9450   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9451   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9452 }
9453 
9454 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9455 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9456 /// SDValue.
9457 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9458                                            SelectionDAG &DAG) const {
9459   const unsigned BytesInVector = 16;
9460   bool IsLE = Subtarget.isLittleEndian();
9461   SDLoc dl(N);
9462   SDValue V1 = N->getOperand(0);
9463   SDValue V2 = N->getOperand(1);
9464   unsigned ShiftElts = 0, InsertAtByte = 0;
9465   bool Swap = false;
9466 
9467   // Shifts required to get the byte we want at element 7.
9468   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9469                                    0, 15, 14, 13, 12, 11, 10, 9};
9470   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9471                                 1, 2,  3,  4,  5,  6,  7,  8};
9472 
9473   ArrayRef<int> Mask = N->getMask();
9474   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9475 
9476   // For each mask element, find out if we're just inserting something
9477   // from V2 into V1 or vice versa.
9478   // Possible permutations inserting an element from V2 into V1:
9479   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9480   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9481   //   ...
9482   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9483   // Inserting from V1 into V2 will be similar, except mask range will be
9484   // [16,31].
9485 
9486   bool FoundCandidate = false;
9487   // If both vector operands for the shuffle are the same vector, the mask
9488   // will contain only elements from the first one and the second one will be
9489   // undef.
9490   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9491   // Go through the mask of half-words to find an element that's being moved
9492   // from one vector to the other.
9493   for (unsigned i = 0; i < BytesInVector; ++i) {
9494     unsigned CurrentElement = Mask[i];
9495     // If 2nd operand is undefined, we should only look for element 7 in the
9496     // Mask.
9497     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9498       continue;
9499 
9500     bool OtherElementsInOrder = true;
9501     // Examine the other elements in the Mask to see if they're in original
9502     // order.
9503     for (unsigned j = 0; j < BytesInVector; ++j) {
9504       if (j == i)
9505         continue;
9506       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9507       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9508       // in which we always assume we're always picking from the 1st operand.
9509       int MaskOffset =
9510           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9511       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9512         OtherElementsInOrder = false;
9513         break;
9514       }
9515     }
9516     // If other elements are in original order, we record the number of shifts
9517     // we need to get the element we want into element 7. Also record which byte
9518     // in the vector we should insert into.
9519     if (OtherElementsInOrder) {
9520       // If 2nd operand is undefined, we assume no shifts and no swapping.
9521       if (V2.isUndef()) {
9522         ShiftElts = 0;
9523         Swap = false;
9524       } else {
9525         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9526         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9527                          : BigEndianShifts[CurrentElement & 0xF];
9528         Swap = CurrentElement < BytesInVector;
9529       }
9530       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9531       FoundCandidate = true;
9532       break;
9533     }
9534   }
9535 
9536   if (!FoundCandidate)
9537     return SDValue();
9538 
9539   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9540   // optionally with VECSHL if shift is required.
9541   if (Swap)
9542     std::swap(V1, V2);
9543   if (V2.isUndef())
9544     V2 = V1;
9545   if (ShiftElts) {
9546     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9547                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9548     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9549                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9550   }
9551   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9552                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9553 }
9554 
9555 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9556 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9557 /// SDValue.
9558 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9559                                            SelectionDAG &DAG) const {
9560   const unsigned NumHalfWords = 8;
9561   const unsigned BytesInVector = NumHalfWords * 2;
9562   // Check that the shuffle is on half-words.
9563   if (!isNByteElemShuffleMask(N, 2, 1))
9564     return SDValue();
9565 
9566   bool IsLE = Subtarget.isLittleEndian();
9567   SDLoc dl(N);
9568   SDValue V1 = N->getOperand(0);
9569   SDValue V2 = N->getOperand(1);
9570   unsigned ShiftElts = 0, InsertAtByte = 0;
9571   bool Swap = false;
9572 
9573   // Shifts required to get the half-word we want at element 3.
9574   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9575   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9576 
9577   uint32_t Mask = 0;
9578   uint32_t OriginalOrderLow = 0x1234567;
9579   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9580   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9581   // 32-bit space, only need 4-bit nibbles per element.
9582   for (unsigned i = 0; i < NumHalfWords; ++i) {
9583     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9584     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9585   }
9586 
9587   // For each mask element, find out if we're just inserting something
9588   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9589   // from V2 into V1:
9590   //   X, 1, 2, 3, 4, 5, 6, 7
9591   //   0, X, 2, 3, 4, 5, 6, 7
9592   //   0, 1, X, 3, 4, 5, 6, 7
9593   //   0, 1, 2, X, 4, 5, 6, 7
9594   //   0, 1, 2, 3, X, 5, 6, 7
9595   //   0, 1, 2, 3, 4, X, 6, 7
9596   //   0, 1, 2, 3, 4, 5, X, 7
9597   //   0, 1, 2, 3, 4, 5, 6, X
9598   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9599 
9600   bool FoundCandidate = false;
9601   // Go through the mask of half-words to find an element that's being moved
9602   // from one vector to the other.
9603   for (unsigned i = 0; i < NumHalfWords; ++i) {
9604     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9605     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9606     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9607     uint32_t TargetOrder = 0x0;
9608 
9609     // If both vector operands for the shuffle are the same vector, the mask
9610     // will contain only elements from the first one and the second one will be
9611     // undef.
9612     if (V2.isUndef()) {
9613       ShiftElts = 0;
9614       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9615       TargetOrder = OriginalOrderLow;
9616       Swap = false;
9617       // Skip if not the correct element or mask of other elements don't equal
9618       // to our expected order.
9619       if (MaskOneElt == VINSERTHSrcElem &&
9620           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9621         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9622         FoundCandidate = true;
9623         break;
9624       }
9625     } else { // If both operands are defined.
9626       // Target order is [8,15] if the current mask is between [0,7].
9627       TargetOrder =
9628           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9629       // Skip if mask of other elements don't equal our expected order.
9630       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9631         // We only need the last 3 bits for the number of shifts.
9632         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9633                          : BigEndianShifts[MaskOneElt & 0x7];
9634         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9635         Swap = MaskOneElt < NumHalfWords;
9636         FoundCandidate = true;
9637         break;
9638       }
9639     }
9640   }
9641 
9642   if (!FoundCandidate)
9643     return SDValue();
9644 
9645   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9646   // optionally with VECSHL if shift is required.
9647   if (Swap)
9648     std::swap(V1, V2);
9649   if (V2.isUndef())
9650     V2 = V1;
9651   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9652   if (ShiftElts) {
9653     // Double ShiftElts because we're left shifting on v16i8 type.
9654     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9655                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9656     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9657     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9658                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9659     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9660   }
9661   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9662   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9663                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9664   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9665 }
9666 
9667 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9668 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9669 /// return the default SDValue.
9670 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9671                                               SelectionDAG &DAG) const {
9672   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9673   // to v16i8. Peek through the bitcasts to get the actual operands.
9674   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9675   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9676 
9677   auto ShuffleMask = SVN->getMask();
9678   SDValue VecShuffle(SVN, 0);
9679   SDLoc DL(SVN);
9680 
9681   // Check that we have a four byte shuffle.
9682   if (!isNByteElemShuffleMask(SVN, 4, 1))
9683     return SDValue();
9684 
9685   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9686   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9687     std::swap(LHS, RHS);
9688     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9689     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9690   }
9691 
9692   // Ensure that the RHS is a vector of constants.
9693   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9694   if (!BVN)
9695     return SDValue();
9696 
9697   // Check if RHS is a splat of 4-bytes (or smaller).
9698   APInt APSplatValue, APSplatUndef;
9699   unsigned SplatBitSize;
9700   bool HasAnyUndefs;
9701   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9702                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9703       SplatBitSize > 32)
9704     return SDValue();
9705 
9706   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9707   // The instruction splats a constant C into two words of the source vector
9708   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9709   // Thus we check that the shuffle mask is the equivalent  of
9710   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9711   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9712   // within each word are consecutive, so we only need to check the first byte.
9713   SDValue Index;
9714   bool IsLE = Subtarget.isLittleEndian();
9715   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9716       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9717        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9718     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9719   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9720            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9721             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9722     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9723   else
9724     return SDValue();
9725 
9726   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9727   // for XXSPLTI32DX.
9728   unsigned SplatVal = APSplatValue.getZExtValue();
9729   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9730     SplatVal |= (SplatVal << SplatBitSize);
9731 
9732   SDValue SplatNode = DAG.getNode(
9733       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9734       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9735   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9736 }
9737 
9738 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9739 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9740 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9741 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9742 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9743   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9744   assert(Op.getValueType() == MVT::v1i128 &&
9745          "Only set v1i128 as custom, other type shouldn't reach here!");
9746   SDLoc dl(Op);
9747   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9748   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9749   unsigned SHLAmt = N1.getConstantOperandVal(0);
9750   if (SHLAmt % 8 == 0) {
9751     SmallVector<int, 16> Mask(16, 0);
9752     std::iota(Mask.begin(), Mask.end(), 0);
9753     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9754     if (SDValue Shuffle =
9755             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9756                                  DAG.getUNDEF(MVT::v16i8), Mask))
9757       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9758   }
9759   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9760   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9761                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9762   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9763                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9764   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9765   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9766 }
9767 
9768 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9769 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9770 /// return the code it can be lowered into.  Worst case, it can always be
9771 /// lowered into a vperm.
9772 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9773                                                SelectionDAG &DAG) const {
9774   SDLoc dl(Op);
9775   SDValue V1 = Op.getOperand(0);
9776   SDValue V2 = Op.getOperand(1);
9777   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9778 
9779   // Any nodes that were combined in the target-independent combiner prior
9780   // to vector legalization will not be sent to the target combine. Try to
9781   // combine it here.
9782   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9783     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9784       return NewShuffle;
9785     Op = NewShuffle;
9786     SVOp = cast<ShuffleVectorSDNode>(Op);
9787     V1 = Op.getOperand(0);
9788     V2 = Op.getOperand(1);
9789   }
9790   EVT VT = Op.getValueType();
9791   bool isLittleEndian = Subtarget.isLittleEndian();
9792 
9793   unsigned ShiftElts, InsertAtByte;
9794   bool Swap = false;
9795 
9796   // If this is a load-and-splat, we can do that with a single instruction
9797   // in some cases. However if the load has multiple uses, we don't want to
9798   // combine it because that will just produce multiple loads.
9799   bool IsPermutedLoad = false;
9800   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9801   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9802       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9803       InputLoad->hasOneUse()) {
9804     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9805     int SplatIdx =
9806       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9807 
9808     // The splat index for permuted loads will be in the left half of the vector
9809     // which is strictly wider than the loaded value by 8 bytes. So we need to
9810     // adjust the splat index to point to the correct address in memory.
9811     if (IsPermutedLoad) {
9812       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9813       SplatIdx += IsFourByte ? 2 : 1;
9814       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9815              "Splat of a value outside of the loaded memory");
9816     }
9817 
9818     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9819     // For 4-byte load-and-splat, we need Power9.
9820     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9821       uint64_t Offset = 0;
9822       if (IsFourByte)
9823         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9824       else
9825         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9826 
9827       SDValue BasePtr = LD->getBasePtr();
9828       if (Offset != 0)
9829         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9830                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9831       SDValue Ops[] = {
9832         LD->getChain(),    // Chain
9833         BasePtr,           // BasePtr
9834         DAG.getValueType(Op.getValueType()) // VT
9835       };
9836       SDVTList VTL =
9837         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9838       SDValue LdSplt =
9839         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9840                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9841       if (LdSplt.getValueType() != SVOp->getValueType(0))
9842         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9843       return LdSplt;
9844     }
9845   }
9846   if (Subtarget.hasP9Vector() &&
9847       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9848                            isLittleEndian)) {
9849     if (Swap)
9850       std::swap(V1, V2);
9851     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9852     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9853     if (ShiftElts) {
9854       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9855                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9856       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9857                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9858       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9859     }
9860     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9861                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9862     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9863   }
9864 
9865   if (Subtarget.hasPrefixInstrs()) {
9866     SDValue SplatInsertNode;
9867     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9868       return SplatInsertNode;
9869   }
9870 
9871   if (Subtarget.hasP9Altivec()) {
9872     SDValue NewISDNode;
9873     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9874       return NewISDNode;
9875 
9876     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9877       return NewISDNode;
9878   }
9879 
9880   if (Subtarget.hasVSX() &&
9881       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9882     if (Swap)
9883       std::swap(V1, V2);
9884     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9885     SDValue Conv2 =
9886         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9887 
9888     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9889                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9890     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9891   }
9892 
9893   if (Subtarget.hasVSX() &&
9894     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9895     if (Swap)
9896       std::swap(V1, V2);
9897     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9898     SDValue Conv2 =
9899         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9900 
9901     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9902                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9903     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9904   }
9905 
9906   if (Subtarget.hasP9Vector()) {
9907      if (PPC::isXXBRHShuffleMask(SVOp)) {
9908       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9909       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9910       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9911     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9912       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9913       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9914       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9915     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9916       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9917       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9918       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9919     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9920       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9921       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9922       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9923     }
9924   }
9925 
9926   if (Subtarget.hasVSX()) {
9927     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9928       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9929 
9930       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9931       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9932                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9933       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9934     }
9935 
9936     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9937     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9938       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9939       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9940       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9941     }
9942   }
9943 
9944   // Cases that are handled by instructions that take permute immediates
9945   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9946   // selected by the instruction selector.
9947   if (V2.isUndef()) {
9948     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9949         PPC::isSplatShuffleMask(SVOp, 2) ||
9950         PPC::isSplatShuffleMask(SVOp, 4) ||
9951         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9952         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9953         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9954         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9955         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9956         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9957         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9958         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9959         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9960         (Subtarget.hasP8Altivec() && (
9961          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9962          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9963          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9964       return Op;
9965     }
9966   }
9967 
9968   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9969   // and produce a fixed permutation.  If any of these match, do not lower to
9970   // VPERM.
9971   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9972   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9973       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9974       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9975       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9976       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9977       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9978       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9979       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9980       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9981       (Subtarget.hasP8Altivec() && (
9982        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9983        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9984        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9985     return Op;
9986 
9987   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9988   // perfect shuffle table to emit an optimal matching sequence.
9989   ArrayRef<int> PermMask = SVOp->getMask();
9990 
9991   unsigned PFIndexes[4];
9992   bool isFourElementShuffle = true;
9993   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9994     unsigned EltNo = 8;   // Start out undef.
9995     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9996       if (PermMask[i*4+j] < 0)
9997         continue;   // Undef, ignore it.
9998 
9999       unsigned ByteSource = PermMask[i*4+j];
10000       if ((ByteSource & 3) != j) {
10001         isFourElementShuffle = false;
10002         break;
10003       }
10004 
10005       if (EltNo == 8) {
10006         EltNo = ByteSource/4;
10007       } else if (EltNo != ByteSource/4) {
10008         isFourElementShuffle = false;
10009         break;
10010       }
10011     }
10012     PFIndexes[i] = EltNo;
10013   }
10014 
10015   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10016   // perfect shuffle vector to determine if it is cost effective to do this as
10017   // discrete instructions, or whether we should use a vperm.
10018   // For now, we skip this for little endian until such time as we have a
10019   // little-endian perfect shuffle table.
10020   if (isFourElementShuffle && !isLittleEndian) {
10021     // Compute the index in the perfect shuffle table.
10022     unsigned PFTableIndex =
10023       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
10024 
10025     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10026     unsigned Cost  = (PFEntry >> 30);
10027 
10028     // Determining when to avoid vperm is tricky.  Many things affect the cost
10029     // of vperm, particularly how many times the perm mask needs to be computed.
10030     // For example, if the perm mask can be hoisted out of a loop or is already
10031     // used (perhaps because there are multiple permutes with the same shuffle
10032     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
10033     // the loop requires an extra register.
10034     //
10035     // As a compromise, we only emit discrete instructions if the shuffle can be
10036     // generated in 3 or fewer operations.  When we have loop information
10037     // available, if this block is within a loop, we should avoid using vperm
10038     // for 3-operation perms and use a constant pool load instead.
10039     if (Cost < 3)
10040       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10041   }
10042 
10043   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10044   // vector that will get spilled to the constant pool.
10045   if (V2.isUndef()) V2 = V1;
10046 
10047   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10048   // that it is in input element units, not in bytes.  Convert now.
10049 
10050   // For little endian, the order of the input vectors is reversed, and
10051   // the permutation mask is complemented with respect to 31.  This is
10052   // necessary to produce proper semantics with the big-endian-biased vperm
10053   // instruction.
10054   EVT EltVT = V1.getValueType().getVectorElementType();
10055   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10056 
10057   SmallVector<SDValue, 16> ResultMask;
10058   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10059     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10060 
10061     for (unsigned j = 0; j != BytesPerElement; ++j)
10062       if (isLittleEndian)
10063         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10064                                              dl, MVT::i32));
10065       else
10066         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10067                                              MVT::i32));
10068   }
10069 
10070   ShufflesHandledWithVPERM++;
10071   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10072   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10073   LLVM_DEBUG(SVOp->dump());
10074   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10075   LLVM_DEBUG(VPermMask.dump());
10076 
10077   if (isLittleEndian)
10078     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10079                        V2, V1, VPermMask);
10080   else
10081     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10082                        V1, V2, VPermMask);
10083 }
10084 
10085 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10086 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10087 /// information about the intrinsic.
10088 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10089                                  bool &isDot, const PPCSubtarget &Subtarget) {
10090   unsigned IntrinsicID =
10091       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10092   CompareOpc = -1;
10093   isDot = false;
10094   switch (IntrinsicID) {
10095   default:
10096     return false;
10097   // Comparison predicates.
10098   case Intrinsic::ppc_altivec_vcmpbfp_p:
10099     CompareOpc = 966;
10100     isDot = true;
10101     break;
10102   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10103     CompareOpc = 198;
10104     isDot = true;
10105     break;
10106   case Intrinsic::ppc_altivec_vcmpequb_p:
10107     CompareOpc = 6;
10108     isDot = true;
10109     break;
10110   case Intrinsic::ppc_altivec_vcmpequh_p:
10111     CompareOpc = 70;
10112     isDot = true;
10113     break;
10114   case Intrinsic::ppc_altivec_vcmpequw_p:
10115     CompareOpc = 134;
10116     isDot = true;
10117     break;
10118   case Intrinsic::ppc_altivec_vcmpequd_p:
10119     if (Subtarget.hasP8Altivec()) {
10120       CompareOpc = 199;
10121       isDot = true;
10122     } else
10123       return false;
10124     break;
10125   case Intrinsic::ppc_altivec_vcmpneb_p:
10126   case Intrinsic::ppc_altivec_vcmpneh_p:
10127   case Intrinsic::ppc_altivec_vcmpnew_p:
10128   case Intrinsic::ppc_altivec_vcmpnezb_p:
10129   case Intrinsic::ppc_altivec_vcmpnezh_p:
10130   case Intrinsic::ppc_altivec_vcmpnezw_p:
10131     if (Subtarget.hasP9Altivec()) {
10132       switch (IntrinsicID) {
10133       default:
10134         llvm_unreachable("Unknown comparison intrinsic.");
10135       case Intrinsic::ppc_altivec_vcmpneb_p:
10136         CompareOpc = 7;
10137         break;
10138       case Intrinsic::ppc_altivec_vcmpneh_p:
10139         CompareOpc = 71;
10140         break;
10141       case Intrinsic::ppc_altivec_vcmpnew_p:
10142         CompareOpc = 135;
10143         break;
10144       case Intrinsic::ppc_altivec_vcmpnezb_p:
10145         CompareOpc = 263;
10146         break;
10147       case Intrinsic::ppc_altivec_vcmpnezh_p:
10148         CompareOpc = 327;
10149         break;
10150       case Intrinsic::ppc_altivec_vcmpnezw_p:
10151         CompareOpc = 391;
10152         break;
10153       }
10154       isDot = true;
10155     } else
10156       return false;
10157     break;
10158   case Intrinsic::ppc_altivec_vcmpgefp_p:
10159     CompareOpc = 454;
10160     isDot = true;
10161     break;
10162   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10163     CompareOpc = 710;
10164     isDot = true;
10165     break;
10166   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10167     CompareOpc = 774;
10168     isDot = true;
10169     break;
10170   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10171     CompareOpc = 838;
10172     isDot = true;
10173     break;
10174   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10175     CompareOpc = 902;
10176     isDot = true;
10177     break;
10178   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10179     if (Subtarget.hasP8Altivec()) {
10180       CompareOpc = 967;
10181       isDot = true;
10182     } else
10183       return false;
10184     break;
10185   case Intrinsic::ppc_altivec_vcmpgtub_p:
10186     CompareOpc = 518;
10187     isDot = true;
10188     break;
10189   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10190     CompareOpc = 582;
10191     isDot = true;
10192     break;
10193   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10194     CompareOpc = 646;
10195     isDot = true;
10196     break;
10197   case Intrinsic::ppc_altivec_vcmpgtud_p:
10198     if (Subtarget.hasP8Altivec()) {
10199       CompareOpc = 711;
10200       isDot = true;
10201     } else
10202       return false;
10203     break;
10204 
10205   // VSX predicate comparisons use the same infrastructure
10206   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10207   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10208   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10209   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10210   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10211   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10212     if (Subtarget.hasVSX()) {
10213       switch (IntrinsicID) {
10214       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10215         CompareOpc = 99;
10216         break;
10217       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10218         CompareOpc = 115;
10219         break;
10220       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10221         CompareOpc = 107;
10222         break;
10223       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10224         CompareOpc = 67;
10225         break;
10226       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10227         CompareOpc = 83;
10228         break;
10229       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10230         CompareOpc = 75;
10231         break;
10232       }
10233       isDot = true;
10234     } else
10235       return false;
10236     break;
10237 
10238   // Normal Comparisons.
10239   case Intrinsic::ppc_altivec_vcmpbfp:
10240     CompareOpc = 966;
10241     break;
10242   case Intrinsic::ppc_altivec_vcmpeqfp:
10243     CompareOpc = 198;
10244     break;
10245   case Intrinsic::ppc_altivec_vcmpequb:
10246     CompareOpc = 6;
10247     break;
10248   case Intrinsic::ppc_altivec_vcmpequh:
10249     CompareOpc = 70;
10250     break;
10251   case Intrinsic::ppc_altivec_vcmpequw:
10252     CompareOpc = 134;
10253     break;
10254   case Intrinsic::ppc_altivec_vcmpequd:
10255     if (Subtarget.hasP8Altivec())
10256       CompareOpc = 199;
10257     else
10258       return false;
10259     break;
10260   case Intrinsic::ppc_altivec_vcmpneb:
10261   case Intrinsic::ppc_altivec_vcmpneh:
10262   case Intrinsic::ppc_altivec_vcmpnew:
10263   case Intrinsic::ppc_altivec_vcmpnezb:
10264   case Intrinsic::ppc_altivec_vcmpnezh:
10265   case Intrinsic::ppc_altivec_vcmpnezw:
10266     if (Subtarget.hasP9Altivec())
10267       switch (IntrinsicID) {
10268       default:
10269         llvm_unreachable("Unknown comparison intrinsic.");
10270       case Intrinsic::ppc_altivec_vcmpneb:
10271         CompareOpc = 7;
10272         break;
10273       case Intrinsic::ppc_altivec_vcmpneh:
10274         CompareOpc = 71;
10275         break;
10276       case Intrinsic::ppc_altivec_vcmpnew:
10277         CompareOpc = 135;
10278         break;
10279       case Intrinsic::ppc_altivec_vcmpnezb:
10280         CompareOpc = 263;
10281         break;
10282       case Intrinsic::ppc_altivec_vcmpnezh:
10283         CompareOpc = 327;
10284         break;
10285       case Intrinsic::ppc_altivec_vcmpnezw:
10286         CompareOpc = 391;
10287         break;
10288       }
10289     else
10290       return false;
10291     break;
10292   case Intrinsic::ppc_altivec_vcmpgefp:
10293     CompareOpc = 454;
10294     break;
10295   case Intrinsic::ppc_altivec_vcmpgtfp:
10296     CompareOpc = 710;
10297     break;
10298   case Intrinsic::ppc_altivec_vcmpgtsb:
10299     CompareOpc = 774;
10300     break;
10301   case Intrinsic::ppc_altivec_vcmpgtsh:
10302     CompareOpc = 838;
10303     break;
10304   case Intrinsic::ppc_altivec_vcmpgtsw:
10305     CompareOpc = 902;
10306     break;
10307   case Intrinsic::ppc_altivec_vcmpgtsd:
10308     if (Subtarget.hasP8Altivec())
10309       CompareOpc = 967;
10310     else
10311       return false;
10312     break;
10313   case Intrinsic::ppc_altivec_vcmpgtub:
10314     CompareOpc = 518;
10315     break;
10316   case Intrinsic::ppc_altivec_vcmpgtuh:
10317     CompareOpc = 582;
10318     break;
10319   case Intrinsic::ppc_altivec_vcmpgtuw:
10320     CompareOpc = 646;
10321     break;
10322   case Intrinsic::ppc_altivec_vcmpgtud:
10323     if (Subtarget.hasP8Altivec())
10324       CompareOpc = 711;
10325     else
10326       return false;
10327     break;
10328   }
10329   return true;
10330 }
10331 
10332 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10333 /// lower, do it, otherwise return null.
10334 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10335                                                    SelectionDAG &DAG) const {
10336   unsigned IntrinsicID =
10337     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10338 
10339   SDLoc dl(Op);
10340 
10341   if (IntrinsicID == Intrinsic::thread_pointer) {
10342     // Reads the thread pointer register, used for __builtin_thread_pointer.
10343     if (Subtarget.isPPC64())
10344       return DAG.getRegister(PPC::X13, MVT::i64);
10345     return DAG.getRegister(PPC::R2, MVT::i32);
10346   }
10347 
10348   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10349   // opcode number of the comparison.
10350   int CompareOpc;
10351   bool isDot;
10352   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10353     return SDValue();    // Don't custom lower most intrinsics.
10354 
10355   // If this is a non-dot comparison, make the VCMP node and we are done.
10356   if (!isDot) {
10357     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10358                               Op.getOperand(1), Op.getOperand(2),
10359                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10360     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10361   }
10362 
10363   // Create the PPCISD altivec 'dot' comparison node.
10364   SDValue Ops[] = {
10365     Op.getOperand(2),  // LHS
10366     Op.getOperand(3),  // RHS
10367     DAG.getConstant(CompareOpc, dl, MVT::i32)
10368   };
10369   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10370   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10371 
10372   // Now that we have the comparison, emit a copy from the CR to a GPR.
10373   // This is flagged to the above dot comparison.
10374   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10375                                 DAG.getRegister(PPC::CR6, MVT::i32),
10376                                 CompNode.getValue(1));
10377 
10378   // Unpack the result based on how the target uses it.
10379   unsigned BitNo;   // Bit # of CR6.
10380   bool InvertBit;   // Invert result?
10381   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10382   default:  // Can't happen, don't crash on invalid number though.
10383   case 0:   // Return the value of the EQ bit of CR6.
10384     BitNo = 0; InvertBit = false;
10385     break;
10386   case 1:   // Return the inverted value of the EQ bit of CR6.
10387     BitNo = 0; InvertBit = true;
10388     break;
10389   case 2:   // Return the value of the LT bit of CR6.
10390     BitNo = 2; InvertBit = false;
10391     break;
10392   case 3:   // Return the inverted value of the LT bit of CR6.
10393     BitNo = 2; InvertBit = true;
10394     break;
10395   }
10396 
10397   // Shift the bit into the low position.
10398   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10399                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10400   // Isolate the bit.
10401   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10402                       DAG.getConstant(1, dl, MVT::i32));
10403 
10404   // If we are supposed to, toggle the bit.
10405   if (InvertBit)
10406     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10407                         DAG.getConstant(1, dl, MVT::i32));
10408   return Flags;
10409 }
10410 
10411 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10412                                                SelectionDAG &DAG) const {
10413   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10414   // the beginning of the argument list.
10415   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10416   SDLoc DL(Op);
10417   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10418   case Intrinsic::ppc_cfence: {
10419     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10420     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10421     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10422                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10423                                                   Op.getOperand(ArgStart + 1)),
10424                                       Op.getOperand(0)),
10425                    0);
10426   }
10427   default:
10428     break;
10429   }
10430   return SDValue();
10431 }
10432 
10433 // Lower scalar BSWAP64 to xxbrd.
10434 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10435   SDLoc dl(Op);
10436   // MTVSRDD
10437   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10438                    Op.getOperand(0));
10439   // XXBRD
10440   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10441   // MFVSRD
10442   int VectorIndex = 0;
10443   if (Subtarget.isLittleEndian())
10444     VectorIndex = 1;
10445   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10446                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10447   return Op;
10448 }
10449 
10450 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10451 // compared to a value that is atomically loaded (atomic loads zero-extend).
10452 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10453                                                 SelectionDAG &DAG) const {
10454   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10455          "Expecting an atomic compare-and-swap here.");
10456   SDLoc dl(Op);
10457   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10458   EVT MemVT = AtomicNode->getMemoryVT();
10459   if (MemVT.getSizeInBits() >= 32)
10460     return Op;
10461 
10462   SDValue CmpOp = Op.getOperand(2);
10463   // If this is already correctly zero-extended, leave it alone.
10464   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10465   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10466     return Op;
10467 
10468   // Clear the high bits of the compare operand.
10469   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10470   SDValue NewCmpOp =
10471     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10472                 DAG.getConstant(MaskVal, dl, MVT::i32));
10473 
10474   // Replace the existing compare operand with the properly zero-extended one.
10475   SmallVector<SDValue, 4> Ops;
10476   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10477     Ops.push_back(AtomicNode->getOperand(i));
10478   Ops[2] = NewCmpOp;
10479   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10480   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10481   auto NodeTy =
10482     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10483   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10484 }
10485 
10486 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10487                                                  SelectionDAG &DAG) const {
10488   SDLoc dl(Op);
10489   // Create a stack slot that is 16-byte aligned.
10490   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10491   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10492   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10493   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10494 
10495   // Store the input value into Value#0 of the stack slot.
10496   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10497                                MachinePointerInfo());
10498   // Load it out.
10499   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10500 }
10501 
10502 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10503                                                   SelectionDAG &DAG) const {
10504   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10505          "Should only be called for ISD::INSERT_VECTOR_ELT");
10506 
10507   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10508   // We have legal lowering for constant indices but not for variable ones.
10509   if (!C)
10510     return SDValue();
10511 
10512   EVT VT = Op.getValueType();
10513   SDLoc dl(Op);
10514   SDValue V1 = Op.getOperand(0);
10515   SDValue V2 = Op.getOperand(1);
10516   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10517   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10518     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10519     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10520     unsigned InsertAtElement = C->getZExtValue();
10521     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10522     if (Subtarget.isLittleEndian()) {
10523       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10524     }
10525     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10526                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10527   }
10528   return Op;
10529 }
10530 
10531 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10532   SDLoc dl(Op);
10533   if (Op.getValueType() == MVT::v4i32) {
10534     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10535 
10536     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10537     // +16 as shift amt.
10538     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10539     SDValue RHSSwap =   // = vrlw RHS, 16
10540       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10541 
10542     // Shrinkify inputs to v8i16.
10543     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10544     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10545     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10546 
10547     // Low parts multiplied together, generating 32-bit results (we ignore the
10548     // top parts).
10549     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10550                                         LHS, RHS, DAG, dl, MVT::v4i32);
10551 
10552     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10553                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10554     // Shift the high parts up 16 bits.
10555     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10556                               Neg16, DAG, dl);
10557     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10558   } else if (Op.getValueType() == MVT::v16i8) {
10559     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10560     bool isLittleEndian = Subtarget.isLittleEndian();
10561 
10562     // Multiply the even 8-bit parts, producing 16-bit sums.
10563     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10564                                            LHS, RHS, DAG, dl, MVT::v8i16);
10565     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10566 
10567     // Multiply the odd 8-bit parts, producing 16-bit sums.
10568     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10569                                           LHS, RHS, DAG, dl, MVT::v8i16);
10570     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10571 
10572     // Merge the results together.  Because vmuleub and vmuloub are
10573     // instructions with a big-endian bias, we must reverse the
10574     // element numbering and reverse the meaning of "odd" and "even"
10575     // when generating little endian code.
10576     int Ops[16];
10577     for (unsigned i = 0; i != 8; ++i) {
10578       if (isLittleEndian) {
10579         Ops[i*2  ] = 2*i;
10580         Ops[i*2+1] = 2*i+16;
10581       } else {
10582         Ops[i*2  ] = 2*i+1;
10583         Ops[i*2+1] = 2*i+1+16;
10584       }
10585     }
10586     if (isLittleEndian)
10587       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10588     else
10589       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10590   } else {
10591     llvm_unreachable("Unknown mul to lower!");
10592   }
10593 }
10594 
10595 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10596 
10597   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10598 
10599   EVT VT = Op.getValueType();
10600   assert(VT.isVector() &&
10601          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10602   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10603           VT == MVT::v16i8) &&
10604          "Unexpected vector element type!");
10605   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10606          "Current subtarget doesn't support smax v2i64!");
10607 
10608   // For vector abs, it can be lowered to:
10609   // abs x
10610   // ==>
10611   // y = -x
10612   // smax(x, y)
10613 
10614   SDLoc dl(Op);
10615   SDValue X = Op.getOperand(0);
10616   SDValue Zero = DAG.getConstant(0, dl, VT);
10617   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10618 
10619   // SMAX patch https://reviews.llvm.org/D47332
10620   // hasn't landed yet, so use intrinsic first here.
10621   // TODO: Should use SMAX directly once SMAX patch landed
10622   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10623   if (VT == MVT::v2i64)
10624     BifID = Intrinsic::ppc_altivec_vmaxsd;
10625   else if (VT == MVT::v8i16)
10626     BifID = Intrinsic::ppc_altivec_vmaxsh;
10627   else if (VT == MVT::v16i8)
10628     BifID = Intrinsic::ppc_altivec_vmaxsb;
10629 
10630   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10631 }
10632 
10633 // Custom lowering for fpext vf32 to v2f64
10634 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10635 
10636   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10637          "Should only be called for ISD::FP_EXTEND");
10638 
10639   // FIXME: handle extends from half precision float vectors on P9.
10640   // We only want to custom lower an extend from v2f32 to v2f64.
10641   if (Op.getValueType() != MVT::v2f64 ||
10642       Op.getOperand(0).getValueType() != MVT::v2f32)
10643     return SDValue();
10644 
10645   SDLoc dl(Op);
10646   SDValue Op0 = Op.getOperand(0);
10647 
10648   switch (Op0.getOpcode()) {
10649   default:
10650     return SDValue();
10651   case ISD::EXTRACT_SUBVECTOR: {
10652     assert(Op0.getNumOperands() == 2 &&
10653            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10654            "Node should have 2 operands with second one being a constant!");
10655 
10656     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10657       return SDValue();
10658 
10659     // Custom lower is only done for high or low doubleword.
10660     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10661     if (Idx % 2 != 0)
10662       return SDValue();
10663 
10664     // Since input is v4f32, at this point Idx is either 0 or 2.
10665     // Shift to get the doubleword position we want.
10666     int DWord = Idx >> 1;
10667 
10668     // High and low word positions are different on little endian.
10669     if (Subtarget.isLittleEndian())
10670       DWord ^= 0x1;
10671 
10672     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10673                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10674   }
10675   case ISD::FADD:
10676   case ISD::FMUL:
10677   case ISD::FSUB: {
10678     SDValue NewLoad[2];
10679     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10680       // Ensure both input are loads.
10681       SDValue LdOp = Op0.getOperand(i);
10682       if (LdOp.getOpcode() != ISD::LOAD)
10683         return SDValue();
10684       // Generate new load node.
10685       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10686       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10687       NewLoad[i] = DAG.getMemIntrinsicNode(
10688           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10689           LD->getMemoryVT(), LD->getMemOperand());
10690     }
10691     SDValue NewOp =
10692         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10693                     NewLoad[1], Op0.getNode()->getFlags());
10694     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10695                        DAG.getConstant(0, dl, MVT::i32));
10696   }
10697   case ISD::LOAD: {
10698     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10699     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10700     SDValue NewLd = DAG.getMemIntrinsicNode(
10701         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10702         LD->getMemoryVT(), LD->getMemOperand());
10703     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10704                        DAG.getConstant(0, dl, MVT::i32));
10705   }
10706   }
10707   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10708 }
10709 
10710 /// LowerOperation - Provide custom lowering hooks for some operations.
10711 ///
10712 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10713   switch (Op.getOpcode()) {
10714   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10715   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10716   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10717   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10718   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10719   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10720   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10721   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10722   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10723 
10724   // Variable argument lowering.
10725   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10726   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10727   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10728 
10729   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10730   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10731   case ISD::GET_DYNAMIC_AREA_OFFSET:
10732     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10733 
10734   // Exception handling lowering.
10735   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10736   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10737   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10738 
10739   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10740   case ISD::STORE:              return LowerSTORE(Op, DAG);
10741   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10742   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10743   case ISD::STRICT_FP_TO_UINT:
10744   case ISD::STRICT_FP_TO_SINT:
10745   case ISD::FP_TO_UINT:
10746   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10747   case ISD::STRICT_UINT_TO_FP:
10748   case ISD::STRICT_SINT_TO_FP:
10749   case ISD::UINT_TO_FP:
10750   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10751   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10752 
10753   // Lower 64-bit shifts.
10754   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10755   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10756   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10757 
10758   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10759   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10760 
10761   // Vector-related lowering.
10762   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10763   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10764   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10765   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10766   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10767   case ISD::MUL:                return LowerMUL(Op, DAG);
10768   case ISD::ABS:                return LowerABS(Op, DAG);
10769   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10770   case ISD::ROTL:               return LowerROTL(Op, DAG);
10771 
10772   // For counter-based loop handling.
10773   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10774 
10775   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10776 
10777   // Frame & Return address.
10778   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10779   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10780 
10781   case ISD::INTRINSIC_VOID:
10782     return LowerINTRINSIC_VOID(Op, DAG);
10783   case ISD::BSWAP:
10784     return LowerBSWAP(Op, DAG);
10785   case ISD::ATOMIC_CMP_SWAP:
10786     return LowerATOMIC_CMP_SWAP(Op, DAG);
10787   }
10788 }
10789 
10790 void PPCTargetLowering::LowerOperationWrapper(SDNode *N,
10791                                               SmallVectorImpl<SDValue> &Results,
10792                                               SelectionDAG &DAG) const {
10793   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10794 
10795   if (!Res.getNode())
10796     return;
10797 
10798   // Take the return value as-is if original node has only one result.
10799   if (N->getNumValues() == 1) {
10800     Results.push_back(Res);
10801     return;
10802   }
10803 
10804   // New node should have the same number of results.
10805   assert((N->getNumValues() == Res->getNumValues()) &&
10806       "Lowering returned the wrong number of results!");
10807 
10808   for (unsigned i = 0; i < N->getNumValues(); ++i)
10809     Results.push_back(Res.getValue(i));
10810 }
10811 
10812 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10813                                            SmallVectorImpl<SDValue>&Results,
10814                                            SelectionDAG &DAG) const {
10815   SDLoc dl(N);
10816   switch (N->getOpcode()) {
10817   default:
10818     llvm_unreachable("Do not know how to custom type legalize this operation!");
10819   case ISD::READCYCLECOUNTER: {
10820     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10821     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10822 
10823     Results.push_back(
10824         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10825     Results.push_back(RTB.getValue(2));
10826     break;
10827   }
10828   case ISD::INTRINSIC_W_CHAIN: {
10829     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10830         Intrinsic::loop_decrement)
10831       break;
10832 
10833     assert(N->getValueType(0) == MVT::i1 &&
10834            "Unexpected result type for CTR decrement intrinsic");
10835     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10836                                  N->getValueType(0));
10837     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10838     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10839                                  N->getOperand(1));
10840 
10841     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10842     Results.push_back(NewInt.getValue(1));
10843     break;
10844   }
10845   case ISD::VAARG: {
10846     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10847       return;
10848 
10849     EVT VT = N->getValueType(0);
10850 
10851     if (VT == MVT::i64) {
10852       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10853 
10854       Results.push_back(NewNode);
10855       Results.push_back(NewNode.getValue(1));
10856     }
10857     return;
10858   }
10859   case ISD::STRICT_FP_TO_SINT:
10860   case ISD::STRICT_FP_TO_UINT:
10861   case ISD::FP_TO_SINT:
10862   case ISD::FP_TO_UINT:
10863     // LowerFP_TO_INT() can only handle f32 and f64.
10864     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10865         MVT::ppcf128)
10866       return;
10867     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10868     return;
10869   case ISD::TRUNCATE: {
10870     if (!N->getValueType(0).isVector())
10871       return;
10872     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
10873     if (Lowered)
10874       Results.push_back(Lowered);
10875     return;
10876   }
10877   case ISD::BITCAST:
10878     // Don't handle bitcast here.
10879     return;
10880   case ISD::FP_EXTEND:
10881     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10882     if (Lowered)
10883       Results.push_back(Lowered);
10884     return;
10885   }
10886 }
10887 
10888 //===----------------------------------------------------------------------===//
10889 //  Other Lowering Code
10890 //===----------------------------------------------------------------------===//
10891 
10892 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10893   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10894   Function *Func = Intrinsic::getDeclaration(M, Id);
10895   return Builder.CreateCall(Func, {});
10896 }
10897 
10898 // The mappings for emitLeading/TrailingFence is taken from
10899 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10900 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10901                                                  Instruction *Inst,
10902                                                  AtomicOrdering Ord) const {
10903   if (Ord == AtomicOrdering::SequentiallyConsistent)
10904     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10905   if (isReleaseOrStronger(Ord))
10906     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10907   return nullptr;
10908 }
10909 
10910 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10911                                                   Instruction *Inst,
10912                                                   AtomicOrdering Ord) const {
10913   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10914     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10915     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10916     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10917     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10918       return Builder.CreateCall(
10919           Intrinsic::getDeclaration(
10920               Builder.GetInsertBlock()->getParent()->getParent(),
10921               Intrinsic::ppc_cfence, {Inst->getType()}),
10922           {Inst});
10923     // FIXME: Can use isync for rmw operation.
10924     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10925   }
10926   return nullptr;
10927 }
10928 
10929 MachineBasicBlock *
10930 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10931                                     unsigned AtomicSize,
10932                                     unsigned BinOpcode,
10933                                     unsigned CmpOpcode,
10934                                     unsigned CmpPred) const {
10935   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10936   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10937 
10938   auto LoadMnemonic = PPC::LDARX;
10939   auto StoreMnemonic = PPC::STDCX;
10940   switch (AtomicSize) {
10941   default:
10942     llvm_unreachable("Unexpected size of atomic entity");
10943   case 1:
10944     LoadMnemonic = PPC::LBARX;
10945     StoreMnemonic = PPC::STBCX;
10946     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10947     break;
10948   case 2:
10949     LoadMnemonic = PPC::LHARX;
10950     StoreMnemonic = PPC::STHCX;
10951     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10952     break;
10953   case 4:
10954     LoadMnemonic = PPC::LWARX;
10955     StoreMnemonic = PPC::STWCX;
10956     break;
10957   case 8:
10958     LoadMnemonic = PPC::LDARX;
10959     StoreMnemonic = PPC::STDCX;
10960     break;
10961   }
10962 
10963   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10964   MachineFunction *F = BB->getParent();
10965   MachineFunction::iterator It = ++BB->getIterator();
10966 
10967   Register dest = MI.getOperand(0).getReg();
10968   Register ptrA = MI.getOperand(1).getReg();
10969   Register ptrB = MI.getOperand(2).getReg();
10970   Register incr = MI.getOperand(3).getReg();
10971   DebugLoc dl = MI.getDebugLoc();
10972 
10973   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10974   MachineBasicBlock *loop2MBB =
10975     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10976   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10977   F->insert(It, loopMBB);
10978   if (CmpOpcode)
10979     F->insert(It, loop2MBB);
10980   F->insert(It, exitMBB);
10981   exitMBB->splice(exitMBB->begin(), BB,
10982                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10983   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10984 
10985   MachineRegisterInfo &RegInfo = F->getRegInfo();
10986   Register TmpReg = (!BinOpcode) ? incr :
10987     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10988                                            : &PPC::GPRCRegClass);
10989 
10990   //  thisMBB:
10991   //   ...
10992   //   fallthrough --> loopMBB
10993   BB->addSuccessor(loopMBB);
10994 
10995   //  loopMBB:
10996   //   l[wd]arx dest, ptr
10997   //   add r0, dest, incr
10998   //   st[wd]cx. r0, ptr
10999   //   bne- loopMBB
11000   //   fallthrough --> exitMBB
11001 
11002   // For max/min...
11003   //  loopMBB:
11004   //   l[wd]arx dest, ptr
11005   //   cmpl?[wd] incr, dest
11006   //   bgt exitMBB
11007   //  loop2MBB:
11008   //   st[wd]cx. dest, ptr
11009   //   bne- loopMBB
11010   //   fallthrough --> exitMBB
11011 
11012   BB = loopMBB;
11013   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11014     .addReg(ptrA).addReg(ptrB);
11015   if (BinOpcode)
11016     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11017   if (CmpOpcode) {
11018     // Signed comparisons of byte or halfword values must be sign-extended.
11019     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11020       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11021       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11022               ExtReg).addReg(dest);
11023       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11024         .addReg(incr).addReg(ExtReg);
11025     } else
11026       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11027         .addReg(incr).addReg(dest);
11028 
11029     BuildMI(BB, dl, TII->get(PPC::BCC))
11030       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11031     BB->addSuccessor(loop2MBB);
11032     BB->addSuccessor(exitMBB);
11033     BB = loop2MBB;
11034   }
11035   BuildMI(BB, dl, TII->get(StoreMnemonic))
11036     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11037   BuildMI(BB, dl, TII->get(PPC::BCC))
11038     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11039   BB->addSuccessor(loopMBB);
11040   BB->addSuccessor(exitMBB);
11041 
11042   //  exitMBB:
11043   //   ...
11044   BB = exitMBB;
11045   return BB;
11046 }
11047 
11048 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11049     MachineInstr &MI, MachineBasicBlock *BB,
11050     bool is8bit, // operation
11051     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11052   // If we support part-word atomic mnemonics, just use them
11053   if (Subtarget.hasPartwordAtomics())
11054     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11055                             CmpPred);
11056 
11057   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11058   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11059   // In 64 bit mode we have to use 64 bits for addresses, even though the
11060   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11061   // registers without caring whether they're 32 or 64, but here we're
11062   // doing actual arithmetic on the addresses.
11063   bool is64bit = Subtarget.isPPC64();
11064   bool isLittleEndian = Subtarget.isLittleEndian();
11065   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11066 
11067   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11068   MachineFunction *F = BB->getParent();
11069   MachineFunction::iterator It = ++BB->getIterator();
11070 
11071   Register dest = MI.getOperand(0).getReg();
11072   Register ptrA = MI.getOperand(1).getReg();
11073   Register ptrB = MI.getOperand(2).getReg();
11074   Register incr = MI.getOperand(3).getReg();
11075   DebugLoc dl = MI.getDebugLoc();
11076 
11077   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11078   MachineBasicBlock *loop2MBB =
11079       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11080   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11081   F->insert(It, loopMBB);
11082   if (CmpOpcode)
11083     F->insert(It, loop2MBB);
11084   F->insert(It, exitMBB);
11085   exitMBB->splice(exitMBB->begin(), BB,
11086                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11087   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11088 
11089   MachineRegisterInfo &RegInfo = F->getRegInfo();
11090   const TargetRegisterClass *RC =
11091       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11092   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11093 
11094   Register PtrReg = RegInfo.createVirtualRegister(RC);
11095   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11096   Register ShiftReg =
11097       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11098   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11099   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11100   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11101   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11102   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11103   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11104   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11105   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11106   Register Ptr1Reg;
11107   Register TmpReg =
11108       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11109 
11110   //  thisMBB:
11111   //   ...
11112   //   fallthrough --> loopMBB
11113   BB->addSuccessor(loopMBB);
11114 
11115   // The 4-byte load must be aligned, while a char or short may be
11116   // anywhere in the word.  Hence all this nasty bookkeeping code.
11117   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11118   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11119   //   xori shift, shift1, 24 [16]
11120   //   rlwinm ptr, ptr1, 0, 0, 29
11121   //   slw incr2, incr, shift
11122   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11123   //   slw mask, mask2, shift
11124   //  loopMBB:
11125   //   lwarx tmpDest, ptr
11126   //   add tmp, tmpDest, incr2
11127   //   andc tmp2, tmpDest, mask
11128   //   and tmp3, tmp, mask
11129   //   or tmp4, tmp3, tmp2
11130   //   stwcx. tmp4, ptr
11131   //   bne- loopMBB
11132   //   fallthrough --> exitMBB
11133   //   srw dest, tmpDest, shift
11134   if (ptrA != ZeroReg) {
11135     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11136     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11137         .addReg(ptrA)
11138         .addReg(ptrB);
11139   } else {
11140     Ptr1Reg = ptrB;
11141   }
11142   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11143   // mode.
11144   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11145       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11146       .addImm(3)
11147       .addImm(27)
11148       .addImm(is8bit ? 28 : 27);
11149   if (!isLittleEndian)
11150     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11151         .addReg(Shift1Reg)
11152         .addImm(is8bit ? 24 : 16);
11153   if (is64bit)
11154     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11155         .addReg(Ptr1Reg)
11156         .addImm(0)
11157         .addImm(61);
11158   else
11159     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11160         .addReg(Ptr1Reg)
11161         .addImm(0)
11162         .addImm(0)
11163         .addImm(29);
11164   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11165   if (is8bit)
11166     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11167   else {
11168     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11169     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11170         .addReg(Mask3Reg)
11171         .addImm(65535);
11172   }
11173   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11174       .addReg(Mask2Reg)
11175       .addReg(ShiftReg);
11176 
11177   BB = loopMBB;
11178   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11179       .addReg(ZeroReg)
11180       .addReg(PtrReg);
11181   if (BinOpcode)
11182     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11183         .addReg(Incr2Reg)
11184         .addReg(TmpDestReg);
11185   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11186       .addReg(TmpDestReg)
11187       .addReg(MaskReg);
11188   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11189   if (CmpOpcode) {
11190     // For unsigned comparisons, we can directly compare the shifted values.
11191     // For signed comparisons we shift and sign extend.
11192     Register SReg = RegInfo.createVirtualRegister(GPRC);
11193     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11194         .addReg(TmpDestReg)
11195         .addReg(MaskReg);
11196     unsigned ValueReg = SReg;
11197     unsigned CmpReg = Incr2Reg;
11198     if (CmpOpcode == PPC::CMPW) {
11199       ValueReg = RegInfo.createVirtualRegister(GPRC);
11200       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11201           .addReg(SReg)
11202           .addReg(ShiftReg);
11203       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11204       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11205           .addReg(ValueReg);
11206       ValueReg = ValueSReg;
11207       CmpReg = incr;
11208     }
11209     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11210         .addReg(CmpReg)
11211         .addReg(ValueReg);
11212     BuildMI(BB, dl, TII->get(PPC::BCC))
11213         .addImm(CmpPred)
11214         .addReg(PPC::CR0)
11215         .addMBB(exitMBB);
11216     BB->addSuccessor(loop2MBB);
11217     BB->addSuccessor(exitMBB);
11218     BB = loop2MBB;
11219   }
11220   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11221   BuildMI(BB, dl, TII->get(PPC::STWCX))
11222       .addReg(Tmp4Reg)
11223       .addReg(ZeroReg)
11224       .addReg(PtrReg);
11225   BuildMI(BB, dl, TII->get(PPC::BCC))
11226       .addImm(PPC::PRED_NE)
11227       .addReg(PPC::CR0)
11228       .addMBB(loopMBB);
11229   BB->addSuccessor(loopMBB);
11230   BB->addSuccessor(exitMBB);
11231 
11232   //  exitMBB:
11233   //   ...
11234   BB = exitMBB;
11235   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11236       .addReg(TmpDestReg)
11237       .addReg(ShiftReg);
11238   return BB;
11239 }
11240 
11241 llvm::MachineBasicBlock *
11242 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11243                                     MachineBasicBlock *MBB) const {
11244   DebugLoc DL = MI.getDebugLoc();
11245   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11246   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11247 
11248   MachineFunction *MF = MBB->getParent();
11249   MachineRegisterInfo &MRI = MF->getRegInfo();
11250 
11251   const BasicBlock *BB = MBB->getBasicBlock();
11252   MachineFunction::iterator I = ++MBB->getIterator();
11253 
11254   Register DstReg = MI.getOperand(0).getReg();
11255   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11256   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11257   Register mainDstReg = MRI.createVirtualRegister(RC);
11258   Register restoreDstReg = MRI.createVirtualRegister(RC);
11259 
11260   MVT PVT = getPointerTy(MF->getDataLayout());
11261   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11262          "Invalid Pointer Size!");
11263   // For v = setjmp(buf), we generate
11264   //
11265   // thisMBB:
11266   //  SjLjSetup mainMBB
11267   //  bl mainMBB
11268   //  v_restore = 1
11269   //  b sinkMBB
11270   //
11271   // mainMBB:
11272   //  buf[LabelOffset] = LR
11273   //  v_main = 0
11274   //
11275   // sinkMBB:
11276   //  v = phi(main, restore)
11277   //
11278 
11279   MachineBasicBlock *thisMBB = MBB;
11280   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11281   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11282   MF->insert(I, mainMBB);
11283   MF->insert(I, sinkMBB);
11284 
11285   MachineInstrBuilder MIB;
11286 
11287   // Transfer the remainder of BB and its successor edges to sinkMBB.
11288   sinkMBB->splice(sinkMBB->begin(), MBB,
11289                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11290   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11291 
11292   // Note that the structure of the jmp_buf used here is not compatible
11293   // with that used by libc, and is not designed to be. Specifically, it
11294   // stores only those 'reserved' registers that LLVM does not otherwise
11295   // understand how to spill. Also, by convention, by the time this
11296   // intrinsic is called, Clang has already stored the frame address in the
11297   // first slot of the buffer and stack address in the third. Following the
11298   // X86 target code, we'll store the jump address in the second slot. We also
11299   // need to save the TOC pointer (R2) to handle jumps between shared
11300   // libraries, and that will be stored in the fourth slot. The thread
11301   // identifier (R13) is not affected.
11302 
11303   // thisMBB:
11304   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11305   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11306   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11307 
11308   // Prepare IP either in reg.
11309   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11310   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11311   Register BufReg = MI.getOperand(1).getReg();
11312 
11313   if (Subtarget.is64BitELFABI()) {
11314     setUsesTOCBasePtr(*MBB->getParent());
11315     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11316               .addReg(PPC::X2)
11317               .addImm(TOCOffset)
11318               .addReg(BufReg)
11319               .cloneMemRefs(MI);
11320   }
11321 
11322   // Naked functions never have a base pointer, and so we use r1. For all
11323   // other functions, this decision must be delayed until during PEI.
11324   unsigned BaseReg;
11325   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11326     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11327   else
11328     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11329 
11330   MIB = BuildMI(*thisMBB, MI, DL,
11331                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11332             .addReg(BaseReg)
11333             .addImm(BPOffset)
11334             .addReg(BufReg)
11335             .cloneMemRefs(MI);
11336 
11337   // Setup
11338   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11339   MIB.addRegMask(TRI->getNoPreservedMask());
11340 
11341   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11342 
11343   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11344           .addMBB(mainMBB);
11345   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11346 
11347   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11348   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11349 
11350   // mainMBB:
11351   //  mainDstReg = 0
11352   MIB =
11353       BuildMI(mainMBB, DL,
11354               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11355 
11356   // Store IP
11357   if (Subtarget.isPPC64()) {
11358     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11359             .addReg(LabelReg)
11360             .addImm(LabelOffset)
11361             .addReg(BufReg);
11362   } else {
11363     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11364             .addReg(LabelReg)
11365             .addImm(LabelOffset)
11366             .addReg(BufReg);
11367   }
11368   MIB.cloneMemRefs(MI);
11369 
11370   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11371   mainMBB->addSuccessor(sinkMBB);
11372 
11373   // sinkMBB:
11374   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11375           TII->get(PPC::PHI), DstReg)
11376     .addReg(mainDstReg).addMBB(mainMBB)
11377     .addReg(restoreDstReg).addMBB(thisMBB);
11378 
11379   MI.eraseFromParent();
11380   return sinkMBB;
11381 }
11382 
11383 MachineBasicBlock *
11384 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11385                                      MachineBasicBlock *MBB) const {
11386   DebugLoc DL = MI.getDebugLoc();
11387   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11388 
11389   MachineFunction *MF = MBB->getParent();
11390   MachineRegisterInfo &MRI = MF->getRegInfo();
11391 
11392   MVT PVT = getPointerTy(MF->getDataLayout());
11393   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11394          "Invalid Pointer Size!");
11395 
11396   const TargetRegisterClass *RC =
11397     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11398   Register Tmp = MRI.createVirtualRegister(RC);
11399   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11400   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11401   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11402   unsigned BP =
11403       (PVT == MVT::i64)
11404           ? PPC::X30
11405           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11406                                                               : PPC::R30);
11407 
11408   MachineInstrBuilder MIB;
11409 
11410   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11411   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11412   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11413   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11414 
11415   Register BufReg = MI.getOperand(0).getReg();
11416 
11417   // Reload FP (the jumped-to function may not have had a
11418   // frame pointer, and if so, then its r31 will be restored
11419   // as necessary).
11420   if (PVT == MVT::i64) {
11421     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11422             .addImm(0)
11423             .addReg(BufReg);
11424   } else {
11425     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11426             .addImm(0)
11427             .addReg(BufReg);
11428   }
11429   MIB.cloneMemRefs(MI);
11430 
11431   // Reload IP
11432   if (PVT == MVT::i64) {
11433     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11434             .addImm(LabelOffset)
11435             .addReg(BufReg);
11436   } else {
11437     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11438             .addImm(LabelOffset)
11439             .addReg(BufReg);
11440   }
11441   MIB.cloneMemRefs(MI);
11442 
11443   // Reload SP
11444   if (PVT == MVT::i64) {
11445     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11446             .addImm(SPOffset)
11447             .addReg(BufReg);
11448   } else {
11449     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11450             .addImm(SPOffset)
11451             .addReg(BufReg);
11452   }
11453   MIB.cloneMemRefs(MI);
11454 
11455   // Reload BP
11456   if (PVT == MVT::i64) {
11457     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11458             .addImm(BPOffset)
11459             .addReg(BufReg);
11460   } else {
11461     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11462             .addImm(BPOffset)
11463             .addReg(BufReg);
11464   }
11465   MIB.cloneMemRefs(MI);
11466 
11467   // Reload TOC
11468   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11469     setUsesTOCBasePtr(*MBB->getParent());
11470     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11471               .addImm(TOCOffset)
11472               .addReg(BufReg)
11473               .cloneMemRefs(MI);
11474   }
11475 
11476   // Jump
11477   BuildMI(*MBB, MI, DL,
11478           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11479   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11480 
11481   MI.eraseFromParent();
11482   return MBB;
11483 }
11484 
11485 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11486   // If the function specifically requests inline stack probes, emit them.
11487   if (MF.getFunction().hasFnAttribute("probe-stack"))
11488     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11489            "inline-asm";
11490   return false;
11491 }
11492 
11493 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11494   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11495   unsigned StackAlign = TFI->getStackAlignment();
11496   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11497          "Unexpected stack alignment");
11498   // The default stack probe size is 4096 if the function has no
11499   // stack-probe-size attribute.
11500   unsigned StackProbeSize = 4096;
11501   const Function &Fn = MF.getFunction();
11502   if (Fn.hasFnAttribute("stack-probe-size"))
11503     Fn.getFnAttribute("stack-probe-size")
11504         .getValueAsString()
11505         .getAsInteger(0, StackProbeSize);
11506   // Round down to the stack alignment.
11507   StackProbeSize &= ~(StackAlign - 1);
11508   return StackProbeSize ? StackProbeSize : StackAlign;
11509 }
11510 
11511 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11512 // into three phases. In the first phase, it uses pseudo instruction
11513 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11514 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11515 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11516 // MaxCallFrameSize so that it can calculate correct data area pointer.
11517 MachineBasicBlock *
11518 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11519                                     MachineBasicBlock *MBB) const {
11520   const bool isPPC64 = Subtarget.isPPC64();
11521   MachineFunction *MF = MBB->getParent();
11522   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11523   DebugLoc DL = MI.getDebugLoc();
11524   const unsigned ProbeSize = getStackProbeSize(*MF);
11525   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11526   MachineRegisterInfo &MRI = MF->getRegInfo();
11527   // The CFG of probing stack looks as
11528   //         +-----+
11529   //         | MBB |
11530   //         +--+--+
11531   //            |
11532   //       +----v----+
11533   //  +--->+ TestMBB +---+
11534   //  |    +----+----+   |
11535   //  |         |        |
11536   //  |   +-----v----+   |
11537   //  +---+ BlockMBB |   |
11538   //      +----------+   |
11539   //                     |
11540   //       +---------+   |
11541   //       | TailMBB +<--+
11542   //       +---------+
11543   // In MBB, calculate previous frame pointer and final stack pointer.
11544   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11545   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11546   // TailMBB is spliced via \p MI.
11547   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11548   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11549   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11550 
11551   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11552   MF->insert(MBBIter, TestMBB);
11553   MF->insert(MBBIter, BlockMBB);
11554   MF->insert(MBBIter, TailMBB);
11555 
11556   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11557   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11558 
11559   Register DstReg = MI.getOperand(0).getReg();
11560   Register NegSizeReg = MI.getOperand(1).getReg();
11561   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11562   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11563   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11564   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11565 
11566   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11567   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11568   // NegSize.
11569   unsigned ProbeOpc;
11570   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11571     ProbeOpc =
11572         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11573   else
11574     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11575     // and NegSizeReg will be allocated in the same phyreg to avoid
11576     // redundant copy when NegSizeReg has only one use which is current MI and
11577     // will be replaced by PREPARE_PROBED_ALLOCA then.
11578     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11579                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11580   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11581       .addDef(ActualNegSizeReg)
11582       .addReg(NegSizeReg)
11583       .add(MI.getOperand(2))
11584       .add(MI.getOperand(3));
11585 
11586   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11587   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11588           FinalStackPtr)
11589       .addReg(SPReg)
11590       .addReg(ActualNegSizeReg);
11591 
11592   // Materialize a scratch register for update.
11593   int64_t NegProbeSize = -(int64_t)ProbeSize;
11594   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11595   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11596   if (!isInt<16>(NegProbeSize)) {
11597     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11598     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11599         .addImm(NegProbeSize >> 16);
11600     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11601             ScratchReg)
11602         .addReg(TempReg)
11603         .addImm(NegProbeSize & 0xFFFF);
11604   } else
11605     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11606         .addImm(NegProbeSize);
11607 
11608   {
11609     // Probing leading residual part.
11610     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11611     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11612         .addReg(ActualNegSizeReg)
11613         .addReg(ScratchReg);
11614     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11615     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11616         .addReg(Div)
11617         .addReg(ScratchReg);
11618     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11619     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11620         .addReg(Mul)
11621         .addReg(ActualNegSizeReg);
11622     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11623         .addReg(FramePointer)
11624         .addReg(SPReg)
11625         .addReg(NegMod);
11626   }
11627 
11628   {
11629     // Remaining part should be multiple of ProbeSize.
11630     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11631     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11632         .addReg(SPReg)
11633         .addReg(FinalStackPtr);
11634     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11635         .addImm(PPC::PRED_EQ)
11636         .addReg(CmpResult)
11637         .addMBB(TailMBB);
11638     TestMBB->addSuccessor(BlockMBB);
11639     TestMBB->addSuccessor(TailMBB);
11640   }
11641 
11642   {
11643     // Touch the block.
11644     // |P...|P...|P...
11645     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11646         .addReg(FramePointer)
11647         .addReg(SPReg)
11648         .addReg(ScratchReg);
11649     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11650     BlockMBB->addSuccessor(TestMBB);
11651   }
11652 
11653   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11654   // DYNAREAOFFSET pseudo instruction to get the future result.
11655   Register MaxCallFrameSizeReg =
11656       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11657   BuildMI(TailMBB, DL,
11658           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11659           MaxCallFrameSizeReg)
11660       .add(MI.getOperand(2))
11661       .add(MI.getOperand(3));
11662   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11663       .addReg(SPReg)
11664       .addReg(MaxCallFrameSizeReg);
11665 
11666   // Splice instructions after MI to TailMBB.
11667   TailMBB->splice(TailMBB->end(), MBB,
11668                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11669   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11670   MBB->addSuccessor(TestMBB);
11671 
11672   // Delete the pseudo instruction.
11673   MI.eraseFromParent();
11674 
11675   ++NumDynamicAllocaProbed;
11676   return TailMBB;
11677 }
11678 
11679 MachineBasicBlock *
11680 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11681                                                MachineBasicBlock *BB) const {
11682   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11683       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11684     if (Subtarget.is64BitELFABI() &&
11685         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11686         !Subtarget.isUsingPCRelativeCalls()) {
11687       // Call lowering should have added an r2 operand to indicate a dependence
11688       // on the TOC base pointer value. It can't however, because there is no
11689       // way to mark the dependence as implicit there, and so the stackmap code
11690       // will confuse it with a regular operand. Instead, add the dependence
11691       // here.
11692       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11693     }
11694 
11695     return emitPatchPoint(MI, BB);
11696   }
11697 
11698   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11699       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11700     return emitEHSjLjSetJmp(MI, BB);
11701   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11702              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11703     return emitEHSjLjLongJmp(MI, BB);
11704   }
11705 
11706   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11707 
11708   // To "insert" these instructions we actually have to insert their
11709   // control-flow patterns.
11710   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11711   MachineFunction::iterator It = ++BB->getIterator();
11712 
11713   MachineFunction *F = BB->getParent();
11714 
11715   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11716       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11717       MI.getOpcode() == PPC::SELECT_I8) {
11718     SmallVector<MachineOperand, 2> Cond;
11719     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11720         MI.getOpcode() == PPC::SELECT_CC_I8)
11721       Cond.push_back(MI.getOperand(4));
11722     else
11723       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11724     Cond.push_back(MI.getOperand(1));
11725 
11726     DebugLoc dl = MI.getDebugLoc();
11727     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11728                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11729   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11730              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11731              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11732              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11733              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11734              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11735              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11736              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11737              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11738              MI.getOpcode() == PPC::SELECT_F4 ||
11739              MI.getOpcode() == PPC::SELECT_F8 ||
11740              MI.getOpcode() == PPC::SELECT_F16 ||
11741              MI.getOpcode() == PPC::SELECT_SPE ||
11742              MI.getOpcode() == PPC::SELECT_SPE4 ||
11743              MI.getOpcode() == PPC::SELECT_VRRC ||
11744              MI.getOpcode() == PPC::SELECT_VSFRC ||
11745              MI.getOpcode() == PPC::SELECT_VSSRC ||
11746              MI.getOpcode() == PPC::SELECT_VSRC) {
11747     // The incoming instruction knows the destination vreg to set, the
11748     // condition code register to branch on, the true/false values to
11749     // select between, and a branch opcode to use.
11750 
11751     //  thisMBB:
11752     //  ...
11753     //   TrueVal = ...
11754     //   cmpTY ccX, r1, r2
11755     //   bCC copy1MBB
11756     //   fallthrough --> copy0MBB
11757     MachineBasicBlock *thisMBB = BB;
11758     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11759     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11760     DebugLoc dl = MI.getDebugLoc();
11761     F->insert(It, copy0MBB);
11762     F->insert(It, sinkMBB);
11763 
11764     // Transfer the remainder of BB and its successor edges to sinkMBB.
11765     sinkMBB->splice(sinkMBB->begin(), BB,
11766                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11767     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11768 
11769     // Next, add the true and fallthrough blocks as its successors.
11770     BB->addSuccessor(copy0MBB);
11771     BB->addSuccessor(sinkMBB);
11772 
11773     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11774         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11775         MI.getOpcode() == PPC::SELECT_F16 ||
11776         MI.getOpcode() == PPC::SELECT_SPE4 ||
11777         MI.getOpcode() == PPC::SELECT_SPE ||
11778         MI.getOpcode() == PPC::SELECT_VRRC ||
11779         MI.getOpcode() == PPC::SELECT_VSFRC ||
11780         MI.getOpcode() == PPC::SELECT_VSSRC ||
11781         MI.getOpcode() == PPC::SELECT_VSRC) {
11782       BuildMI(BB, dl, TII->get(PPC::BC))
11783           .addReg(MI.getOperand(1).getReg())
11784           .addMBB(sinkMBB);
11785     } else {
11786       unsigned SelectPred = MI.getOperand(4).getImm();
11787       BuildMI(BB, dl, TII->get(PPC::BCC))
11788           .addImm(SelectPred)
11789           .addReg(MI.getOperand(1).getReg())
11790           .addMBB(sinkMBB);
11791     }
11792 
11793     //  copy0MBB:
11794     //   %FalseValue = ...
11795     //   # fallthrough to sinkMBB
11796     BB = copy0MBB;
11797 
11798     // Update machine-CFG edges
11799     BB->addSuccessor(sinkMBB);
11800 
11801     //  sinkMBB:
11802     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11803     //  ...
11804     BB = sinkMBB;
11805     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11806         .addReg(MI.getOperand(3).getReg())
11807         .addMBB(copy0MBB)
11808         .addReg(MI.getOperand(2).getReg())
11809         .addMBB(thisMBB);
11810   } else if (MI.getOpcode() == PPC::ReadTB) {
11811     // To read the 64-bit time-base register on a 32-bit target, we read the
11812     // two halves. Should the counter have wrapped while it was being read, we
11813     // need to try again.
11814     // ...
11815     // readLoop:
11816     // mfspr Rx,TBU # load from TBU
11817     // mfspr Ry,TB  # load from TB
11818     // mfspr Rz,TBU # load from TBU
11819     // cmpw crX,Rx,Rz # check if 'old'='new'
11820     // bne readLoop   # branch if they're not equal
11821     // ...
11822 
11823     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11824     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11825     DebugLoc dl = MI.getDebugLoc();
11826     F->insert(It, readMBB);
11827     F->insert(It, sinkMBB);
11828 
11829     // Transfer the remainder of BB and its successor edges to sinkMBB.
11830     sinkMBB->splice(sinkMBB->begin(), BB,
11831                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11832     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11833 
11834     BB->addSuccessor(readMBB);
11835     BB = readMBB;
11836 
11837     MachineRegisterInfo &RegInfo = F->getRegInfo();
11838     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11839     Register LoReg = MI.getOperand(0).getReg();
11840     Register HiReg = MI.getOperand(1).getReg();
11841 
11842     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11843     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11844     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11845 
11846     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11847 
11848     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11849         .addReg(HiReg)
11850         .addReg(ReadAgainReg);
11851     BuildMI(BB, dl, TII->get(PPC::BCC))
11852         .addImm(PPC::PRED_NE)
11853         .addReg(CmpReg)
11854         .addMBB(readMBB);
11855 
11856     BB->addSuccessor(readMBB);
11857     BB->addSuccessor(sinkMBB);
11858   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11859     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11860   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11861     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11862   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11863     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11864   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11865     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11866 
11867   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11868     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11869   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11870     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11871   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11872     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11873   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11874     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11875 
11876   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11877     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11878   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11879     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11880   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11881     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11882   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11883     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11884 
11885   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11886     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11887   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11888     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11889   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11890     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11891   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11892     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11893 
11894   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11895     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11896   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11897     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11898   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11899     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11900   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11901     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11902 
11903   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11904     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11905   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11906     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11907   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11908     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11909   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11910     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11911 
11912   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11913     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11914   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11915     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11916   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11917     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11918   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11919     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11920 
11921   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11922     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11923   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11924     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11925   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11926     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11927   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11928     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11929 
11930   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11931     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11932   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11933     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11934   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11935     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11936   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11937     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11938 
11939   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11940     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11941   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11942     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11943   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11944     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11945   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11946     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11947 
11948   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11949     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11950   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11951     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11952   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11953     BB = EmitAtomicBinary(MI, BB, 4, 0);
11954   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11955     BB = EmitAtomicBinary(MI, BB, 8, 0);
11956   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11957            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11958            (Subtarget.hasPartwordAtomics() &&
11959             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11960            (Subtarget.hasPartwordAtomics() &&
11961             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11962     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11963 
11964     auto LoadMnemonic = PPC::LDARX;
11965     auto StoreMnemonic = PPC::STDCX;
11966     switch (MI.getOpcode()) {
11967     default:
11968       llvm_unreachable("Compare and swap of unknown size");
11969     case PPC::ATOMIC_CMP_SWAP_I8:
11970       LoadMnemonic = PPC::LBARX;
11971       StoreMnemonic = PPC::STBCX;
11972       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11973       break;
11974     case PPC::ATOMIC_CMP_SWAP_I16:
11975       LoadMnemonic = PPC::LHARX;
11976       StoreMnemonic = PPC::STHCX;
11977       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11978       break;
11979     case PPC::ATOMIC_CMP_SWAP_I32:
11980       LoadMnemonic = PPC::LWARX;
11981       StoreMnemonic = PPC::STWCX;
11982       break;
11983     case PPC::ATOMIC_CMP_SWAP_I64:
11984       LoadMnemonic = PPC::LDARX;
11985       StoreMnemonic = PPC::STDCX;
11986       break;
11987     }
11988     Register dest = MI.getOperand(0).getReg();
11989     Register ptrA = MI.getOperand(1).getReg();
11990     Register ptrB = MI.getOperand(2).getReg();
11991     Register oldval = MI.getOperand(3).getReg();
11992     Register newval = MI.getOperand(4).getReg();
11993     DebugLoc dl = MI.getDebugLoc();
11994 
11995     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11996     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11997     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11998     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11999     F->insert(It, loop1MBB);
12000     F->insert(It, loop2MBB);
12001     F->insert(It, midMBB);
12002     F->insert(It, exitMBB);
12003     exitMBB->splice(exitMBB->begin(), BB,
12004                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12005     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12006 
12007     //  thisMBB:
12008     //   ...
12009     //   fallthrough --> loopMBB
12010     BB->addSuccessor(loop1MBB);
12011 
12012     // loop1MBB:
12013     //   l[bhwd]arx dest, ptr
12014     //   cmp[wd] dest, oldval
12015     //   bne- midMBB
12016     // loop2MBB:
12017     //   st[bhwd]cx. newval, ptr
12018     //   bne- loopMBB
12019     //   b exitBB
12020     // midMBB:
12021     //   st[bhwd]cx. dest, ptr
12022     // exitBB:
12023     BB = loop1MBB;
12024     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12025     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12026         .addReg(oldval)
12027         .addReg(dest);
12028     BuildMI(BB, dl, TII->get(PPC::BCC))
12029         .addImm(PPC::PRED_NE)
12030         .addReg(PPC::CR0)
12031         .addMBB(midMBB);
12032     BB->addSuccessor(loop2MBB);
12033     BB->addSuccessor(midMBB);
12034 
12035     BB = loop2MBB;
12036     BuildMI(BB, dl, TII->get(StoreMnemonic))
12037         .addReg(newval)
12038         .addReg(ptrA)
12039         .addReg(ptrB);
12040     BuildMI(BB, dl, TII->get(PPC::BCC))
12041         .addImm(PPC::PRED_NE)
12042         .addReg(PPC::CR0)
12043         .addMBB(loop1MBB);
12044     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12045     BB->addSuccessor(loop1MBB);
12046     BB->addSuccessor(exitMBB);
12047 
12048     BB = midMBB;
12049     BuildMI(BB, dl, TII->get(StoreMnemonic))
12050         .addReg(dest)
12051         .addReg(ptrA)
12052         .addReg(ptrB);
12053     BB->addSuccessor(exitMBB);
12054 
12055     //  exitMBB:
12056     //   ...
12057     BB = exitMBB;
12058   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12059              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12060     // We must use 64-bit registers for addresses when targeting 64-bit,
12061     // since we're actually doing arithmetic on them.  Other registers
12062     // can be 32-bit.
12063     bool is64bit = Subtarget.isPPC64();
12064     bool isLittleEndian = Subtarget.isLittleEndian();
12065     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12066 
12067     Register dest = MI.getOperand(0).getReg();
12068     Register ptrA = MI.getOperand(1).getReg();
12069     Register ptrB = MI.getOperand(2).getReg();
12070     Register oldval = MI.getOperand(3).getReg();
12071     Register newval = MI.getOperand(4).getReg();
12072     DebugLoc dl = MI.getDebugLoc();
12073 
12074     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12075     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12076     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12077     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12078     F->insert(It, loop1MBB);
12079     F->insert(It, loop2MBB);
12080     F->insert(It, midMBB);
12081     F->insert(It, exitMBB);
12082     exitMBB->splice(exitMBB->begin(), BB,
12083                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12084     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12085 
12086     MachineRegisterInfo &RegInfo = F->getRegInfo();
12087     const TargetRegisterClass *RC =
12088         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12089     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12090 
12091     Register PtrReg = RegInfo.createVirtualRegister(RC);
12092     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12093     Register ShiftReg =
12094         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12095     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12096     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12097     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12098     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12099     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12100     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12101     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12102     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12103     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12104     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12105     Register Ptr1Reg;
12106     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12107     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12108     //  thisMBB:
12109     //   ...
12110     //   fallthrough --> loopMBB
12111     BB->addSuccessor(loop1MBB);
12112 
12113     // The 4-byte load must be aligned, while a char or short may be
12114     // anywhere in the word.  Hence all this nasty bookkeeping code.
12115     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12116     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12117     //   xori shift, shift1, 24 [16]
12118     //   rlwinm ptr, ptr1, 0, 0, 29
12119     //   slw newval2, newval, shift
12120     //   slw oldval2, oldval,shift
12121     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12122     //   slw mask, mask2, shift
12123     //   and newval3, newval2, mask
12124     //   and oldval3, oldval2, mask
12125     // loop1MBB:
12126     //   lwarx tmpDest, ptr
12127     //   and tmp, tmpDest, mask
12128     //   cmpw tmp, oldval3
12129     //   bne- midMBB
12130     // loop2MBB:
12131     //   andc tmp2, tmpDest, mask
12132     //   or tmp4, tmp2, newval3
12133     //   stwcx. tmp4, ptr
12134     //   bne- loop1MBB
12135     //   b exitBB
12136     // midMBB:
12137     //   stwcx. tmpDest, ptr
12138     // exitBB:
12139     //   srw dest, tmpDest, shift
12140     if (ptrA != ZeroReg) {
12141       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12142       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12143           .addReg(ptrA)
12144           .addReg(ptrB);
12145     } else {
12146       Ptr1Reg = ptrB;
12147     }
12148 
12149     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12150     // mode.
12151     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12152         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12153         .addImm(3)
12154         .addImm(27)
12155         .addImm(is8bit ? 28 : 27);
12156     if (!isLittleEndian)
12157       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12158           .addReg(Shift1Reg)
12159           .addImm(is8bit ? 24 : 16);
12160     if (is64bit)
12161       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12162           .addReg(Ptr1Reg)
12163           .addImm(0)
12164           .addImm(61);
12165     else
12166       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12167           .addReg(Ptr1Reg)
12168           .addImm(0)
12169           .addImm(0)
12170           .addImm(29);
12171     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12172         .addReg(newval)
12173         .addReg(ShiftReg);
12174     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12175         .addReg(oldval)
12176         .addReg(ShiftReg);
12177     if (is8bit)
12178       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12179     else {
12180       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12181       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12182           .addReg(Mask3Reg)
12183           .addImm(65535);
12184     }
12185     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12186         .addReg(Mask2Reg)
12187         .addReg(ShiftReg);
12188     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12189         .addReg(NewVal2Reg)
12190         .addReg(MaskReg);
12191     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12192         .addReg(OldVal2Reg)
12193         .addReg(MaskReg);
12194 
12195     BB = loop1MBB;
12196     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12197         .addReg(ZeroReg)
12198         .addReg(PtrReg);
12199     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12200         .addReg(TmpDestReg)
12201         .addReg(MaskReg);
12202     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12203         .addReg(TmpReg)
12204         .addReg(OldVal3Reg);
12205     BuildMI(BB, dl, TII->get(PPC::BCC))
12206         .addImm(PPC::PRED_NE)
12207         .addReg(PPC::CR0)
12208         .addMBB(midMBB);
12209     BB->addSuccessor(loop2MBB);
12210     BB->addSuccessor(midMBB);
12211 
12212     BB = loop2MBB;
12213     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12214         .addReg(TmpDestReg)
12215         .addReg(MaskReg);
12216     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12217         .addReg(Tmp2Reg)
12218         .addReg(NewVal3Reg);
12219     BuildMI(BB, dl, TII->get(PPC::STWCX))
12220         .addReg(Tmp4Reg)
12221         .addReg(ZeroReg)
12222         .addReg(PtrReg);
12223     BuildMI(BB, dl, TII->get(PPC::BCC))
12224         .addImm(PPC::PRED_NE)
12225         .addReg(PPC::CR0)
12226         .addMBB(loop1MBB);
12227     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12228     BB->addSuccessor(loop1MBB);
12229     BB->addSuccessor(exitMBB);
12230 
12231     BB = midMBB;
12232     BuildMI(BB, dl, TII->get(PPC::STWCX))
12233         .addReg(TmpDestReg)
12234         .addReg(ZeroReg)
12235         .addReg(PtrReg);
12236     BB->addSuccessor(exitMBB);
12237 
12238     //  exitMBB:
12239     //   ...
12240     BB = exitMBB;
12241     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12242         .addReg(TmpReg)
12243         .addReg(ShiftReg);
12244   } else if (MI.getOpcode() == PPC::FADDrtz) {
12245     // This pseudo performs an FADD with rounding mode temporarily forced
12246     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12247     // is not modeled at the SelectionDAG level.
12248     Register Dest = MI.getOperand(0).getReg();
12249     Register Src1 = MI.getOperand(1).getReg();
12250     Register Src2 = MI.getOperand(2).getReg();
12251     DebugLoc dl = MI.getDebugLoc();
12252 
12253     MachineRegisterInfo &RegInfo = F->getRegInfo();
12254     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12255 
12256     // Save FPSCR value.
12257     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12258 
12259     // Set rounding mode to round-to-zero.
12260     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12261         .addImm(31)
12262         .addReg(PPC::RM, RegState::ImplicitDefine);
12263 
12264     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12265         .addImm(30)
12266         .addReg(PPC::RM, RegState::ImplicitDefine);
12267 
12268     // Perform addition.
12269     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12270                    .addReg(Src1)
12271                    .addReg(Src2);
12272     if (MI.getFlag(MachineInstr::NoFPExcept))
12273       MIB.setMIFlag(MachineInstr::NoFPExcept);
12274 
12275     // Restore FPSCR value.
12276     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12277   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12278              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12279              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12280              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12281     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12282                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12283                           ? PPC::ANDI8_rec
12284                           : PPC::ANDI_rec;
12285     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12286                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12287 
12288     MachineRegisterInfo &RegInfo = F->getRegInfo();
12289     Register Dest = RegInfo.createVirtualRegister(
12290         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12291 
12292     DebugLoc Dl = MI.getDebugLoc();
12293     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12294         .addReg(MI.getOperand(1).getReg())
12295         .addImm(1);
12296     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12297             MI.getOperand(0).getReg())
12298         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12299   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12300     DebugLoc Dl = MI.getDebugLoc();
12301     MachineRegisterInfo &RegInfo = F->getRegInfo();
12302     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12303     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12304     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12305             MI.getOperand(0).getReg())
12306         .addReg(CRReg);
12307   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12308     DebugLoc Dl = MI.getDebugLoc();
12309     unsigned Imm = MI.getOperand(1).getImm();
12310     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12311     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12312             MI.getOperand(0).getReg())
12313         .addReg(PPC::CR0EQ);
12314   } else if (MI.getOpcode() == PPC::SETRNDi) {
12315     DebugLoc dl = MI.getDebugLoc();
12316     Register OldFPSCRReg = MI.getOperand(0).getReg();
12317 
12318     // Save FPSCR value.
12319     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12320 
12321     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12322     // the following settings:
12323     //   00 Round to nearest
12324     //   01 Round to 0
12325     //   10 Round to +inf
12326     //   11 Round to -inf
12327 
12328     // When the operand is immediate, using the two least significant bits of
12329     // the immediate to set the bits 62:63 of FPSCR.
12330     unsigned Mode = MI.getOperand(1).getImm();
12331     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12332         .addImm(31)
12333         .addReg(PPC::RM, RegState::ImplicitDefine);
12334 
12335     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12336         .addImm(30)
12337         .addReg(PPC::RM, RegState::ImplicitDefine);
12338   } else if (MI.getOpcode() == PPC::SETRND) {
12339     DebugLoc dl = MI.getDebugLoc();
12340 
12341     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12342     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12343     // If the target doesn't have DirectMove, we should use stack to do the
12344     // conversion, because the target doesn't have the instructions like mtvsrd
12345     // or mfvsrd to do this conversion directly.
12346     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12347       if (Subtarget.hasDirectMove()) {
12348         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12349           .addReg(SrcReg);
12350       } else {
12351         // Use stack to do the register copy.
12352         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12353         MachineRegisterInfo &RegInfo = F->getRegInfo();
12354         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12355         if (RC == &PPC::F8RCRegClass) {
12356           // Copy register from F8RCRegClass to G8RCRegclass.
12357           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12358                  "Unsupported RegClass.");
12359 
12360           StoreOp = PPC::STFD;
12361           LoadOp = PPC::LD;
12362         } else {
12363           // Copy register from G8RCRegClass to F8RCRegclass.
12364           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12365                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12366                  "Unsupported RegClass.");
12367         }
12368 
12369         MachineFrameInfo &MFI = F->getFrameInfo();
12370         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12371 
12372         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12373             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12374             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12375             MFI.getObjectAlign(FrameIdx));
12376 
12377         // Store the SrcReg into the stack.
12378         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12379           .addReg(SrcReg)
12380           .addImm(0)
12381           .addFrameIndex(FrameIdx)
12382           .addMemOperand(MMOStore);
12383 
12384         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12385             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12386             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12387             MFI.getObjectAlign(FrameIdx));
12388 
12389         // Load from the stack where SrcReg is stored, and save to DestReg,
12390         // so we have done the RegClass conversion from RegClass::SrcReg to
12391         // RegClass::DestReg.
12392         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12393           .addImm(0)
12394           .addFrameIndex(FrameIdx)
12395           .addMemOperand(MMOLoad);
12396       }
12397     };
12398 
12399     Register OldFPSCRReg = MI.getOperand(0).getReg();
12400 
12401     // Save FPSCR value.
12402     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12403 
12404     // When the operand is gprc register, use two least significant bits of the
12405     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12406     //
12407     // copy OldFPSCRTmpReg, OldFPSCRReg
12408     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12409     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12410     // copy NewFPSCRReg, NewFPSCRTmpReg
12411     // mtfsf 255, NewFPSCRReg
12412     MachineOperand SrcOp = MI.getOperand(1);
12413     MachineRegisterInfo &RegInfo = F->getRegInfo();
12414     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12415 
12416     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12417 
12418     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12419     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12420 
12421     // The first operand of INSERT_SUBREG should be a register which has
12422     // subregisters, we only care about its RegClass, so we should use an
12423     // IMPLICIT_DEF register.
12424     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12425     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12426       .addReg(ImDefReg)
12427       .add(SrcOp)
12428       .addImm(1);
12429 
12430     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12431     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12432       .addReg(OldFPSCRTmpReg)
12433       .addReg(ExtSrcReg)
12434       .addImm(0)
12435       .addImm(62);
12436 
12437     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12438     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12439 
12440     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12441     // bits of FPSCR.
12442     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12443       .addImm(255)
12444       .addReg(NewFPSCRReg)
12445       .addImm(0)
12446       .addImm(0);
12447   } else if (MI.getOpcode() == PPC::SETFLM) {
12448     DebugLoc Dl = MI.getDebugLoc();
12449 
12450     // Result of setflm is previous FPSCR content, so we need to save it first.
12451     Register OldFPSCRReg = MI.getOperand(0).getReg();
12452     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12453 
12454     // Put bits in 32:63 to FPSCR.
12455     Register NewFPSCRReg = MI.getOperand(1).getReg();
12456     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12457         .addImm(255)
12458         .addReg(NewFPSCRReg)
12459         .addImm(0)
12460         .addImm(0);
12461   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12462              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12463     return emitProbedAlloca(MI, BB);
12464   } else {
12465     llvm_unreachable("Unexpected instr type to insert");
12466   }
12467 
12468   MI.eraseFromParent(); // The pseudo instruction is gone now.
12469   return BB;
12470 }
12471 
12472 //===----------------------------------------------------------------------===//
12473 // Target Optimization Hooks
12474 //===----------------------------------------------------------------------===//
12475 
12476 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12477   // For the estimates, convergence is quadratic, so we essentially double the
12478   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12479   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12480   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12481   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12482   if (VT.getScalarType() == MVT::f64)
12483     RefinementSteps++;
12484   return RefinementSteps;
12485 }
12486 
12487 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12488                                            int Enabled, int &RefinementSteps,
12489                                            bool &UseOneConstNR,
12490                                            bool Reciprocal) const {
12491   EVT VT = Operand.getValueType();
12492   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12493       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12494       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12495       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12496     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12497       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12498 
12499     // The Newton-Raphson computation with a single constant does not provide
12500     // enough accuracy on some CPUs.
12501     UseOneConstNR = !Subtarget.needsTwoConstNR();
12502     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12503   }
12504   return SDValue();
12505 }
12506 
12507 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12508                                             int Enabled,
12509                                             int &RefinementSteps) const {
12510   EVT VT = Operand.getValueType();
12511   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12512       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12513       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12514       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12515     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12516       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12517     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12518   }
12519   return SDValue();
12520 }
12521 
12522 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12523   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12524   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12525   // enabled for division), this functionality is redundant with the default
12526   // combiner logic (once the division -> reciprocal/multiply transformation
12527   // has taken place). As a result, this matters more for older cores than for
12528   // newer ones.
12529 
12530   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12531   // reciprocal if there are two or more FDIVs (for embedded cores with only
12532   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12533   switch (Subtarget.getCPUDirective()) {
12534   default:
12535     return 3;
12536   case PPC::DIR_440:
12537   case PPC::DIR_A2:
12538   case PPC::DIR_E500:
12539   case PPC::DIR_E500mc:
12540   case PPC::DIR_E5500:
12541     return 2;
12542   }
12543 }
12544 
12545 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12546 // collapsed, and so we need to look through chains of them.
12547 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12548                                      int64_t& Offset, SelectionDAG &DAG) {
12549   if (DAG.isBaseWithConstantOffset(Loc)) {
12550     Base = Loc.getOperand(0);
12551     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12552 
12553     // The base might itself be a base plus an offset, and if so, accumulate
12554     // that as well.
12555     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12556   }
12557 }
12558 
12559 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12560                             unsigned Bytes, int Dist,
12561                             SelectionDAG &DAG) {
12562   if (VT.getSizeInBits() / 8 != Bytes)
12563     return false;
12564 
12565   SDValue BaseLoc = Base->getBasePtr();
12566   if (Loc.getOpcode() == ISD::FrameIndex) {
12567     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12568       return false;
12569     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12570     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12571     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12572     int FS  = MFI.getObjectSize(FI);
12573     int BFS = MFI.getObjectSize(BFI);
12574     if (FS != BFS || FS != (int)Bytes) return false;
12575     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12576   }
12577 
12578   SDValue Base1 = Loc, Base2 = BaseLoc;
12579   int64_t Offset1 = 0, Offset2 = 0;
12580   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12581   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12582   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12583     return true;
12584 
12585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12586   const GlobalValue *GV1 = nullptr;
12587   const GlobalValue *GV2 = nullptr;
12588   Offset1 = 0;
12589   Offset2 = 0;
12590   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12591   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12592   if (isGA1 && isGA2 && GV1 == GV2)
12593     return Offset1 == (Offset2 + Dist*Bytes);
12594   return false;
12595 }
12596 
12597 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12598 // not enforce equality of the chain operands.
12599 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12600                             unsigned Bytes, int Dist,
12601                             SelectionDAG &DAG) {
12602   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12603     EVT VT = LS->getMemoryVT();
12604     SDValue Loc = LS->getBasePtr();
12605     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12606   }
12607 
12608   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12609     EVT VT;
12610     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12611     default: return false;
12612     case Intrinsic::ppc_altivec_lvx:
12613     case Intrinsic::ppc_altivec_lvxl:
12614     case Intrinsic::ppc_vsx_lxvw4x:
12615     case Intrinsic::ppc_vsx_lxvw4x_be:
12616       VT = MVT::v4i32;
12617       break;
12618     case Intrinsic::ppc_vsx_lxvd2x:
12619     case Intrinsic::ppc_vsx_lxvd2x_be:
12620       VT = MVT::v2f64;
12621       break;
12622     case Intrinsic::ppc_altivec_lvebx:
12623       VT = MVT::i8;
12624       break;
12625     case Intrinsic::ppc_altivec_lvehx:
12626       VT = MVT::i16;
12627       break;
12628     case Intrinsic::ppc_altivec_lvewx:
12629       VT = MVT::i32;
12630       break;
12631     }
12632 
12633     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12634   }
12635 
12636   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12637     EVT VT;
12638     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12639     default: return false;
12640     case Intrinsic::ppc_altivec_stvx:
12641     case Intrinsic::ppc_altivec_stvxl:
12642     case Intrinsic::ppc_vsx_stxvw4x:
12643       VT = MVT::v4i32;
12644       break;
12645     case Intrinsic::ppc_vsx_stxvd2x:
12646       VT = MVT::v2f64;
12647       break;
12648     case Intrinsic::ppc_vsx_stxvw4x_be:
12649       VT = MVT::v4i32;
12650       break;
12651     case Intrinsic::ppc_vsx_stxvd2x_be:
12652       VT = MVT::v2f64;
12653       break;
12654     case Intrinsic::ppc_altivec_stvebx:
12655       VT = MVT::i8;
12656       break;
12657     case Intrinsic::ppc_altivec_stvehx:
12658       VT = MVT::i16;
12659       break;
12660     case Intrinsic::ppc_altivec_stvewx:
12661       VT = MVT::i32;
12662       break;
12663     }
12664 
12665     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12666   }
12667 
12668   return false;
12669 }
12670 
12671 // Return true is there is a nearyby consecutive load to the one provided
12672 // (regardless of alignment). We search up and down the chain, looking though
12673 // token factors and other loads (but nothing else). As a result, a true result
12674 // indicates that it is safe to create a new consecutive load adjacent to the
12675 // load provided.
12676 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12677   SDValue Chain = LD->getChain();
12678   EVT VT = LD->getMemoryVT();
12679 
12680   SmallSet<SDNode *, 16> LoadRoots;
12681   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12682   SmallSet<SDNode *, 16> Visited;
12683 
12684   // First, search up the chain, branching to follow all token-factor operands.
12685   // If we find a consecutive load, then we're done, otherwise, record all
12686   // nodes just above the top-level loads and token factors.
12687   while (!Queue.empty()) {
12688     SDNode *ChainNext = Queue.pop_back_val();
12689     if (!Visited.insert(ChainNext).second)
12690       continue;
12691 
12692     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12693       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12694         return true;
12695 
12696       if (!Visited.count(ChainLD->getChain().getNode()))
12697         Queue.push_back(ChainLD->getChain().getNode());
12698     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12699       for (const SDUse &O : ChainNext->ops())
12700         if (!Visited.count(O.getNode()))
12701           Queue.push_back(O.getNode());
12702     } else
12703       LoadRoots.insert(ChainNext);
12704   }
12705 
12706   // Second, search down the chain, starting from the top-level nodes recorded
12707   // in the first phase. These top-level nodes are the nodes just above all
12708   // loads and token factors. Starting with their uses, recursively look though
12709   // all loads (just the chain uses) and token factors to find a consecutive
12710   // load.
12711   Visited.clear();
12712   Queue.clear();
12713 
12714   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12715        IE = LoadRoots.end(); I != IE; ++I) {
12716     Queue.push_back(*I);
12717 
12718     while (!Queue.empty()) {
12719       SDNode *LoadRoot = Queue.pop_back_val();
12720       if (!Visited.insert(LoadRoot).second)
12721         continue;
12722 
12723       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12724         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12725           return true;
12726 
12727       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12728            UE = LoadRoot->use_end(); UI != UE; ++UI)
12729         if (((isa<MemSDNode>(*UI) &&
12730             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12731             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12732           Queue.push_back(*UI);
12733     }
12734   }
12735 
12736   return false;
12737 }
12738 
12739 /// This function is called when we have proved that a SETCC node can be replaced
12740 /// by subtraction (and other supporting instructions) so that the result of
12741 /// comparison is kept in a GPR instead of CR. This function is purely for
12742 /// codegen purposes and has some flags to guide the codegen process.
12743 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12744                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12745   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12746 
12747   // Zero extend the operands to the largest legal integer. Originally, they
12748   // must be of a strictly smaller size.
12749   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12750                          DAG.getConstant(Size, DL, MVT::i32));
12751   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12752                          DAG.getConstant(Size, DL, MVT::i32));
12753 
12754   // Swap if needed. Depends on the condition code.
12755   if (Swap)
12756     std::swap(Op0, Op1);
12757 
12758   // Subtract extended integers.
12759   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12760 
12761   // Move the sign bit to the least significant position and zero out the rest.
12762   // Now the least significant bit carries the result of original comparison.
12763   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12764                              DAG.getConstant(Size - 1, DL, MVT::i32));
12765   auto Final = Shifted;
12766 
12767   // Complement the result if needed. Based on the condition code.
12768   if (Complement)
12769     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12770                         DAG.getConstant(1, DL, MVT::i64));
12771 
12772   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12773 }
12774 
12775 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12776                                                   DAGCombinerInfo &DCI) const {
12777   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12778 
12779   SelectionDAG &DAG = DCI.DAG;
12780   SDLoc DL(N);
12781 
12782   // Size of integers being compared has a critical role in the following
12783   // analysis, so we prefer to do this when all types are legal.
12784   if (!DCI.isAfterLegalizeDAG())
12785     return SDValue();
12786 
12787   // If all users of SETCC extend its value to a legal integer type
12788   // then we replace SETCC with a subtraction
12789   for (SDNode::use_iterator UI = N->use_begin(),
12790        UE = N->use_end(); UI != UE; ++UI) {
12791     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12792       return SDValue();
12793   }
12794 
12795   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12796   auto OpSize = N->getOperand(0).getValueSizeInBits();
12797 
12798   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12799 
12800   if (OpSize < Size) {
12801     switch (CC) {
12802     default: break;
12803     case ISD::SETULT:
12804       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12805     case ISD::SETULE:
12806       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12807     case ISD::SETUGT:
12808       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12809     case ISD::SETUGE:
12810       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12811     }
12812   }
12813 
12814   return SDValue();
12815 }
12816 
12817 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12818                                                   DAGCombinerInfo &DCI) const {
12819   SelectionDAG &DAG = DCI.DAG;
12820   SDLoc dl(N);
12821 
12822   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12823   // If we're tracking CR bits, we need to be careful that we don't have:
12824   //   trunc(binary-ops(zext(x), zext(y)))
12825   // or
12826   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12827   // such that we're unnecessarily moving things into GPRs when it would be
12828   // better to keep them in CR bits.
12829 
12830   // Note that trunc here can be an actual i1 trunc, or can be the effective
12831   // truncation that comes from a setcc or select_cc.
12832   if (N->getOpcode() == ISD::TRUNCATE &&
12833       N->getValueType(0) != MVT::i1)
12834     return SDValue();
12835 
12836   if (N->getOperand(0).getValueType() != MVT::i32 &&
12837       N->getOperand(0).getValueType() != MVT::i64)
12838     return SDValue();
12839 
12840   if (N->getOpcode() == ISD::SETCC ||
12841       N->getOpcode() == ISD::SELECT_CC) {
12842     // If we're looking at a comparison, then we need to make sure that the
12843     // high bits (all except for the first) don't matter the result.
12844     ISD::CondCode CC =
12845       cast<CondCodeSDNode>(N->getOperand(
12846         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12847     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12848 
12849     if (ISD::isSignedIntSetCC(CC)) {
12850       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12851           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12852         return SDValue();
12853     } else if (ISD::isUnsignedIntSetCC(CC)) {
12854       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12855                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12856           !DAG.MaskedValueIsZero(N->getOperand(1),
12857                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12858         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12859                                              : SDValue());
12860     } else {
12861       // This is neither a signed nor an unsigned comparison, just make sure
12862       // that the high bits are equal.
12863       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12864       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12865 
12866       // We don't really care about what is known about the first bit (if
12867       // anything), so clear it in all masks prior to comparing them.
12868       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12869       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12870 
12871       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12872         return SDValue();
12873     }
12874   }
12875 
12876   // We now know that the higher-order bits are irrelevant, we just need to
12877   // make sure that all of the intermediate operations are bit operations, and
12878   // all inputs are extensions.
12879   if (N->getOperand(0).getOpcode() != ISD::AND &&
12880       N->getOperand(0).getOpcode() != ISD::OR  &&
12881       N->getOperand(0).getOpcode() != ISD::XOR &&
12882       N->getOperand(0).getOpcode() != ISD::SELECT &&
12883       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12884       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12885       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12886       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12887       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12888     return SDValue();
12889 
12890   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12891       N->getOperand(1).getOpcode() != ISD::AND &&
12892       N->getOperand(1).getOpcode() != ISD::OR  &&
12893       N->getOperand(1).getOpcode() != ISD::XOR &&
12894       N->getOperand(1).getOpcode() != ISD::SELECT &&
12895       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12896       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12897       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12898       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12899       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12900     return SDValue();
12901 
12902   SmallVector<SDValue, 4> Inputs;
12903   SmallVector<SDValue, 8> BinOps, PromOps;
12904   SmallPtrSet<SDNode *, 16> Visited;
12905 
12906   for (unsigned i = 0; i < 2; ++i) {
12907     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12908           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12909           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12910           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12911         isa<ConstantSDNode>(N->getOperand(i)))
12912       Inputs.push_back(N->getOperand(i));
12913     else
12914       BinOps.push_back(N->getOperand(i));
12915 
12916     if (N->getOpcode() == ISD::TRUNCATE)
12917       break;
12918   }
12919 
12920   // Visit all inputs, collect all binary operations (and, or, xor and
12921   // select) that are all fed by extensions.
12922   while (!BinOps.empty()) {
12923     SDValue BinOp = BinOps.back();
12924     BinOps.pop_back();
12925 
12926     if (!Visited.insert(BinOp.getNode()).second)
12927       continue;
12928 
12929     PromOps.push_back(BinOp);
12930 
12931     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12932       // The condition of the select is not promoted.
12933       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12934         continue;
12935       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12936         continue;
12937 
12938       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12939             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12940             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12941            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12942           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12943         Inputs.push_back(BinOp.getOperand(i));
12944       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12945                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12946                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12947                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12948                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12949                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12950                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12951                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12952                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12953         BinOps.push_back(BinOp.getOperand(i));
12954       } else {
12955         // We have an input that is not an extension or another binary
12956         // operation; we'll abort this transformation.
12957         return SDValue();
12958       }
12959     }
12960   }
12961 
12962   // Make sure that this is a self-contained cluster of operations (which
12963   // is not quite the same thing as saying that everything has only one
12964   // use).
12965   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12966     if (isa<ConstantSDNode>(Inputs[i]))
12967       continue;
12968 
12969     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12970                               UE = Inputs[i].getNode()->use_end();
12971          UI != UE; ++UI) {
12972       SDNode *User = *UI;
12973       if (User != N && !Visited.count(User))
12974         return SDValue();
12975 
12976       // Make sure that we're not going to promote the non-output-value
12977       // operand(s) or SELECT or SELECT_CC.
12978       // FIXME: Although we could sometimes handle this, and it does occur in
12979       // practice that one of the condition inputs to the select is also one of
12980       // the outputs, we currently can't deal with this.
12981       if (User->getOpcode() == ISD::SELECT) {
12982         if (User->getOperand(0) == Inputs[i])
12983           return SDValue();
12984       } else if (User->getOpcode() == ISD::SELECT_CC) {
12985         if (User->getOperand(0) == Inputs[i] ||
12986             User->getOperand(1) == Inputs[i])
12987           return SDValue();
12988       }
12989     }
12990   }
12991 
12992   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12993     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12994                               UE = PromOps[i].getNode()->use_end();
12995          UI != UE; ++UI) {
12996       SDNode *User = *UI;
12997       if (User != N && !Visited.count(User))
12998         return SDValue();
12999 
13000       // Make sure that we're not going to promote the non-output-value
13001       // operand(s) or SELECT or SELECT_CC.
13002       // FIXME: Although we could sometimes handle this, and it does occur in
13003       // practice that one of the condition inputs to the select is also one of
13004       // the outputs, we currently can't deal with this.
13005       if (User->getOpcode() == ISD::SELECT) {
13006         if (User->getOperand(0) == PromOps[i])
13007           return SDValue();
13008       } else if (User->getOpcode() == ISD::SELECT_CC) {
13009         if (User->getOperand(0) == PromOps[i] ||
13010             User->getOperand(1) == PromOps[i])
13011           return SDValue();
13012       }
13013     }
13014   }
13015 
13016   // Replace all inputs with the extension operand.
13017   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13018     // Constants may have users outside the cluster of to-be-promoted nodes,
13019     // and so we need to replace those as we do the promotions.
13020     if (isa<ConstantSDNode>(Inputs[i]))
13021       continue;
13022     else
13023       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13024   }
13025 
13026   std::list<HandleSDNode> PromOpHandles;
13027   for (auto &PromOp : PromOps)
13028     PromOpHandles.emplace_back(PromOp);
13029 
13030   // Replace all operations (these are all the same, but have a different
13031   // (i1) return type). DAG.getNode will validate that the types of
13032   // a binary operator match, so go through the list in reverse so that
13033   // we've likely promoted both operands first. Any intermediate truncations or
13034   // extensions disappear.
13035   while (!PromOpHandles.empty()) {
13036     SDValue PromOp = PromOpHandles.back().getValue();
13037     PromOpHandles.pop_back();
13038 
13039     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13040         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13041         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13042         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13043       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13044           PromOp.getOperand(0).getValueType() != MVT::i1) {
13045         // The operand is not yet ready (see comment below).
13046         PromOpHandles.emplace_front(PromOp);
13047         continue;
13048       }
13049 
13050       SDValue RepValue = PromOp.getOperand(0);
13051       if (isa<ConstantSDNode>(RepValue))
13052         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13053 
13054       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13055       continue;
13056     }
13057 
13058     unsigned C;
13059     switch (PromOp.getOpcode()) {
13060     default:             C = 0; break;
13061     case ISD::SELECT:    C = 1; break;
13062     case ISD::SELECT_CC: C = 2; break;
13063     }
13064 
13065     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13066          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13067         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13068          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13069       // The to-be-promoted operands of this node have not yet been
13070       // promoted (this should be rare because we're going through the
13071       // list backward, but if one of the operands has several users in
13072       // this cluster of to-be-promoted nodes, it is possible).
13073       PromOpHandles.emplace_front(PromOp);
13074       continue;
13075     }
13076 
13077     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13078                                 PromOp.getNode()->op_end());
13079 
13080     // If there are any constant inputs, make sure they're replaced now.
13081     for (unsigned i = 0; i < 2; ++i)
13082       if (isa<ConstantSDNode>(Ops[C+i]))
13083         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13084 
13085     DAG.ReplaceAllUsesOfValueWith(PromOp,
13086       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13087   }
13088 
13089   // Now we're left with the initial truncation itself.
13090   if (N->getOpcode() == ISD::TRUNCATE)
13091     return N->getOperand(0);
13092 
13093   // Otherwise, this is a comparison. The operands to be compared have just
13094   // changed type (to i1), but everything else is the same.
13095   return SDValue(N, 0);
13096 }
13097 
13098 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13099                                                   DAGCombinerInfo &DCI) const {
13100   SelectionDAG &DAG = DCI.DAG;
13101   SDLoc dl(N);
13102 
13103   // If we're tracking CR bits, we need to be careful that we don't have:
13104   //   zext(binary-ops(trunc(x), trunc(y)))
13105   // or
13106   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13107   // such that we're unnecessarily moving things into CR bits that can more
13108   // efficiently stay in GPRs. Note that if we're not certain that the high
13109   // bits are set as required by the final extension, we still may need to do
13110   // some masking to get the proper behavior.
13111 
13112   // This same functionality is important on PPC64 when dealing with
13113   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13114   // the return values of functions. Because it is so similar, it is handled
13115   // here as well.
13116 
13117   if (N->getValueType(0) != MVT::i32 &&
13118       N->getValueType(0) != MVT::i64)
13119     return SDValue();
13120 
13121   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13122         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13123     return SDValue();
13124 
13125   if (N->getOperand(0).getOpcode() != ISD::AND &&
13126       N->getOperand(0).getOpcode() != ISD::OR  &&
13127       N->getOperand(0).getOpcode() != ISD::XOR &&
13128       N->getOperand(0).getOpcode() != ISD::SELECT &&
13129       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13130     return SDValue();
13131 
13132   SmallVector<SDValue, 4> Inputs;
13133   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13134   SmallPtrSet<SDNode *, 16> Visited;
13135 
13136   // Visit all inputs, collect all binary operations (and, or, xor and
13137   // select) that are all fed by truncations.
13138   while (!BinOps.empty()) {
13139     SDValue BinOp = BinOps.back();
13140     BinOps.pop_back();
13141 
13142     if (!Visited.insert(BinOp.getNode()).second)
13143       continue;
13144 
13145     PromOps.push_back(BinOp);
13146 
13147     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13148       // The condition of the select is not promoted.
13149       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13150         continue;
13151       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13152         continue;
13153 
13154       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13155           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13156         Inputs.push_back(BinOp.getOperand(i));
13157       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13158                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13159                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13160                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13161                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13162         BinOps.push_back(BinOp.getOperand(i));
13163       } else {
13164         // We have an input that is not a truncation or another binary
13165         // operation; we'll abort this transformation.
13166         return SDValue();
13167       }
13168     }
13169   }
13170 
13171   // The operands of a select that must be truncated when the select is
13172   // promoted because the operand is actually part of the to-be-promoted set.
13173   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13174 
13175   // Make sure that this is a self-contained cluster of operations (which
13176   // is not quite the same thing as saying that everything has only one
13177   // use).
13178   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13179     if (isa<ConstantSDNode>(Inputs[i]))
13180       continue;
13181 
13182     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13183                               UE = Inputs[i].getNode()->use_end();
13184          UI != UE; ++UI) {
13185       SDNode *User = *UI;
13186       if (User != N && !Visited.count(User))
13187         return SDValue();
13188 
13189       // If we're going to promote the non-output-value operand(s) or SELECT or
13190       // SELECT_CC, record them for truncation.
13191       if (User->getOpcode() == ISD::SELECT) {
13192         if (User->getOperand(0) == Inputs[i])
13193           SelectTruncOp[0].insert(std::make_pair(User,
13194                                     User->getOperand(0).getValueType()));
13195       } else if (User->getOpcode() == ISD::SELECT_CC) {
13196         if (User->getOperand(0) == Inputs[i])
13197           SelectTruncOp[0].insert(std::make_pair(User,
13198                                     User->getOperand(0).getValueType()));
13199         if (User->getOperand(1) == Inputs[i])
13200           SelectTruncOp[1].insert(std::make_pair(User,
13201                                     User->getOperand(1).getValueType()));
13202       }
13203     }
13204   }
13205 
13206   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13207     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13208                               UE = PromOps[i].getNode()->use_end();
13209          UI != UE; ++UI) {
13210       SDNode *User = *UI;
13211       if (User != N && !Visited.count(User))
13212         return SDValue();
13213 
13214       // If we're going to promote the non-output-value operand(s) or SELECT or
13215       // SELECT_CC, record them for truncation.
13216       if (User->getOpcode() == ISD::SELECT) {
13217         if (User->getOperand(0) == PromOps[i])
13218           SelectTruncOp[0].insert(std::make_pair(User,
13219                                     User->getOperand(0).getValueType()));
13220       } else if (User->getOpcode() == ISD::SELECT_CC) {
13221         if (User->getOperand(0) == PromOps[i])
13222           SelectTruncOp[0].insert(std::make_pair(User,
13223                                     User->getOperand(0).getValueType()));
13224         if (User->getOperand(1) == PromOps[i])
13225           SelectTruncOp[1].insert(std::make_pair(User,
13226                                     User->getOperand(1).getValueType()));
13227       }
13228     }
13229   }
13230 
13231   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13232   bool ReallyNeedsExt = false;
13233   if (N->getOpcode() != ISD::ANY_EXTEND) {
13234     // If all of the inputs are not already sign/zero extended, then
13235     // we'll still need to do that at the end.
13236     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13237       if (isa<ConstantSDNode>(Inputs[i]))
13238         continue;
13239 
13240       unsigned OpBits =
13241         Inputs[i].getOperand(0).getValueSizeInBits();
13242       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13243 
13244       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13245            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13246                                   APInt::getHighBitsSet(OpBits,
13247                                                         OpBits-PromBits))) ||
13248           (N->getOpcode() == ISD::SIGN_EXTEND &&
13249            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13250              (OpBits-(PromBits-1)))) {
13251         ReallyNeedsExt = true;
13252         break;
13253       }
13254     }
13255   }
13256 
13257   // Replace all inputs, either with the truncation operand, or a
13258   // truncation or extension to the final output type.
13259   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13260     // Constant inputs need to be replaced with the to-be-promoted nodes that
13261     // use them because they might have users outside of the cluster of
13262     // promoted nodes.
13263     if (isa<ConstantSDNode>(Inputs[i]))
13264       continue;
13265 
13266     SDValue InSrc = Inputs[i].getOperand(0);
13267     if (Inputs[i].getValueType() == N->getValueType(0))
13268       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13269     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13270       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13271         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13272     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13273       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13274         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13275     else
13276       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13277         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13278   }
13279 
13280   std::list<HandleSDNode> PromOpHandles;
13281   for (auto &PromOp : PromOps)
13282     PromOpHandles.emplace_back(PromOp);
13283 
13284   // Replace all operations (these are all the same, but have a different
13285   // (promoted) return type). DAG.getNode will validate that the types of
13286   // a binary operator match, so go through the list in reverse so that
13287   // we've likely promoted both operands first.
13288   while (!PromOpHandles.empty()) {
13289     SDValue PromOp = PromOpHandles.back().getValue();
13290     PromOpHandles.pop_back();
13291 
13292     unsigned C;
13293     switch (PromOp.getOpcode()) {
13294     default:             C = 0; break;
13295     case ISD::SELECT:    C = 1; break;
13296     case ISD::SELECT_CC: C = 2; break;
13297     }
13298 
13299     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13300          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13301         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13302          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13303       // The to-be-promoted operands of this node have not yet been
13304       // promoted (this should be rare because we're going through the
13305       // list backward, but if one of the operands has several users in
13306       // this cluster of to-be-promoted nodes, it is possible).
13307       PromOpHandles.emplace_front(PromOp);
13308       continue;
13309     }
13310 
13311     // For SELECT and SELECT_CC nodes, we do a similar check for any
13312     // to-be-promoted comparison inputs.
13313     if (PromOp.getOpcode() == ISD::SELECT ||
13314         PromOp.getOpcode() == ISD::SELECT_CC) {
13315       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13316            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13317           (SelectTruncOp[1].count(PromOp.getNode()) &&
13318            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13319         PromOpHandles.emplace_front(PromOp);
13320         continue;
13321       }
13322     }
13323 
13324     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13325                                 PromOp.getNode()->op_end());
13326 
13327     // If this node has constant inputs, then they'll need to be promoted here.
13328     for (unsigned i = 0; i < 2; ++i) {
13329       if (!isa<ConstantSDNode>(Ops[C+i]))
13330         continue;
13331       if (Ops[C+i].getValueType() == N->getValueType(0))
13332         continue;
13333 
13334       if (N->getOpcode() == ISD::SIGN_EXTEND)
13335         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13336       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13337         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13338       else
13339         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13340     }
13341 
13342     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13343     // truncate them again to the original value type.
13344     if (PromOp.getOpcode() == ISD::SELECT ||
13345         PromOp.getOpcode() == ISD::SELECT_CC) {
13346       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13347       if (SI0 != SelectTruncOp[0].end())
13348         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13349       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13350       if (SI1 != SelectTruncOp[1].end())
13351         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13352     }
13353 
13354     DAG.ReplaceAllUsesOfValueWith(PromOp,
13355       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13356   }
13357 
13358   // Now we're left with the initial extension itself.
13359   if (!ReallyNeedsExt)
13360     return N->getOperand(0);
13361 
13362   // To zero extend, just mask off everything except for the first bit (in the
13363   // i1 case).
13364   if (N->getOpcode() == ISD::ZERO_EXTEND)
13365     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13366                        DAG.getConstant(APInt::getLowBitsSet(
13367                                          N->getValueSizeInBits(0), PromBits),
13368                                        dl, N->getValueType(0)));
13369 
13370   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13371          "Invalid extension type");
13372   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13373   SDValue ShiftCst =
13374       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13375   return DAG.getNode(
13376       ISD::SRA, dl, N->getValueType(0),
13377       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13378       ShiftCst);
13379 }
13380 
13381 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13382                                         DAGCombinerInfo &DCI) const {
13383   assert(N->getOpcode() == ISD::SETCC &&
13384          "Should be called with a SETCC node");
13385 
13386   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13387   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13388     SDValue LHS = N->getOperand(0);
13389     SDValue RHS = N->getOperand(1);
13390 
13391     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13392     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13393         LHS.hasOneUse())
13394       std::swap(LHS, RHS);
13395 
13396     // x == 0-y --> x+y == 0
13397     // x != 0-y --> x+y != 0
13398     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13399         RHS.hasOneUse()) {
13400       SDLoc DL(N);
13401       SelectionDAG &DAG = DCI.DAG;
13402       EVT VT = N->getValueType(0);
13403       EVT OpVT = LHS.getValueType();
13404       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13405       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13406     }
13407   }
13408 
13409   return DAGCombineTruncBoolExt(N, DCI);
13410 }
13411 
13412 // Is this an extending load from an f32 to an f64?
13413 static bool isFPExtLoad(SDValue Op) {
13414   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13415     return LD->getExtensionType() == ISD::EXTLOAD &&
13416       Op.getValueType() == MVT::f64;
13417   return false;
13418 }
13419 
13420 /// Reduces the number of fp-to-int conversion when building a vector.
13421 ///
13422 /// If this vector is built out of floating to integer conversions,
13423 /// transform it to a vector built out of floating point values followed by a
13424 /// single floating to integer conversion of the vector.
13425 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13426 /// becomes (fptosi (build_vector ($A, $B, ...)))
13427 SDValue PPCTargetLowering::
13428 combineElementTruncationToVectorTruncation(SDNode *N,
13429                                            DAGCombinerInfo &DCI) const {
13430   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13431          "Should be called with a BUILD_VECTOR node");
13432 
13433   SelectionDAG &DAG = DCI.DAG;
13434   SDLoc dl(N);
13435 
13436   SDValue FirstInput = N->getOperand(0);
13437   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13438          "The input operand must be an fp-to-int conversion.");
13439 
13440   // This combine happens after legalization so the fp_to_[su]i nodes are
13441   // already converted to PPCSISD nodes.
13442   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13443   if (FirstConversion == PPCISD::FCTIDZ ||
13444       FirstConversion == PPCISD::FCTIDUZ ||
13445       FirstConversion == PPCISD::FCTIWZ ||
13446       FirstConversion == PPCISD::FCTIWUZ) {
13447     bool IsSplat = true;
13448     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13449       FirstConversion == PPCISD::FCTIWUZ;
13450     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13451     SmallVector<SDValue, 4> Ops;
13452     EVT TargetVT = N->getValueType(0);
13453     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13454       SDValue NextOp = N->getOperand(i);
13455       if (NextOp.getOpcode() != PPCISD::MFVSR)
13456         return SDValue();
13457       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13458       if (NextConversion != FirstConversion)
13459         return SDValue();
13460       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13461       // This is not valid if the input was originally double precision. It is
13462       // also not profitable to do unless this is an extending load in which
13463       // case doing this combine will allow us to combine consecutive loads.
13464       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13465         return SDValue();
13466       if (N->getOperand(i) != FirstInput)
13467         IsSplat = false;
13468     }
13469 
13470     // If this is a splat, we leave it as-is since there will be only a single
13471     // fp-to-int conversion followed by a splat of the integer. This is better
13472     // for 32-bit and smaller ints and neutral for 64-bit ints.
13473     if (IsSplat)
13474       return SDValue();
13475 
13476     // Now that we know we have the right type of node, get its operands
13477     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13478       SDValue In = N->getOperand(i).getOperand(0);
13479       if (Is32Bit) {
13480         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13481         // here, we know that all inputs are extending loads so this is safe).
13482         if (In.isUndef())
13483           Ops.push_back(DAG.getUNDEF(SrcVT));
13484         else {
13485           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13486                                       MVT::f32, In.getOperand(0),
13487                                       DAG.getIntPtrConstant(1, dl));
13488           Ops.push_back(Trunc);
13489         }
13490       } else
13491         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13492     }
13493 
13494     unsigned Opcode;
13495     if (FirstConversion == PPCISD::FCTIDZ ||
13496         FirstConversion == PPCISD::FCTIWZ)
13497       Opcode = ISD::FP_TO_SINT;
13498     else
13499       Opcode = ISD::FP_TO_UINT;
13500 
13501     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13502     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13503     return DAG.getNode(Opcode, dl, TargetVT, BV);
13504   }
13505   return SDValue();
13506 }
13507 
13508 /// Reduce the number of loads when building a vector.
13509 ///
13510 /// Building a vector out of multiple loads can be converted to a load
13511 /// of the vector type if the loads are consecutive. If the loads are
13512 /// consecutive but in descending order, a shuffle is added at the end
13513 /// to reorder the vector.
13514 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13515   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13516          "Should be called with a BUILD_VECTOR node");
13517 
13518   SDLoc dl(N);
13519 
13520   // Return early for non byte-sized type, as they can't be consecutive.
13521   if (!N->getValueType(0).getVectorElementType().isByteSized())
13522     return SDValue();
13523 
13524   bool InputsAreConsecutiveLoads = true;
13525   bool InputsAreReverseConsecutive = true;
13526   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13527   SDValue FirstInput = N->getOperand(0);
13528   bool IsRoundOfExtLoad = false;
13529 
13530   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13531       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13532     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13533     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13534   }
13535   // Not a build vector of (possibly fp_rounded) loads.
13536   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13537       N->getNumOperands() == 1)
13538     return SDValue();
13539 
13540   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13541     // If any inputs are fp_round(extload), they all must be.
13542     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13543       return SDValue();
13544 
13545     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13546       N->getOperand(i);
13547     if (NextInput.getOpcode() != ISD::LOAD)
13548       return SDValue();
13549 
13550     SDValue PreviousInput =
13551       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13552     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13553     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13554 
13555     // If any inputs are fp_round(extload), they all must be.
13556     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13557       return SDValue();
13558 
13559     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13560       InputsAreConsecutiveLoads = false;
13561     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13562       InputsAreReverseConsecutive = false;
13563 
13564     // Exit early if the loads are neither consecutive nor reverse consecutive.
13565     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13566       return SDValue();
13567   }
13568 
13569   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13570          "The loads cannot be both consecutive and reverse consecutive.");
13571 
13572   SDValue FirstLoadOp =
13573     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13574   SDValue LastLoadOp =
13575     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13576                        N->getOperand(N->getNumOperands()-1);
13577 
13578   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13579   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13580   if (InputsAreConsecutiveLoads) {
13581     assert(LD1 && "Input needs to be a LoadSDNode.");
13582     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13583                        LD1->getBasePtr(), LD1->getPointerInfo(),
13584                        LD1->getAlignment());
13585   }
13586   if (InputsAreReverseConsecutive) {
13587     assert(LDL && "Input needs to be a LoadSDNode.");
13588     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13589                                LDL->getBasePtr(), LDL->getPointerInfo(),
13590                                LDL->getAlignment());
13591     SmallVector<int, 16> Ops;
13592     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13593       Ops.push_back(i);
13594 
13595     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13596                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13597   }
13598   return SDValue();
13599 }
13600 
13601 // This function adds the required vector_shuffle needed to get
13602 // the elements of the vector extract in the correct position
13603 // as specified by the CorrectElems encoding.
13604 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13605                                       SDValue Input, uint64_t Elems,
13606                                       uint64_t CorrectElems) {
13607   SDLoc dl(N);
13608 
13609   unsigned NumElems = Input.getValueType().getVectorNumElements();
13610   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13611 
13612   // Knowing the element indices being extracted from the original
13613   // vector and the order in which they're being inserted, just put
13614   // them at element indices required for the instruction.
13615   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13616     if (DAG.getDataLayout().isLittleEndian())
13617       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13618     else
13619       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13620     CorrectElems = CorrectElems >> 8;
13621     Elems = Elems >> 8;
13622   }
13623 
13624   SDValue Shuffle =
13625       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13626                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13627 
13628   EVT VT = N->getValueType(0);
13629   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13630 
13631   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13632                                Input.getValueType().getVectorElementType(),
13633                                VT.getVectorNumElements());
13634   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13635                      DAG.getValueType(ExtVT));
13636 }
13637 
13638 // Look for build vector patterns where input operands come from sign
13639 // extended vector_extract elements of specific indices. If the correct indices
13640 // aren't used, add a vector shuffle to fix up the indices and create
13641 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13642 // during instruction selection.
13643 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13644   // This array encodes the indices that the vector sign extend instructions
13645   // extract from when extending from one type to another for both BE and LE.
13646   // The right nibble of each byte corresponds to the LE incides.
13647   // and the left nibble of each byte corresponds to the BE incides.
13648   // For example: 0x3074B8FC  byte->word
13649   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13650   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13651   // For example: 0x000070F8  byte->double word
13652   // For LE: the allowed indices are: 0x0,0x8
13653   // For BE: the allowed indices are: 0x7,0xF
13654   uint64_t TargetElems[] = {
13655       0x3074B8FC, // b->w
13656       0x000070F8, // b->d
13657       0x10325476, // h->w
13658       0x00003074, // h->d
13659       0x00001032, // w->d
13660   };
13661 
13662   uint64_t Elems = 0;
13663   int Index;
13664   SDValue Input;
13665 
13666   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13667     if (!Op)
13668       return false;
13669     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13670         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13671       return false;
13672 
13673     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13674     // of the right width.
13675     SDValue Extract = Op.getOperand(0);
13676     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13677       Extract = Extract.getOperand(0);
13678     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13679       return false;
13680 
13681     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13682     if (!ExtOp)
13683       return false;
13684 
13685     Index = ExtOp->getZExtValue();
13686     if (Input && Input != Extract.getOperand(0))
13687       return false;
13688 
13689     if (!Input)
13690       Input = Extract.getOperand(0);
13691 
13692     Elems = Elems << 8;
13693     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13694     Elems |= Index;
13695 
13696     return true;
13697   };
13698 
13699   // If the build vector operands aren't sign extended vector extracts,
13700   // of the same input vector, then return.
13701   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13702     if (!isSExtOfVecExtract(N->getOperand(i))) {
13703       return SDValue();
13704     }
13705   }
13706 
13707   // If the vector extract indicies are not correct, add the appropriate
13708   // vector_shuffle.
13709   int TgtElemArrayIdx;
13710   int InputSize = Input.getValueType().getScalarSizeInBits();
13711   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13712   if (InputSize + OutputSize == 40)
13713     TgtElemArrayIdx = 0;
13714   else if (InputSize + OutputSize == 72)
13715     TgtElemArrayIdx = 1;
13716   else if (InputSize + OutputSize == 48)
13717     TgtElemArrayIdx = 2;
13718   else if (InputSize + OutputSize == 80)
13719     TgtElemArrayIdx = 3;
13720   else if (InputSize + OutputSize == 96)
13721     TgtElemArrayIdx = 4;
13722   else
13723     return SDValue();
13724 
13725   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13726   CorrectElems = DAG.getDataLayout().isLittleEndian()
13727                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13728                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13729   if (Elems != CorrectElems) {
13730     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13731   }
13732 
13733   // Regular lowering will catch cases where a shuffle is not needed.
13734   return SDValue();
13735 }
13736 
13737 // Look for the pattern of a load from a narrow width to i128, feeding
13738 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13739 // (LXVRZX). This node represents a zero extending load that will be matched
13740 // to the Load VSX Vector Rightmost instructions.
13741 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13742   SDLoc DL(N);
13743 
13744   // This combine is only eligible for a BUILD_VECTOR of v1i128.
13745   if (N->getValueType(0) != MVT::v1i128)
13746     return SDValue();
13747 
13748   SDValue Operand = N->getOperand(0);
13749   // Proceed with the transformation if the operand to the BUILD_VECTOR
13750   // is a load instruction.
13751   if (Operand.getOpcode() != ISD::LOAD)
13752     return SDValue();
13753 
13754   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
13755   EVT MemoryType = LD->getMemoryVT();
13756 
13757   // This transformation is only valid if the we are loading either a byte,
13758   // halfword, word, or doubleword.
13759   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
13760                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
13761 
13762   // Ensure that the load from the narrow width is being zero extended to i128.
13763   if (!ValidLDType ||
13764       (LD->getExtensionType() != ISD::ZEXTLOAD &&
13765        LD->getExtensionType() != ISD::EXTLOAD))
13766     return SDValue();
13767 
13768   SDValue LoadOps[] = {
13769       LD->getChain(), LD->getBasePtr(),
13770       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
13771 
13772   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
13773                                  DAG.getVTList(MVT::v1i128, MVT::Other),
13774                                  LoadOps, MemoryType, LD->getMemOperand());
13775 }
13776 
13777 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13778                                                  DAGCombinerInfo &DCI) const {
13779   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13780          "Should be called with a BUILD_VECTOR node");
13781 
13782   SelectionDAG &DAG = DCI.DAG;
13783   SDLoc dl(N);
13784 
13785   if (!Subtarget.hasVSX())
13786     return SDValue();
13787 
13788   // The target independent DAG combiner will leave a build_vector of
13789   // float-to-int conversions intact. We can generate MUCH better code for
13790   // a float-to-int conversion of a vector of floats.
13791   SDValue FirstInput = N->getOperand(0);
13792   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13793     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13794     if (Reduced)
13795       return Reduced;
13796   }
13797 
13798   // If we're building a vector out of consecutive loads, just load that
13799   // vector type.
13800   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13801   if (Reduced)
13802     return Reduced;
13803 
13804   // If we're building a vector out of extended elements from another vector
13805   // we have P9 vector integer extend instructions. The code assumes legal
13806   // input types (i.e. it can't handle things like v4i16) so do not run before
13807   // legalization.
13808   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13809     Reduced = combineBVOfVecSExt(N, DAG);
13810     if (Reduced)
13811       return Reduced;
13812   }
13813 
13814   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
13815   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
13816   // is a load from <valid narrow width> to i128.
13817   if (Subtarget.isISA3_1()) {
13818     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
13819     if (BVOfZLoad)
13820       return BVOfZLoad;
13821   }
13822 
13823   if (N->getValueType(0) != MVT::v2f64)
13824     return SDValue();
13825 
13826   // Looking for:
13827   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13828   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13829       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13830     return SDValue();
13831   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13832       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13833     return SDValue();
13834   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13835     return SDValue();
13836 
13837   SDValue Ext1 = FirstInput.getOperand(0);
13838   SDValue Ext2 = N->getOperand(1).getOperand(0);
13839   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13840      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13841     return SDValue();
13842 
13843   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13844   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13845   if (!Ext1Op || !Ext2Op)
13846     return SDValue();
13847   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13848       Ext1.getOperand(0) != Ext2.getOperand(0))
13849     return SDValue();
13850 
13851   int FirstElem = Ext1Op->getZExtValue();
13852   int SecondElem = Ext2Op->getZExtValue();
13853   int SubvecIdx;
13854   if (FirstElem == 0 && SecondElem == 1)
13855     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13856   else if (FirstElem == 2 && SecondElem == 3)
13857     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13858   else
13859     return SDValue();
13860 
13861   SDValue SrcVec = Ext1.getOperand(0);
13862   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13863     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13864   return DAG.getNode(NodeType, dl, MVT::v2f64,
13865                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13866 }
13867 
13868 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13869                                               DAGCombinerInfo &DCI) const {
13870   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13871           N->getOpcode() == ISD::UINT_TO_FP) &&
13872          "Need an int -> FP conversion node here");
13873 
13874   if (useSoftFloat() || !Subtarget.has64BitSupport())
13875     return SDValue();
13876 
13877   SelectionDAG &DAG = DCI.DAG;
13878   SDLoc dl(N);
13879   SDValue Op(N, 0);
13880 
13881   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13882   // from the hardware.
13883   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13884     return SDValue();
13885   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13886       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13887     return SDValue();
13888 
13889   SDValue FirstOperand(Op.getOperand(0));
13890   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13891     (FirstOperand.getValueType() == MVT::i8 ||
13892      FirstOperand.getValueType() == MVT::i16);
13893   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13894     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13895     bool DstDouble = Op.getValueType() == MVT::f64;
13896     unsigned ConvOp = Signed ?
13897       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13898       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13899     SDValue WidthConst =
13900       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13901                             dl, false);
13902     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13903     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13904     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13905                                          DAG.getVTList(MVT::f64, MVT::Other),
13906                                          Ops, MVT::i8, LDN->getMemOperand());
13907 
13908     // For signed conversion, we need to sign-extend the value in the VSR
13909     if (Signed) {
13910       SDValue ExtOps[] = { Ld, WidthConst };
13911       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13912       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13913     } else
13914       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13915   }
13916 
13917 
13918   // For i32 intermediate values, unfortunately, the conversion functions
13919   // leave the upper 32 bits of the value are undefined. Within the set of
13920   // scalar instructions, we have no method for zero- or sign-extending the
13921   // value. Thus, we cannot handle i32 intermediate values here.
13922   if (Op.getOperand(0).getValueType() == MVT::i32)
13923     return SDValue();
13924 
13925   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13926          "UINT_TO_FP is supported only with FPCVT");
13927 
13928   // If we have FCFIDS, then use it when converting to single-precision.
13929   // Otherwise, convert to double-precision and then round.
13930   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13931                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13932                                                             : PPCISD::FCFIDS)
13933                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13934                                                             : PPCISD::FCFID);
13935   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13936                   ? MVT::f32
13937                   : MVT::f64;
13938 
13939   // If we're converting from a float, to an int, and back to a float again,
13940   // then we don't need the store/load pair at all.
13941   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13942        Subtarget.hasFPCVT()) ||
13943       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13944     SDValue Src = Op.getOperand(0).getOperand(0);
13945     if (Src.getValueType() == MVT::f32) {
13946       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13947       DCI.AddToWorklist(Src.getNode());
13948     } else if (Src.getValueType() != MVT::f64) {
13949       // Make sure that we don't pick up a ppc_fp128 source value.
13950       return SDValue();
13951     }
13952 
13953     unsigned FCTOp =
13954       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13955                                                         PPCISD::FCTIDUZ;
13956 
13957     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13958     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13959 
13960     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13961       FP = DAG.getNode(ISD::FP_ROUND, dl,
13962                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13963       DCI.AddToWorklist(FP.getNode());
13964     }
13965 
13966     return FP;
13967   }
13968 
13969   return SDValue();
13970 }
13971 
13972 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13973 // builtins) into loads with swaps.
13974 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13975                                               DAGCombinerInfo &DCI) const {
13976   SelectionDAG &DAG = DCI.DAG;
13977   SDLoc dl(N);
13978   SDValue Chain;
13979   SDValue Base;
13980   MachineMemOperand *MMO;
13981 
13982   switch (N->getOpcode()) {
13983   default:
13984     llvm_unreachable("Unexpected opcode for little endian VSX load");
13985   case ISD::LOAD: {
13986     LoadSDNode *LD = cast<LoadSDNode>(N);
13987     Chain = LD->getChain();
13988     Base = LD->getBasePtr();
13989     MMO = LD->getMemOperand();
13990     // If the MMO suggests this isn't a load of a full vector, leave
13991     // things alone.  For a built-in, we have to make the change for
13992     // correctness, so if there is a size problem that will be a bug.
13993     if (MMO->getSize() < 16)
13994       return SDValue();
13995     break;
13996   }
13997   case ISD::INTRINSIC_W_CHAIN: {
13998     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13999     Chain = Intrin->getChain();
14000     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14001     // us what we want. Get operand 2 instead.
14002     Base = Intrin->getOperand(2);
14003     MMO = Intrin->getMemOperand();
14004     break;
14005   }
14006   }
14007 
14008   MVT VecTy = N->getValueType(0).getSimpleVT();
14009 
14010   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14011   // aligned and the type is a vector with elements up to 4 bytes
14012   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14013       VecTy.getScalarSizeInBits() <= 32) {
14014     return SDValue();
14015   }
14016 
14017   SDValue LoadOps[] = { Chain, Base };
14018   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14019                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14020                                          LoadOps, MVT::v2f64, MMO);
14021 
14022   DCI.AddToWorklist(Load.getNode());
14023   Chain = Load.getValue(1);
14024   SDValue Swap = DAG.getNode(
14025       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14026   DCI.AddToWorklist(Swap.getNode());
14027 
14028   // Add a bitcast if the resulting load type doesn't match v2f64.
14029   if (VecTy != MVT::v2f64) {
14030     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14031     DCI.AddToWorklist(N.getNode());
14032     // Package {bitcast value, swap's chain} to match Load's shape.
14033     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14034                        N, Swap.getValue(1));
14035   }
14036 
14037   return Swap;
14038 }
14039 
14040 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14041 // builtins) into stores with swaps.
14042 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14043                                                DAGCombinerInfo &DCI) const {
14044   SelectionDAG &DAG = DCI.DAG;
14045   SDLoc dl(N);
14046   SDValue Chain;
14047   SDValue Base;
14048   unsigned SrcOpnd;
14049   MachineMemOperand *MMO;
14050 
14051   switch (N->getOpcode()) {
14052   default:
14053     llvm_unreachable("Unexpected opcode for little endian VSX store");
14054   case ISD::STORE: {
14055     StoreSDNode *ST = cast<StoreSDNode>(N);
14056     Chain = ST->getChain();
14057     Base = ST->getBasePtr();
14058     MMO = ST->getMemOperand();
14059     SrcOpnd = 1;
14060     // If the MMO suggests this isn't a store of a full vector, leave
14061     // things alone.  For a built-in, we have to make the change for
14062     // correctness, so if there is a size problem that will be a bug.
14063     if (MMO->getSize() < 16)
14064       return SDValue();
14065     break;
14066   }
14067   case ISD::INTRINSIC_VOID: {
14068     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14069     Chain = Intrin->getChain();
14070     // Intrin->getBasePtr() oddly does not get what we want.
14071     Base = Intrin->getOperand(3);
14072     MMO = Intrin->getMemOperand();
14073     SrcOpnd = 2;
14074     break;
14075   }
14076   }
14077 
14078   SDValue Src = N->getOperand(SrcOpnd);
14079   MVT VecTy = Src.getValueType().getSimpleVT();
14080 
14081   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14082   // aligned and the type is a vector with elements up to 4 bytes
14083   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14084       VecTy.getScalarSizeInBits() <= 32) {
14085     return SDValue();
14086   }
14087 
14088   // All stores are done as v2f64 and possible bit cast.
14089   if (VecTy != MVT::v2f64) {
14090     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14091     DCI.AddToWorklist(Src.getNode());
14092   }
14093 
14094   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14095                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14096   DCI.AddToWorklist(Swap.getNode());
14097   Chain = Swap.getValue(1);
14098   SDValue StoreOps[] = { Chain, Swap, Base };
14099   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14100                                           DAG.getVTList(MVT::Other),
14101                                           StoreOps, VecTy, MMO);
14102   DCI.AddToWorklist(Store.getNode());
14103   return Store;
14104 }
14105 
14106 // Handle DAG combine for STORE (FP_TO_INT F).
14107 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14108                                                DAGCombinerInfo &DCI) const {
14109 
14110   SelectionDAG &DAG = DCI.DAG;
14111   SDLoc dl(N);
14112   unsigned Opcode = N->getOperand(1).getOpcode();
14113 
14114   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14115          && "Not a FP_TO_INT Instruction!");
14116 
14117   SDValue Val = N->getOperand(1).getOperand(0);
14118   EVT Op1VT = N->getOperand(1).getValueType();
14119   EVT ResVT = Val.getValueType();
14120 
14121   if (!isTypeLegal(ResVT))
14122     return SDValue();
14123 
14124   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14125   bool ValidTypeForStoreFltAsInt =
14126         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14127          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14128 
14129   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14130       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14131     return SDValue();
14132 
14133   // Extend f32 values to f64
14134   if (ResVT.getScalarSizeInBits() == 32) {
14135     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14136     DCI.AddToWorklist(Val.getNode());
14137   }
14138 
14139   // Set signed or unsigned conversion opcode.
14140   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14141                           PPCISD::FP_TO_SINT_IN_VSR :
14142                           PPCISD::FP_TO_UINT_IN_VSR;
14143 
14144   Val = DAG.getNode(ConvOpcode,
14145                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14146   DCI.AddToWorklist(Val.getNode());
14147 
14148   // Set number of bytes being converted.
14149   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14150   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14151                     DAG.getIntPtrConstant(ByteSize, dl, false),
14152                     DAG.getValueType(Op1VT) };
14153 
14154   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14155           DAG.getVTList(MVT::Other), Ops,
14156           cast<StoreSDNode>(N)->getMemoryVT(),
14157           cast<StoreSDNode>(N)->getMemOperand());
14158 
14159   DCI.AddToWorklist(Val.getNode());
14160   return Val;
14161 }
14162 
14163 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14164   // Check that the source of the element keeps flipping
14165   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14166   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14167   for (int i = 1, e = Mask.size(); i < e; i++) {
14168     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14169       return false;
14170     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14171       return false;
14172     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14173   }
14174   return true;
14175 }
14176 
14177 static bool isSplatBV(SDValue Op) {
14178   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14179     return false;
14180   SDValue FirstOp;
14181 
14182   // Find first non-undef input.
14183   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14184     FirstOp = Op.getOperand(i);
14185     if (!FirstOp.isUndef())
14186       break;
14187   }
14188 
14189   // All inputs are undef or the same as the first non-undef input.
14190   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14191     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14192       return false;
14193   return true;
14194 }
14195 
14196 static SDValue isScalarToVec(SDValue Op) {
14197   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14198     return Op;
14199   if (Op.getOpcode() != ISD::BITCAST)
14200     return SDValue();
14201   Op = Op.getOperand(0);
14202   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14203     return Op;
14204   return SDValue();
14205 }
14206 
14207 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14208                                             int LHSMaxIdx, int RHSMinIdx,
14209                                             int RHSMaxIdx, int HalfVec) {
14210   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14211     int Idx = ShuffV[i];
14212     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14213       ShuffV[i] += HalfVec;
14214   }
14215   return;
14216 }
14217 
14218 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14219 // the original is:
14220 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14221 // In such a case, just change the shuffle mask to extract the element
14222 // from the permuted index.
14223 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14224   SDLoc dl(OrigSToV);
14225   EVT VT = OrigSToV.getValueType();
14226   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14227          "Expecting a SCALAR_TO_VECTOR here");
14228   SDValue Input = OrigSToV.getOperand(0);
14229 
14230   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14231     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14232     SDValue OrigVector = Input.getOperand(0);
14233 
14234     // Can't handle non-const element indices or different vector types
14235     // for the input to the extract and the output of the scalar_to_vector.
14236     if (Idx && VT == OrigVector.getValueType()) {
14237       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14238       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14239       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14240     }
14241   }
14242   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14243                      OrigSToV.getOperand(0));
14244 }
14245 
14246 // On little endian subtargets, combine shuffles such as:
14247 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14248 // into:
14249 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14250 // because the latter can be matched to a single instruction merge.
14251 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14252 // to put the value into element zero. Adjust the shuffle mask so that the
14253 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14254 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14255                                                 SelectionDAG &DAG) const {
14256   SDValue LHS = SVN->getOperand(0);
14257   SDValue RHS = SVN->getOperand(1);
14258   auto Mask = SVN->getMask();
14259   int NumElts = LHS.getValueType().getVectorNumElements();
14260   SDValue Res(SVN, 0);
14261   SDLoc dl(SVN);
14262 
14263   // None of these combines are useful on big endian systems since the ISA
14264   // already has a big endian bias.
14265   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14266     return Res;
14267 
14268   // If this is not a shuffle of a shuffle and the first element comes from
14269   // the second vector, canonicalize to the commuted form. This will make it
14270   // more likely to match one of the single instruction patterns.
14271   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14272       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14273     std::swap(LHS, RHS);
14274     Res = DAG.getCommutedVectorShuffle(*SVN);
14275     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14276   }
14277 
14278   // Adjust the shuffle mask if either input vector comes from a
14279   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14280   // form (to prevent the need for a swap).
14281   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14282   SDValue SToVLHS = isScalarToVec(LHS);
14283   SDValue SToVRHS = isScalarToVec(RHS);
14284   if (SToVLHS || SToVRHS) {
14285     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14286                             : SToVRHS.getValueType().getVectorNumElements();
14287     int NumEltsOut = ShuffV.size();
14288 
14289     // Initially assume that neither input is permuted. These will be adjusted
14290     // accordingly if either input is.
14291     int LHSMaxIdx = -1;
14292     int RHSMinIdx = -1;
14293     int RHSMaxIdx = -1;
14294     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14295 
14296     // Get the permuted scalar to vector nodes for the source(s) that come from
14297     // ISD::SCALAR_TO_VECTOR.
14298     if (SToVLHS) {
14299       // Set up the values for the shuffle vector fixup.
14300       LHSMaxIdx = NumEltsOut / NumEltsIn;
14301       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14302       if (SToVLHS.getValueType() != LHS.getValueType())
14303         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14304       LHS = SToVLHS;
14305     }
14306     if (SToVRHS) {
14307       RHSMinIdx = NumEltsOut;
14308       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14309       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14310       if (SToVRHS.getValueType() != RHS.getValueType())
14311         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14312       RHS = SToVRHS;
14313     }
14314 
14315     // Fix up the shuffle mask to reflect where the desired element actually is.
14316     // The minimum and maximum indices that correspond to element zero for both
14317     // the LHS and RHS are computed and will control which shuffle mask entries
14318     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14319     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14320     // HalfVec to refer to the corresponding element in the permuted vector.
14321     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14322                                     HalfVec);
14323     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14324 
14325     // We may have simplified away the shuffle. We won't be able to do anything
14326     // further with it here.
14327     if (!isa<ShuffleVectorSDNode>(Res))
14328       return Res;
14329     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14330   }
14331 
14332   // The common case after we commuted the shuffle is that the RHS is a splat
14333   // and we have elements coming in from the splat at indices that are not
14334   // conducive to using a merge.
14335   // Example:
14336   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14337   if (!isSplatBV(RHS))
14338     return Res;
14339 
14340   // We are looking for a mask such that all even elements are from
14341   // one vector and all odd elements from the other.
14342   if (!isAlternatingShuffMask(Mask, NumElts))
14343     return Res;
14344 
14345   // Adjust the mask so we are pulling in the same index from the splat
14346   // as the index from the interesting vector in consecutive elements.
14347   // Example (even elements from first vector):
14348   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14349   if (Mask[0] < NumElts)
14350     for (int i = 1, e = Mask.size(); i < e; i += 2)
14351       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14352   // Example (odd elements from first vector):
14353   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14354   else
14355     for (int i = 0, e = Mask.size(); i < e; i += 2)
14356       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14357 
14358   // If the RHS has undefs, we need to remove them since we may have created
14359   // a shuffle that adds those instead of the splat value.
14360   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14361   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14362 
14363   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14364   return Res;
14365 }
14366 
14367 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14368                                                 LSBaseSDNode *LSBase,
14369                                                 DAGCombinerInfo &DCI) const {
14370   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14371         "Not a reverse memop pattern!");
14372 
14373   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14374     auto Mask = SVN->getMask();
14375     int i = 0;
14376     auto I = Mask.rbegin();
14377     auto E = Mask.rend();
14378 
14379     for (; I != E; ++I) {
14380       if (*I != i)
14381         return false;
14382       i++;
14383     }
14384     return true;
14385   };
14386 
14387   SelectionDAG &DAG = DCI.DAG;
14388   EVT VT = SVN->getValueType(0);
14389 
14390   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14391     return SDValue();
14392 
14393   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14394   // See comment in PPCVSXSwapRemoval.cpp.
14395   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14396   if (!Subtarget.hasP9Vector())
14397     return SDValue();
14398 
14399   if(!IsElementReverse(SVN))
14400     return SDValue();
14401 
14402   if (LSBase->getOpcode() == ISD::LOAD) {
14403     SDLoc dl(SVN);
14404     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14405     return DAG.getMemIntrinsicNode(
14406         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14407         LSBase->getMemoryVT(), LSBase->getMemOperand());
14408   }
14409 
14410   if (LSBase->getOpcode() == ISD::STORE) {
14411     SDLoc dl(LSBase);
14412     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14413                           LSBase->getBasePtr()};
14414     return DAG.getMemIntrinsicNode(
14415         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14416         LSBase->getMemoryVT(), LSBase->getMemOperand());
14417   }
14418 
14419   llvm_unreachable("Expected a load or store node here");
14420 }
14421 
14422 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14423                                              DAGCombinerInfo &DCI) const {
14424   SelectionDAG &DAG = DCI.DAG;
14425   SDLoc dl(N);
14426   switch (N->getOpcode()) {
14427   default: break;
14428   case ISD::ADD:
14429     return combineADD(N, DCI);
14430   case ISD::SHL:
14431     return combineSHL(N, DCI);
14432   case ISD::SRA:
14433     return combineSRA(N, DCI);
14434   case ISD::SRL:
14435     return combineSRL(N, DCI);
14436   case ISD::MUL:
14437     return combineMUL(N, DCI);
14438   case ISD::FMA:
14439   case PPCISD::FNMSUB:
14440     return combineFMALike(N, DCI);
14441   case PPCISD::SHL:
14442     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14443         return N->getOperand(0);
14444     break;
14445   case PPCISD::SRL:
14446     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14447         return N->getOperand(0);
14448     break;
14449   case PPCISD::SRA:
14450     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14451       if (C->isNullValue() ||   //  0 >>s V -> 0.
14452           C->isAllOnesValue())    // -1 >>s V -> -1.
14453         return N->getOperand(0);
14454     }
14455     break;
14456   case ISD::SIGN_EXTEND:
14457   case ISD::ZERO_EXTEND:
14458   case ISD::ANY_EXTEND:
14459     return DAGCombineExtBoolTrunc(N, DCI);
14460   case ISD::TRUNCATE:
14461     return combineTRUNCATE(N, DCI);
14462   case ISD::SETCC:
14463     if (SDValue CSCC = combineSetCC(N, DCI))
14464       return CSCC;
14465     LLVM_FALLTHROUGH;
14466   case ISD::SELECT_CC:
14467     return DAGCombineTruncBoolExt(N, DCI);
14468   case ISD::SINT_TO_FP:
14469   case ISD::UINT_TO_FP:
14470     return combineFPToIntToFP(N, DCI);
14471   case ISD::VECTOR_SHUFFLE:
14472     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14473       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14474       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14475     }
14476     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14477   case ISD::STORE: {
14478 
14479     EVT Op1VT = N->getOperand(1).getValueType();
14480     unsigned Opcode = N->getOperand(1).getOpcode();
14481 
14482     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14483       SDValue Val= combineStoreFPToInt(N, DCI);
14484       if (Val)
14485         return Val;
14486     }
14487 
14488     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14489       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14490       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14491       if (Val)
14492         return Val;
14493     }
14494 
14495     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14496     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14497         N->getOperand(1).getNode()->hasOneUse() &&
14498         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14499          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14500 
14501       // STBRX can only handle simple types and it makes no sense to store less
14502       // two bytes in byte-reversed order.
14503       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14504       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14505         break;
14506 
14507       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14508       // Do an any-extend to 32-bits if this is a half-word input.
14509       if (BSwapOp.getValueType() == MVT::i16)
14510         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14511 
14512       // If the type of BSWAP operand is wider than stored memory width
14513       // it need to be shifted to the right side before STBRX.
14514       if (Op1VT.bitsGT(mVT)) {
14515         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14516         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14517                               DAG.getConstant(Shift, dl, MVT::i32));
14518         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14519         if (Op1VT == MVT::i64)
14520           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14521       }
14522 
14523       SDValue Ops[] = {
14524         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14525       };
14526       return
14527         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14528                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14529                                 cast<StoreSDNode>(N)->getMemOperand());
14530     }
14531 
14532     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14533     // So it can increase the chance of CSE constant construction.
14534     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14535         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14536       // Need to sign-extended to 64-bits to handle negative values.
14537       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14538       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14539                                     MemVT.getSizeInBits());
14540       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14541 
14542       // DAG.getTruncStore() can't be used here because it doesn't accept
14543       // the general (base + offset) addressing mode.
14544       // So we use UpdateNodeOperands and setTruncatingStore instead.
14545       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14546                              N->getOperand(3));
14547       cast<StoreSDNode>(N)->setTruncatingStore(true);
14548       return SDValue(N, 0);
14549     }
14550 
14551     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14552     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14553     if (Op1VT.isSimple()) {
14554       MVT StoreVT = Op1VT.getSimpleVT();
14555       if (Subtarget.needsSwapsForVSXMemOps() &&
14556           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14557            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14558         return expandVSXStoreForLE(N, DCI);
14559     }
14560     break;
14561   }
14562   case ISD::LOAD: {
14563     LoadSDNode *LD = cast<LoadSDNode>(N);
14564     EVT VT = LD->getValueType(0);
14565 
14566     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14567     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14568     if (VT.isSimple()) {
14569       MVT LoadVT = VT.getSimpleVT();
14570       if (Subtarget.needsSwapsForVSXMemOps() &&
14571           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14572            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14573         return expandVSXLoadForLE(N, DCI);
14574     }
14575 
14576     // We sometimes end up with a 64-bit integer load, from which we extract
14577     // two single-precision floating-point numbers. This happens with
14578     // std::complex<float>, and other similar structures, because of the way we
14579     // canonicalize structure copies. However, if we lack direct moves,
14580     // then the final bitcasts from the extracted integer values to the
14581     // floating-point numbers turn into store/load pairs. Even with direct moves,
14582     // just loading the two floating-point numbers is likely better.
14583     auto ReplaceTwoFloatLoad = [&]() {
14584       if (VT != MVT::i64)
14585         return false;
14586 
14587       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14588           LD->isVolatile())
14589         return false;
14590 
14591       //  We're looking for a sequence like this:
14592       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14593       //      t16: i64 = srl t13, Constant:i32<32>
14594       //    t17: i32 = truncate t16
14595       //  t18: f32 = bitcast t17
14596       //    t19: i32 = truncate t13
14597       //  t20: f32 = bitcast t19
14598 
14599       if (!LD->hasNUsesOfValue(2, 0))
14600         return false;
14601 
14602       auto UI = LD->use_begin();
14603       while (UI.getUse().getResNo() != 0) ++UI;
14604       SDNode *Trunc = *UI++;
14605       while (UI.getUse().getResNo() != 0) ++UI;
14606       SDNode *RightShift = *UI;
14607       if (Trunc->getOpcode() != ISD::TRUNCATE)
14608         std::swap(Trunc, RightShift);
14609 
14610       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14611           Trunc->getValueType(0) != MVT::i32 ||
14612           !Trunc->hasOneUse())
14613         return false;
14614       if (RightShift->getOpcode() != ISD::SRL ||
14615           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14616           RightShift->getConstantOperandVal(1) != 32 ||
14617           !RightShift->hasOneUse())
14618         return false;
14619 
14620       SDNode *Trunc2 = *RightShift->use_begin();
14621       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14622           Trunc2->getValueType(0) != MVT::i32 ||
14623           !Trunc2->hasOneUse())
14624         return false;
14625 
14626       SDNode *Bitcast = *Trunc->use_begin();
14627       SDNode *Bitcast2 = *Trunc2->use_begin();
14628 
14629       if (Bitcast->getOpcode() != ISD::BITCAST ||
14630           Bitcast->getValueType(0) != MVT::f32)
14631         return false;
14632       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14633           Bitcast2->getValueType(0) != MVT::f32)
14634         return false;
14635 
14636       if (Subtarget.isLittleEndian())
14637         std::swap(Bitcast, Bitcast2);
14638 
14639       // Bitcast has the second float (in memory-layout order) and Bitcast2
14640       // has the first one.
14641 
14642       SDValue BasePtr = LD->getBasePtr();
14643       if (LD->isIndexed()) {
14644         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14645                "Non-pre-inc AM on PPC?");
14646         BasePtr =
14647           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14648                       LD->getOffset());
14649       }
14650 
14651       auto MMOFlags =
14652           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14653       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14654                                       LD->getPointerInfo(), LD->getAlignment(),
14655                                       MMOFlags, LD->getAAInfo());
14656       SDValue AddPtr =
14657         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14658                     BasePtr, DAG.getIntPtrConstant(4, dl));
14659       SDValue FloatLoad2 = DAG.getLoad(
14660           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14661           LD->getPointerInfo().getWithOffset(4),
14662           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14663 
14664       if (LD->isIndexed()) {
14665         // Note that DAGCombine should re-form any pre-increment load(s) from
14666         // what is produced here if that makes sense.
14667         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14668       }
14669 
14670       DCI.CombineTo(Bitcast2, FloatLoad);
14671       DCI.CombineTo(Bitcast, FloatLoad2);
14672 
14673       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14674                                     SDValue(FloatLoad2.getNode(), 1));
14675       return true;
14676     };
14677 
14678     if (ReplaceTwoFloatLoad())
14679       return SDValue(N, 0);
14680 
14681     EVT MemVT = LD->getMemoryVT();
14682     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14683     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14684     if (LD->isUnindexed() && VT.isVector() &&
14685         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14686           // P8 and later hardware should just use LOAD.
14687           !Subtarget.hasP8Vector() &&
14688           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14689            VT == MVT::v4f32))) &&
14690         LD->getAlign() < ABIAlignment) {
14691       // This is a type-legal unaligned Altivec load.
14692       SDValue Chain = LD->getChain();
14693       SDValue Ptr = LD->getBasePtr();
14694       bool isLittleEndian = Subtarget.isLittleEndian();
14695 
14696       // This implements the loading of unaligned vectors as described in
14697       // the venerable Apple Velocity Engine overview. Specifically:
14698       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14699       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14700       //
14701       // The general idea is to expand a sequence of one or more unaligned
14702       // loads into an alignment-based permutation-control instruction (lvsl
14703       // or lvsr), a series of regular vector loads (which always truncate
14704       // their input address to an aligned address), and a series of
14705       // permutations.  The results of these permutations are the requested
14706       // loaded values.  The trick is that the last "extra" load is not taken
14707       // from the address you might suspect (sizeof(vector) bytes after the
14708       // last requested load), but rather sizeof(vector) - 1 bytes after the
14709       // last requested vector. The point of this is to avoid a page fault if
14710       // the base address happened to be aligned. This works because if the
14711       // base address is aligned, then adding less than a full vector length
14712       // will cause the last vector in the sequence to be (re)loaded.
14713       // Otherwise, the next vector will be fetched as you might suspect was
14714       // necessary.
14715 
14716       // We might be able to reuse the permutation generation from
14717       // a different base address offset from this one by an aligned amount.
14718       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14719       // optimization later.
14720       Intrinsic::ID Intr, IntrLD, IntrPerm;
14721       MVT PermCntlTy, PermTy, LDTy;
14722       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14723                             : Intrinsic::ppc_altivec_lvsl;
14724       IntrLD = Intrinsic::ppc_altivec_lvx;
14725       IntrPerm = Intrinsic::ppc_altivec_vperm;
14726       PermCntlTy = MVT::v16i8;
14727       PermTy = MVT::v4i32;
14728       LDTy = MVT::v4i32;
14729 
14730       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14731 
14732       // Create the new MMO for the new base load. It is like the original MMO,
14733       // but represents an area in memory almost twice the vector size centered
14734       // on the original address. If the address is unaligned, we might start
14735       // reading up to (sizeof(vector)-1) bytes below the address of the
14736       // original unaligned load.
14737       MachineFunction &MF = DAG.getMachineFunction();
14738       MachineMemOperand *BaseMMO =
14739         MF.getMachineMemOperand(LD->getMemOperand(),
14740                                 -(long)MemVT.getStoreSize()+1,
14741                                 2*MemVT.getStoreSize()-1);
14742 
14743       // Create the new base load.
14744       SDValue LDXIntID =
14745           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14746       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14747       SDValue BaseLoad =
14748         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14749                                 DAG.getVTList(PermTy, MVT::Other),
14750                                 BaseLoadOps, LDTy, BaseMMO);
14751 
14752       // Note that the value of IncOffset (which is provided to the next
14753       // load's pointer info offset value, and thus used to calculate the
14754       // alignment), and the value of IncValue (which is actually used to
14755       // increment the pointer value) are different! This is because we
14756       // require the next load to appear to be aligned, even though it
14757       // is actually offset from the base pointer by a lesser amount.
14758       int IncOffset = VT.getSizeInBits() / 8;
14759       int IncValue = IncOffset;
14760 
14761       // Walk (both up and down) the chain looking for another load at the real
14762       // (aligned) offset (the alignment of the other load does not matter in
14763       // this case). If found, then do not use the offset reduction trick, as
14764       // that will prevent the loads from being later combined (as they would
14765       // otherwise be duplicates).
14766       if (!findConsecutiveLoad(LD, DAG))
14767         --IncValue;
14768 
14769       SDValue Increment =
14770           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14771       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14772 
14773       MachineMemOperand *ExtraMMO =
14774         MF.getMachineMemOperand(LD->getMemOperand(),
14775                                 1, 2*MemVT.getStoreSize()-1);
14776       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14777       SDValue ExtraLoad =
14778         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14779                                 DAG.getVTList(PermTy, MVT::Other),
14780                                 ExtraLoadOps, LDTy, ExtraMMO);
14781 
14782       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14783         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14784 
14785       // Because vperm has a big-endian bias, we must reverse the order
14786       // of the input vectors and complement the permute control vector
14787       // when generating little endian code.  We have already handled the
14788       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14789       // and ExtraLoad here.
14790       SDValue Perm;
14791       if (isLittleEndian)
14792         Perm = BuildIntrinsicOp(IntrPerm,
14793                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14794       else
14795         Perm = BuildIntrinsicOp(IntrPerm,
14796                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14797 
14798       if (VT != PermTy)
14799         Perm = Subtarget.hasAltivec()
14800                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14801                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14802                                  DAG.getTargetConstant(1, dl, MVT::i64));
14803                                // second argument is 1 because this rounding
14804                                // is always exact.
14805 
14806       // The output of the permutation is our loaded result, the TokenFactor is
14807       // our new chain.
14808       DCI.CombineTo(N, Perm, TF);
14809       return SDValue(N, 0);
14810     }
14811     }
14812     break;
14813     case ISD::INTRINSIC_WO_CHAIN: {
14814       bool isLittleEndian = Subtarget.isLittleEndian();
14815       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14816       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14817                                            : Intrinsic::ppc_altivec_lvsl);
14818       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14819         SDValue Add = N->getOperand(1);
14820 
14821         int Bits = 4 /* 16 byte alignment */;
14822 
14823         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14824                                   APInt::getAllOnesValue(Bits /* alignment */)
14825                                       .zext(Add.getScalarValueSizeInBits()))) {
14826           SDNode *BasePtr = Add->getOperand(0).getNode();
14827           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14828                                     UE = BasePtr->use_end();
14829                UI != UE; ++UI) {
14830             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14831                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14832                     IID) {
14833               // We've found another LVSL/LVSR, and this address is an aligned
14834               // multiple of that one. The results will be the same, so use the
14835               // one we've just found instead.
14836 
14837               return SDValue(*UI, 0);
14838             }
14839           }
14840         }
14841 
14842         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14843           SDNode *BasePtr = Add->getOperand(0).getNode();
14844           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14845                UE = BasePtr->use_end(); UI != UE; ++UI) {
14846             if (UI->getOpcode() == ISD::ADD &&
14847                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14848                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14849                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14850                 (1ULL << Bits) == 0) {
14851               SDNode *OtherAdd = *UI;
14852               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14853                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14854                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14855                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14856                   return SDValue(*VI, 0);
14857                 }
14858               }
14859             }
14860           }
14861         }
14862       }
14863 
14864       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14865       // Expose the vabsduw/h/b opportunity for down stream
14866       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14867           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14868            IID == Intrinsic::ppc_altivec_vmaxsh ||
14869            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14870         SDValue V1 = N->getOperand(1);
14871         SDValue V2 = N->getOperand(2);
14872         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14873              V1.getSimpleValueType() == MVT::v8i16 ||
14874              V1.getSimpleValueType() == MVT::v16i8) &&
14875             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14876           // (0-a, a)
14877           if (V1.getOpcode() == ISD::SUB &&
14878               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14879               V1.getOperand(1) == V2) {
14880             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14881           }
14882           // (a, 0-a)
14883           if (V2.getOpcode() == ISD::SUB &&
14884               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14885               V2.getOperand(1) == V1) {
14886             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14887           }
14888           // (x-y, y-x)
14889           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14890               V1.getOperand(0) == V2.getOperand(1) &&
14891               V1.getOperand(1) == V2.getOperand(0)) {
14892             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14893           }
14894         }
14895       }
14896     }
14897 
14898     break;
14899   case ISD::INTRINSIC_W_CHAIN:
14900     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14901     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14902     if (Subtarget.needsSwapsForVSXMemOps()) {
14903       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14904       default:
14905         break;
14906       case Intrinsic::ppc_vsx_lxvw4x:
14907       case Intrinsic::ppc_vsx_lxvd2x:
14908         return expandVSXLoadForLE(N, DCI);
14909       }
14910     }
14911     break;
14912   case ISD::INTRINSIC_VOID:
14913     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14914     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14915     if (Subtarget.needsSwapsForVSXMemOps()) {
14916       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14917       default:
14918         break;
14919       case Intrinsic::ppc_vsx_stxvw4x:
14920       case Intrinsic::ppc_vsx_stxvd2x:
14921         return expandVSXStoreForLE(N, DCI);
14922       }
14923     }
14924     break;
14925   case ISD::BSWAP:
14926     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14927     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14928         N->getOperand(0).hasOneUse() &&
14929         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14930          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14931           N->getValueType(0) == MVT::i64))) {
14932       SDValue Load = N->getOperand(0);
14933       LoadSDNode *LD = cast<LoadSDNode>(Load);
14934       // Create the byte-swapping load.
14935       SDValue Ops[] = {
14936         LD->getChain(),    // Chain
14937         LD->getBasePtr(),  // Ptr
14938         DAG.getValueType(N->getValueType(0)) // VT
14939       };
14940       SDValue BSLoad =
14941         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14942                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14943                                               MVT::i64 : MVT::i32, MVT::Other),
14944                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14945 
14946       // If this is an i16 load, insert the truncate.
14947       SDValue ResVal = BSLoad;
14948       if (N->getValueType(0) == MVT::i16)
14949         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14950 
14951       // First, combine the bswap away.  This makes the value produced by the
14952       // load dead.
14953       DCI.CombineTo(N, ResVal);
14954 
14955       // Next, combine the load away, we give it a bogus result value but a real
14956       // chain result.  The result value is dead because the bswap is dead.
14957       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14958 
14959       // Return N so it doesn't get rechecked!
14960       return SDValue(N, 0);
14961     }
14962     break;
14963   case PPCISD::VCMP:
14964     // If a VCMPo node already exists with exactly the same operands as this
14965     // node, use its result instead of this node (VCMPo computes both a CR6 and
14966     // a normal output).
14967     //
14968     if (!N->getOperand(0).hasOneUse() &&
14969         !N->getOperand(1).hasOneUse() &&
14970         !N->getOperand(2).hasOneUse()) {
14971 
14972       // Scan all of the users of the LHS, looking for VCMPo's that match.
14973       SDNode *VCMPoNode = nullptr;
14974 
14975       SDNode *LHSN = N->getOperand(0).getNode();
14976       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14977            UI != E; ++UI)
14978         if (UI->getOpcode() == PPCISD::VCMPo &&
14979             UI->getOperand(1) == N->getOperand(1) &&
14980             UI->getOperand(2) == N->getOperand(2) &&
14981             UI->getOperand(0) == N->getOperand(0)) {
14982           VCMPoNode = *UI;
14983           break;
14984         }
14985 
14986       // If there is no VCMPo node, or if the flag value has a single use, don't
14987       // transform this.
14988       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14989         break;
14990 
14991       // Look at the (necessarily single) use of the flag value.  If it has a
14992       // chain, this transformation is more complex.  Note that multiple things
14993       // could use the value result, which we should ignore.
14994       SDNode *FlagUser = nullptr;
14995       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14996            FlagUser == nullptr; ++UI) {
14997         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14998         SDNode *User = *UI;
14999         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15000           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
15001             FlagUser = User;
15002             break;
15003           }
15004         }
15005       }
15006 
15007       // If the user is a MFOCRF instruction, we know this is safe.
15008       // Otherwise we give up for right now.
15009       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15010         return SDValue(VCMPoNode, 0);
15011     }
15012     break;
15013   case ISD::BRCOND: {
15014     SDValue Cond = N->getOperand(1);
15015     SDValue Target = N->getOperand(2);
15016 
15017     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15018         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15019           Intrinsic::loop_decrement) {
15020 
15021       // We now need to make the intrinsic dead (it cannot be instruction
15022       // selected).
15023       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15024       assert(Cond.getNode()->hasOneUse() &&
15025              "Counter decrement has more than one use");
15026 
15027       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15028                          N->getOperand(0), Target);
15029     }
15030   }
15031   break;
15032   case ISD::BR_CC: {
15033     // If this is a branch on an altivec predicate comparison, lower this so
15034     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15035     // lowering is done pre-legalize, because the legalizer lowers the predicate
15036     // compare down to code that is difficult to reassemble.
15037     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15038     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15039 
15040     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15041     // value. If so, pass-through the AND to get to the intrinsic.
15042     if (LHS.getOpcode() == ISD::AND &&
15043         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15044         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15045           Intrinsic::loop_decrement &&
15046         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15047         !isNullConstant(LHS.getOperand(1)))
15048       LHS = LHS.getOperand(0);
15049 
15050     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15051         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15052           Intrinsic::loop_decrement &&
15053         isa<ConstantSDNode>(RHS)) {
15054       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15055              "Counter decrement comparison is not EQ or NE");
15056 
15057       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15058       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15059                     (CC == ISD::SETNE && !Val);
15060 
15061       // We now need to make the intrinsic dead (it cannot be instruction
15062       // selected).
15063       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15064       assert(LHS.getNode()->hasOneUse() &&
15065              "Counter decrement has more than one use");
15066 
15067       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15068                          N->getOperand(0), N->getOperand(4));
15069     }
15070 
15071     int CompareOpc;
15072     bool isDot;
15073 
15074     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15075         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15076         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15077       assert(isDot && "Can't compare against a vector result!");
15078 
15079       // If this is a comparison against something other than 0/1, then we know
15080       // that the condition is never/always true.
15081       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15082       if (Val != 0 && Val != 1) {
15083         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15084           return N->getOperand(0);
15085         // Always !=, turn it into an unconditional branch.
15086         return DAG.getNode(ISD::BR, dl, MVT::Other,
15087                            N->getOperand(0), N->getOperand(4));
15088       }
15089 
15090       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15091 
15092       // Create the PPCISD altivec 'dot' comparison node.
15093       SDValue Ops[] = {
15094         LHS.getOperand(2),  // LHS of compare
15095         LHS.getOperand(3),  // RHS of compare
15096         DAG.getConstant(CompareOpc, dl, MVT::i32)
15097       };
15098       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15099       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
15100 
15101       // Unpack the result based on how the target uses it.
15102       PPC::Predicate CompOpc;
15103       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15104       default:  // Can't happen, don't crash on invalid number though.
15105       case 0:   // Branch on the value of the EQ bit of CR6.
15106         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15107         break;
15108       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15109         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15110         break;
15111       case 2:   // Branch on the value of the LT bit of CR6.
15112         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15113         break;
15114       case 3:   // Branch on the inverted value of the LT bit of CR6.
15115         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15116         break;
15117       }
15118 
15119       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15120                          DAG.getConstant(CompOpc, dl, MVT::i32),
15121                          DAG.getRegister(PPC::CR6, MVT::i32),
15122                          N->getOperand(4), CompNode.getValue(1));
15123     }
15124     break;
15125   }
15126   case ISD::BUILD_VECTOR:
15127     return DAGCombineBuildVector(N, DCI);
15128   case ISD::ABS:
15129     return combineABS(N, DCI);
15130   case ISD::VSELECT:
15131     return combineVSelect(N, DCI);
15132   }
15133 
15134   return SDValue();
15135 }
15136 
15137 SDValue
15138 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15139                                  SelectionDAG &DAG,
15140                                  SmallVectorImpl<SDNode *> &Created) const {
15141   // fold (sdiv X, pow2)
15142   EVT VT = N->getValueType(0);
15143   if (VT == MVT::i64 && !Subtarget.isPPC64())
15144     return SDValue();
15145   if ((VT != MVT::i32 && VT != MVT::i64) ||
15146       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15147     return SDValue();
15148 
15149   SDLoc DL(N);
15150   SDValue N0 = N->getOperand(0);
15151 
15152   bool IsNegPow2 = (-Divisor).isPowerOf2();
15153   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15154   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15155 
15156   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15157   Created.push_back(Op.getNode());
15158 
15159   if (IsNegPow2) {
15160     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15161     Created.push_back(Op.getNode());
15162   }
15163 
15164   return Op;
15165 }
15166 
15167 //===----------------------------------------------------------------------===//
15168 // Inline Assembly Support
15169 //===----------------------------------------------------------------------===//
15170 
15171 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15172                                                       KnownBits &Known,
15173                                                       const APInt &DemandedElts,
15174                                                       const SelectionDAG &DAG,
15175                                                       unsigned Depth) const {
15176   Known.resetAll();
15177   switch (Op.getOpcode()) {
15178   default: break;
15179   case PPCISD::LBRX: {
15180     // lhbrx is known to have the top bits cleared out.
15181     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15182       Known.Zero = 0xFFFF0000;
15183     break;
15184   }
15185   case ISD::INTRINSIC_WO_CHAIN: {
15186     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15187     default: break;
15188     case Intrinsic::ppc_altivec_vcmpbfp_p:
15189     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15190     case Intrinsic::ppc_altivec_vcmpequb_p:
15191     case Intrinsic::ppc_altivec_vcmpequh_p:
15192     case Intrinsic::ppc_altivec_vcmpequw_p:
15193     case Intrinsic::ppc_altivec_vcmpequd_p:
15194     case Intrinsic::ppc_altivec_vcmpgefp_p:
15195     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15196     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15197     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15198     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15199     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15200     case Intrinsic::ppc_altivec_vcmpgtub_p:
15201     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15202     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15203     case Intrinsic::ppc_altivec_vcmpgtud_p:
15204       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15205       break;
15206     }
15207   }
15208   }
15209 }
15210 
15211 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15212   switch (Subtarget.getCPUDirective()) {
15213   default: break;
15214   case PPC::DIR_970:
15215   case PPC::DIR_PWR4:
15216   case PPC::DIR_PWR5:
15217   case PPC::DIR_PWR5X:
15218   case PPC::DIR_PWR6:
15219   case PPC::DIR_PWR6X:
15220   case PPC::DIR_PWR7:
15221   case PPC::DIR_PWR8:
15222   case PPC::DIR_PWR9:
15223   case PPC::DIR_PWR10:
15224   case PPC::DIR_PWR_FUTURE: {
15225     if (!ML)
15226       break;
15227 
15228     if (!DisableInnermostLoopAlign32) {
15229       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15230       // so that we can decrease cache misses and branch-prediction misses.
15231       // Actual alignment of the loop will depend on the hotness check and other
15232       // logic in alignBlocks.
15233       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15234         return Align(32);
15235     }
15236 
15237     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15238 
15239     // For small loops (between 5 and 8 instructions), align to a 32-byte
15240     // boundary so that the entire loop fits in one instruction-cache line.
15241     uint64_t LoopSize = 0;
15242     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15243       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15244         LoopSize += TII->getInstSizeInBytes(*J);
15245         if (LoopSize > 32)
15246           break;
15247       }
15248 
15249     if (LoopSize > 16 && LoopSize <= 32)
15250       return Align(32);
15251 
15252     break;
15253   }
15254   }
15255 
15256   return TargetLowering::getPrefLoopAlignment(ML);
15257 }
15258 
15259 /// getConstraintType - Given a constraint, return the type of
15260 /// constraint it is for this target.
15261 PPCTargetLowering::ConstraintType
15262 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15263   if (Constraint.size() == 1) {
15264     switch (Constraint[0]) {
15265     default: break;
15266     case 'b':
15267     case 'r':
15268     case 'f':
15269     case 'd':
15270     case 'v':
15271     case 'y':
15272       return C_RegisterClass;
15273     case 'Z':
15274       // FIXME: While Z does indicate a memory constraint, it specifically
15275       // indicates an r+r address (used in conjunction with the 'y' modifier
15276       // in the replacement string). Currently, we're forcing the base
15277       // register to be r0 in the asm printer (which is interpreted as zero)
15278       // and forming the complete address in the second register. This is
15279       // suboptimal.
15280       return C_Memory;
15281     }
15282   } else if (Constraint == "wc") { // individual CR bits.
15283     return C_RegisterClass;
15284   } else if (Constraint == "wa" || Constraint == "wd" ||
15285              Constraint == "wf" || Constraint == "ws" ||
15286              Constraint == "wi" || Constraint == "ww") {
15287     return C_RegisterClass; // VSX registers.
15288   }
15289   return TargetLowering::getConstraintType(Constraint);
15290 }
15291 
15292 /// Examine constraint type and operand type and determine a weight value.
15293 /// This object must already have been set up with the operand type
15294 /// and the current alternative constraint selected.
15295 TargetLowering::ConstraintWeight
15296 PPCTargetLowering::getSingleConstraintMatchWeight(
15297     AsmOperandInfo &info, const char *constraint) const {
15298   ConstraintWeight weight = CW_Invalid;
15299   Value *CallOperandVal = info.CallOperandVal;
15300     // If we don't have a value, we can't do a match,
15301     // but allow it at the lowest weight.
15302   if (!CallOperandVal)
15303     return CW_Default;
15304   Type *type = CallOperandVal->getType();
15305 
15306   // Look at the constraint type.
15307   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15308     return CW_Register; // an individual CR bit.
15309   else if ((StringRef(constraint) == "wa" ||
15310             StringRef(constraint) == "wd" ||
15311             StringRef(constraint) == "wf") &&
15312            type->isVectorTy())
15313     return CW_Register;
15314   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15315     return CW_Register; // just hold 64-bit integers data.
15316   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15317     return CW_Register;
15318   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15319     return CW_Register;
15320 
15321   switch (*constraint) {
15322   default:
15323     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15324     break;
15325   case 'b':
15326     if (type->isIntegerTy())
15327       weight = CW_Register;
15328     break;
15329   case 'f':
15330     if (type->isFloatTy())
15331       weight = CW_Register;
15332     break;
15333   case 'd':
15334     if (type->isDoubleTy())
15335       weight = CW_Register;
15336     break;
15337   case 'v':
15338     if (type->isVectorTy())
15339       weight = CW_Register;
15340     break;
15341   case 'y':
15342     weight = CW_Register;
15343     break;
15344   case 'Z':
15345     weight = CW_Memory;
15346     break;
15347   }
15348   return weight;
15349 }
15350 
15351 std::pair<unsigned, const TargetRegisterClass *>
15352 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15353                                                 StringRef Constraint,
15354                                                 MVT VT) const {
15355   if (Constraint.size() == 1) {
15356     // GCC RS6000 Constraint Letters
15357     switch (Constraint[0]) {
15358     case 'b':   // R1-R31
15359       if (VT == MVT::i64 && Subtarget.isPPC64())
15360         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15361       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15362     case 'r':   // R0-R31
15363       if (VT == MVT::i64 && Subtarget.isPPC64())
15364         return std::make_pair(0U, &PPC::G8RCRegClass);
15365       return std::make_pair(0U, &PPC::GPRCRegClass);
15366     // 'd' and 'f' constraints are both defined to be "the floating point
15367     // registers", where one is for 32-bit and the other for 64-bit. We don't
15368     // really care overly much here so just give them all the same reg classes.
15369     case 'd':
15370     case 'f':
15371       if (Subtarget.hasSPE()) {
15372         if (VT == MVT::f32 || VT == MVT::i32)
15373           return std::make_pair(0U, &PPC::GPRCRegClass);
15374         if (VT == MVT::f64 || VT == MVT::i64)
15375           return std::make_pair(0U, &PPC::SPERCRegClass);
15376       } else {
15377         if (VT == MVT::f32 || VT == MVT::i32)
15378           return std::make_pair(0U, &PPC::F4RCRegClass);
15379         if (VT == MVT::f64 || VT == MVT::i64)
15380           return std::make_pair(0U, &PPC::F8RCRegClass);
15381       }
15382       break;
15383     case 'v':
15384       if (Subtarget.hasAltivec())
15385         return std::make_pair(0U, &PPC::VRRCRegClass);
15386       break;
15387     case 'y':   // crrc
15388       return std::make_pair(0U, &PPC::CRRCRegClass);
15389     }
15390   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15391     // An individual CR bit.
15392     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15393   } else if ((Constraint == "wa" || Constraint == "wd" ||
15394              Constraint == "wf" || Constraint == "wi") &&
15395              Subtarget.hasVSX()) {
15396     return std::make_pair(0U, &PPC::VSRCRegClass);
15397   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15398     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15399       return std::make_pair(0U, &PPC::VSSRCRegClass);
15400     else
15401       return std::make_pair(0U, &PPC::VSFRCRegClass);
15402   }
15403 
15404   // If we name a VSX register, we can't defer to the base class because it
15405   // will not recognize the correct register (their names will be VSL{0-31}
15406   // and V{0-31} so they won't match). So we match them here.
15407   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15408     int VSNum = atoi(Constraint.data() + 3);
15409     assert(VSNum >= 0 && VSNum <= 63 &&
15410            "Attempted to access a vsr out of range");
15411     if (VSNum < 32)
15412       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15413     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15414   }
15415   std::pair<unsigned, const TargetRegisterClass *> R =
15416       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15417 
15418   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15419   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15420   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15421   // register.
15422   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15423   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15424   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15425       PPC::GPRCRegClass.contains(R.first))
15426     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15427                             PPC::sub_32, &PPC::G8RCRegClass),
15428                           &PPC::G8RCRegClass);
15429 
15430   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15431   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15432     R.first = PPC::CR0;
15433     R.second = &PPC::CRRCRegClass;
15434   }
15435 
15436   return R;
15437 }
15438 
15439 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15440 /// vector.  If it is invalid, don't add anything to Ops.
15441 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15442                                                      std::string &Constraint,
15443                                                      std::vector<SDValue>&Ops,
15444                                                      SelectionDAG &DAG) const {
15445   SDValue Result;
15446 
15447   // Only support length 1 constraints.
15448   if (Constraint.length() > 1) return;
15449 
15450   char Letter = Constraint[0];
15451   switch (Letter) {
15452   default: break;
15453   case 'I':
15454   case 'J':
15455   case 'K':
15456   case 'L':
15457   case 'M':
15458   case 'N':
15459   case 'O':
15460   case 'P': {
15461     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15462     if (!CST) return; // Must be an immediate to match.
15463     SDLoc dl(Op);
15464     int64_t Value = CST->getSExtValue();
15465     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15466                          // numbers are printed as such.
15467     switch (Letter) {
15468     default: llvm_unreachable("Unknown constraint letter!");
15469     case 'I':  // "I" is a signed 16-bit constant.
15470       if (isInt<16>(Value))
15471         Result = DAG.getTargetConstant(Value, dl, TCVT);
15472       break;
15473     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15474       if (isShiftedUInt<16, 16>(Value))
15475         Result = DAG.getTargetConstant(Value, dl, TCVT);
15476       break;
15477     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15478       if (isShiftedInt<16, 16>(Value))
15479         Result = DAG.getTargetConstant(Value, dl, TCVT);
15480       break;
15481     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15482       if (isUInt<16>(Value))
15483         Result = DAG.getTargetConstant(Value, dl, TCVT);
15484       break;
15485     case 'M':  // "M" is a constant that is greater than 31.
15486       if (Value > 31)
15487         Result = DAG.getTargetConstant(Value, dl, TCVT);
15488       break;
15489     case 'N':  // "N" is a positive constant that is an exact power of two.
15490       if (Value > 0 && isPowerOf2_64(Value))
15491         Result = DAG.getTargetConstant(Value, dl, TCVT);
15492       break;
15493     case 'O':  // "O" is the constant zero.
15494       if (Value == 0)
15495         Result = DAG.getTargetConstant(Value, dl, TCVT);
15496       break;
15497     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15498       if (isInt<16>(-Value))
15499         Result = DAG.getTargetConstant(Value, dl, TCVT);
15500       break;
15501     }
15502     break;
15503   }
15504   }
15505 
15506   if (Result.getNode()) {
15507     Ops.push_back(Result);
15508     return;
15509   }
15510 
15511   // Handle standard constraint letters.
15512   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15513 }
15514 
15515 // isLegalAddressingMode - Return true if the addressing mode represented
15516 // by AM is legal for this target, for a load/store of the specified type.
15517 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15518                                               const AddrMode &AM, Type *Ty,
15519                                               unsigned AS,
15520                                               Instruction *I) const {
15521   // Vector type r+i form is supported since power9 as DQ form. We don't check
15522   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15523   // imm form is preferred and the offset can be adjusted to use imm form later
15524   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15525   // max offset to check legal addressing mode, we should be a little aggressive
15526   // to contain other offsets for that LSRUse.
15527   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15528     return false;
15529 
15530   // PPC allows a sign-extended 16-bit immediate field.
15531   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15532     return false;
15533 
15534   // No global is ever allowed as a base.
15535   if (AM.BaseGV)
15536     return false;
15537 
15538   // PPC only support r+r,
15539   switch (AM.Scale) {
15540   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15541     break;
15542   case 1:
15543     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15544       return false;
15545     // Otherwise we have r+r or r+i.
15546     break;
15547   case 2:
15548     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15549       return false;
15550     // Allow 2*r as r+r.
15551     break;
15552   default:
15553     // No other scales are supported.
15554     return false;
15555   }
15556 
15557   return true;
15558 }
15559 
15560 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15561                                            SelectionDAG &DAG) const {
15562   MachineFunction &MF = DAG.getMachineFunction();
15563   MachineFrameInfo &MFI = MF.getFrameInfo();
15564   MFI.setReturnAddressIsTaken(true);
15565 
15566   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15567     return SDValue();
15568 
15569   SDLoc dl(Op);
15570   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15571 
15572   // Make sure the function does not optimize away the store of the RA to
15573   // the stack.
15574   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15575   FuncInfo->setLRStoreRequired();
15576   bool isPPC64 = Subtarget.isPPC64();
15577   auto PtrVT = getPointerTy(MF.getDataLayout());
15578 
15579   if (Depth > 0) {
15580     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15581     SDValue Offset =
15582         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15583                         isPPC64 ? MVT::i64 : MVT::i32);
15584     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15585                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15586                        MachinePointerInfo());
15587   }
15588 
15589   // Just load the return address off the stack.
15590   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15591   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15592                      MachinePointerInfo());
15593 }
15594 
15595 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15596                                           SelectionDAG &DAG) const {
15597   SDLoc dl(Op);
15598   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15599 
15600   MachineFunction &MF = DAG.getMachineFunction();
15601   MachineFrameInfo &MFI = MF.getFrameInfo();
15602   MFI.setFrameAddressIsTaken(true);
15603 
15604   EVT PtrVT = getPointerTy(MF.getDataLayout());
15605   bool isPPC64 = PtrVT == MVT::i64;
15606 
15607   // Naked functions never have a frame pointer, and so we use r1. For all
15608   // other functions, this decision must be delayed until during PEI.
15609   unsigned FrameReg;
15610   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15611     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15612   else
15613     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15614 
15615   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15616                                          PtrVT);
15617   while (Depth--)
15618     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15619                             FrameAddr, MachinePointerInfo());
15620   return FrameAddr;
15621 }
15622 
15623 // FIXME? Maybe this could be a TableGen attribute on some registers and
15624 // this table could be generated automatically from RegInfo.
15625 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15626                                               const MachineFunction &MF) const {
15627   bool isPPC64 = Subtarget.isPPC64();
15628 
15629   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15630   if (!is64Bit && VT != LLT::scalar(32))
15631     report_fatal_error("Invalid register global variable type");
15632 
15633   Register Reg = StringSwitch<Register>(RegName)
15634                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15635                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15636                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15637                      .Default(Register());
15638 
15639   if (Reg)
15640     return Reg;
15641   report_fatal_error("Invalid register name global variable");
15642 }
15643 
15644 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15645   // 32-bit SVR4 ABI access everything as got-indirect.
15646   if (Subtarget.is32BitELFABI())
15647     return true;
15648 
15649   // AIX accesses everything indirectly through the TOC, which is similar to
15650   // the GOT.
15651   if (Subtarget.isAIXABI())
15652     return true;
15653 
15654   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15655   // If it is small or large code model, module locals are accessed
15656   // indirectly by loading their address from .toc/.got.
15657   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15658     return true;
15659 
15660   // JumpTable and BlockAddress are accessed as got-indirect.
15661   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15662     return true;
15663 
15664   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15665     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15666 
15667   return false;
15668 }
15669 
15670 bool
15671 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15672   // The PowerPC target isn't yet aware of offsets.
15673   return false;
15674 }
15675 
15676 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15677                                            const CallInst &I,
15678                                            MachineFunction &MF,
15679                                            unsigned Intrinsic) const {
15680   switch (Intrinsic) {
15681   case Intrinsic::ppc_altivec_lvx:
15682   case Intrinsic::ppc_altivec_lvxl:
15683   case Intrinsic::ppc_altivec_lvebx:
15684   case Intrinsic::ppc_altivec_lvehx:
15685   case Intrinsic::ppc_altivec_lvewx:
15686   case Intrinsic::ppc_vsx_lxvd2x:
15687   case Intrinsic::ppc_vsx_lxvw4x: {
15688     EVT VT;
15689     switch (Intrinsic) {
15690     case Intrinsic::ppc_altivec_lvebx:
15691       VT = MVT::i8;
15692       break;
15693     case Intrinsic::ppc_altivec_lvehx:
15694       VT = MVT::i16;
15695       break;
15696     case Intrinsic::ppc_altivec_lvewx:
15697       VT = MVT::i32;
15698       break;
15699     case Intrinsic::ppc_vsx_lxvd2x:
15700       VT = MVT::v2f64;
15701       break;
15702     default:
15703       VT = MVT::v4i32;
15704       break;
15705     }
15706 
15707     Info.opc = ISD::INTRINSIC_W_CHAIN;
15708     Info.memVT = VT;
15709     Info.ptrVal = I.getArgOperand(0);
15710     Info.offset = -VT.getStoreSize()+1;
15711     Info.size = 2*VT.getStoreSize()-1;
15712     Info.align = Align(1);
15713     Info.flags = MachineMemOperand::MOLoad;
15714     return true;
15715   }
15716   case Intrinsic::ppc_altivec_stvx:
15717   case Intrinsic::ppc_altivec_stvxl:
15718   case Intrinsic::ppc_altivec_stvebx:
15719   case Intrinsic::ppc_altivec_stvehx:
15720   case Intrinsic::ppc_altivec_stvewx:
15721   case Intrinsic::ppc_vsx_stxvd2x:
15722   case Intrinsic::ppc_vsx_stxvw4x: {
15723     EVT VT;
15724     switch (Intrinsic) {
15725     case Intrinsic::ppc_altivec_stvebx:
15726       VT = MVT::i8;
15727       break;
15728     case Intrinsic::ppc_altivec_stvehx:
15729       VT = MVT::i16;
15730       break;
15731     case Intrinsic::ppc_altivec_stvewx:
15732       VT = MVT::i32;
15733       break;
15734     case Intrinsic::ppc_vsx_stxvd2x:
15735       VT = MVT::v2f64;
15736       break;
15737     default:
15738       VT = MVT::v4i32;
15739       break;
15740     }
15741 
15742     Info.opc = ISD::INTRINSIC_VOID;
15743     Info.memVT = VT;
15744     Info.ptrVal = I.getArgOperand(1);
15745     Info.offset = -VT.getStoreSize()+1;
15746     Info.size = 2*VT.getStoreSize()-1;
15747     Info.align = Align(1);
15748     Info.flags = MachineMemOperand::MOStore;
15749     return true;
15750   }
15751   default:
15752     break;
15753   }
15754 
15755   return false;
15756 }
15757 
15758 /// It returns EVT::Other if the type should be determined using generic
15759 /// target-independent logic.
15760 EVT PPCTargetLowering::getOptimalMemOpType(
15761     const MemOp &Op, const AttributeList &FuncAttributes) const {
15762   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15763     // We should use Altivec/VSX loads and stores when available. For unaligned
15764     // addresses, unaligned VSX loads are only fast starting with the P8.
15765     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15766         (Op.isAligned(Align(16)) ||
15767          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15768       return MVT::v4i32;
15769   }
15770 
15771   if (Subtarget.isPPC64()) {
15772     return MVT::i64;
15773   }
15774 
15775   return MVT::i32;
15776 }
15777 
15778 /// Returns true if it is beneficial to convert a load of a constant
15779 /// to just the constant itself.
15780 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15781                                                           Type *Ty) const {
15782   assert(Ty->isIntegerTy());
15783 
15784   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15785   return !(BitSize == 0 || BitSize > 64);
15786 }
15787 
15788 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15789   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15790     return false;
15791   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15792   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15793   return NumBits1 == 64 && NumBits2 == 32;
15794 }
15795 
15796 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15797   if (!VT1.isInteger() || !VT2.isInteger())
15798     return false;
15799   unsigned NumBits1 = VT1.getSizeInBits();
15800   unsigned NumBits2 = VT2.getSizeInBits();
15801   return NumBits1 == 64 && NumBits2 == 32;
15802 }
15803 
15804 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15805   // Generally speaking, zexts are not free, but they are free when they can be
15806   // folded with other operations.
15807   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15808     EVT MemVT = LD->getMemoryVT();
15809     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15810          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15811         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15812          LD->getExtensionType() == ISD::ZEXTLOAD))
15813       return true;
15814   }
15815 
15816   // FIXME: Add other cases...
15817   //  - 32-bit shifts with a zext to i64
15818   //  - zext after ctlz, bswap, etc.
15819   //  - zext after and by a constant mask
15820 
15821   return TargetLowering::isZExtFree(Val, VT2);
15822 }
15823 
15824 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15825   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15826          "invalid fpext types");
15827   // Extending to float128 is not free.
15828   if (DestVT == MVT::f128)
15829     return false;
15830   return true;
15831 }
15832 
15833 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15834   return isInt<16>(Imm) || isUInt<16>(Imm);
15835 }
15836 
15837 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15838   return isInt<16>(Imm) || isUInt<16>(Imm);
15839 }
15840 
15841 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15842                                                        unsigned,
15843                                                        unsigned,
15844                                                        MachineMemOperand::Flags,
15845                                                        bool *Fast) const {
15846   if (DisablePPCUnaligned)
15847     return false;
15848 
15849   // PowerPC supports unaligned memory access for simple non-vector types.
15850   // Although accessing unaligned addresses is not as efficient as accessing
15851   // aligned addresses, it is generally more efficient than manual expansion,
15852   // and generally only traps for software emulation when crossing page
15853   // boundaries.
15854 
15855   if (!VT.isSimple())
15856     return false;
15857 
15858   if (VT.isFloatingPoint() && !VT.isVector() &&
15859       !Subtarget.allowsUnalignedFPAccess())
15860     return false;
15861 
15862   if (VT.getSimpleVT().isVector()) {
15863     if (Subtarget.hasVSX()) {
15864       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15865           VT != MVT::v4f32 && VT != MVT::v4i32)
15866         return false;
15867     } else {
15868       return false;
15869     }
15870   }
15871 
15872   if (VT == MVT::ppcf128)
15873     return false;
15874 
15875   if (Fast)
15876     *Fast = true;
15877 
15878   return true;
15879 }
15880 
15881 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15882                                                    EVT VT) const {
15883   return isFMAFasterThanFMulAndFAdd(
15884       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15885 }
15886 
15887 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15888                                                    Type *Ty) const {
15889   switch (Ty->getScalarType()->getTypeID()) {
15890   case Type::FloatTyID:
15891   case Type::DoubleTyID:
15892     return true;
15893   case Type::FP128TyID:
15894     return Subtarget.hasP9Vector();
15895   default:
15896     return false;
15897   }
15898 }
15899 
15900 // FIXME: add more patterns which are not profitable to hoist.
15901 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15902   if (!I->hasOneUse())
15903     return true;
15904 
15905   Instruction *User = I->user_back();
15906   assert(User && "A single use instruction with no uses.");
15907 
15908   switch (I->getOpcode()) {
15909   case Instruction::FMul: {
15910     // Don't break FMA, PowerPC prefers FMA.
15911     if (User->getOpcode() != Instruction::FSub &&
15912         User->getOpcode() != Instruction::FAdd)
15913       return true;
15914 
15915     const TargetOptions &Options = getTargetMachine().Options;
15916     const Function *F = I->getFunction();
15917     const DataLayout &DL = F->getParent()->getDataLayout();
15918     Type *Ty = User->getOperand(0)->getType();
15919 
15920     return !(
15921         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15922         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15923         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15924   }
15925   case Instruction::Load: {
15926     // Don't break "store (load float*)" pattern, this pattern will be combined
15927     // to "store (load int32)" in later InstCombine pass. See function
15928     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15929     // cycles than loading a 32 bit integer.
15930     LoadInst *LI = cast<LoadInst>(I);
15931     // For the loads that combineLoadToOperationType does nothing, like
15932     // ordered load, it should be profitable to hoist them.
15933     // For swifterror load, it can only be used for pointer to pointer type, so
15934     // later type check should get rid of this case.
15935     if (!LI->isUnordered())
15936       return true;
15937 
15938     if (User->getOpcode() != Instruction::Store)
15939       return true;
15940 
15941     if (I->getType()->getTypeID() != Type::FloatTyID)
15942       return true;
15943 
15944     return false;
15945   }
15946   default:
15947     return true;
15948   }
15949   return true;
15950 }
15951 
15952 const MCPhysReg *
15953 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15954   // LR is a callee-save register, but we must treat it as clobbered by any call
15955   // site. Hence we include LR in the scratch registers, which are in turn added
15956   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15957   // to CTR, which is used by any indirect call.
15958   static const MCPhysReg ScratchRegs[] = {
15959     PPC::X12, PPC::LR8, PPC::CTR8, 0
15960   };
15961 
15962   return ScratchRegs;
15963 }
15964 
15965 Register PPCTargetLowering::getExceptionPointerRegister(
15966     const Constant *PersonalityFn) const {
15967   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15968 }
15969 
15970 Register PPCTargetLowering::getExceptionSelectorRegister(
15971     const Constant *PersonalityFn) const {
15972   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15973 }
15974 
15975 bool
15976 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15977                      EVT VT , unsigned DefinedValues) const {
15978   if (VT == MVT::v2i64)
15979     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15980 
15981   if (Subtarget.hasVSX())
15982     return true;
15983 
15984   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15985 }
15986 
15987 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15988   if (DisableILPPref || Subtarget.enableMachineScheduler())
15989     return TargetLowering::getSchedulingPreference(N);
15990 
15991   return Sched::ILP;
15992 }
15993 
15994 // Create a fast isel object.
15995 FastISel *
15996 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15997                                   const TargetLibraryInfo *LibInfo) const {
15998   return PPC::createFastISel(FuncInfo, LibInfo);
15999 }
16000 
16001 // 'Inverted' means the FMA opcode after negating one multiplicand.
16002 // For example, (fma -a b c) = (fnmsub a b c)
16003 static unsigned invertFMAOpcode(unsigned Opc) {
16004   switch (Opc) {
16005   default:
16006     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16007   case ISD::FMA:
16008     return PPCISD::FNMSUB;
16009   case PPCISD::FNMSUB:
16010     return ISD::FMA;
16011   }
16012 }
16013 
16014 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16015                                                 bool LegalOps, bool OptForSize,
16016                                                 NegatibleCost &Cost,
16017                                                 unsigned Depth) const {
16018   if (Depth > SelectionDAG::MaxRecursionDepth)
16019     return SDValue();
16020 
16021   unsigned Opc = Op.getOpcode();
16022   EVT VT = Op.getValueType();
16023   SDNodeFlags Flags = Op.getNode()->getFlags();
16024 
16025   switch (Opc) {
16026   case PPCISD::FNMSUB:
16027     if (!Op.hasOneUse() || !isTypeLegal(VT))
16028       break;
16029 
16030     const TargetOptions &Options = getTargetMachine().Options;
16031     SDValue N0 = Op.getOperand(0);
16032     SDValue N1 = Op.getOperand(1);
16033     SDValue N2 = Op.getOperand(2);
16034     SDLoc Loc(Op);
16035 
16036     NegatibleCost N2Cost = NegatibleCost::Expensive;
16037     SDValue NegN2 =
16038         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16039 
16040     if (!NegN2)
16041       return SDValue();
16042 
16043     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16044     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16045     // These transformations may change sign of zeroes. For example,
16046     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16047     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16048       // Try and choose the cheaper one to negate.
16049       NegatibleCost N0Cost = NegatibleCost::Expensive;
16050       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16051                                            N0Cost, Depth + 1);
16052 
16053       NegatibleCost N1Cost = NegatibleCost::Expensive;
16054       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16055                                            N1Cost, Depth + 1);
16056 
16057       if (NegN0 && N0Cost <= N1Cost) {
16058         Cost = std::min(N0Cost, N2Cost);
16059         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16060       } else if (NegN1) {
16061         Cost = std::min(N1Cost, N2Cost);
16062         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16063       }
16064     }
16065 
16066     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16067     if (isOperationLegal(ISD::FMA, VT)) {
16068       Cost = N2Cost;
16069       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16070     }
16071 
16072     break;
16073   }
16074 
16075   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16076                                               Cost, Depth);
16077 }
16078 
16079 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16080 bool PPCTargetLowering::useLoadStackGuardNode() const {
16081   if (!Subtarget.isTargetLinux())
16082     return TargetLowering::useLoadStackGuardNode();
16083   return true;
16084 }
16085 
16086 // Override to disable global variable loading on Linux.
16087 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16088   if (!Subtarget.isTargetLinux())
16089     return TargetLowering::insertSSPDeclarations(M);
16090 }
16091 
16092 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16093                                      bool ForCodeSize) const {
16094   if (!VT.isSimple() || !Subtarget.hasVSX())
16095     return false;
16096 
16097   switch(VT.getSimpleVT().SimpleTy) {
16098   default:
16099     // For FP types that are currently not supported by PPC backend, return
16100     // false. Examples: f16, f80.
16101     return false;
16102   case MVT::f32:
16103   case MVT::f64:
16104     if (Subtarget.hasPrefixInstrs()) {
16105       // With prefixed instructions, we can materialize anything that can be
16106       // represented with a 32-bit immediate, not just positive zero.
16107       APFloat APFloatOfImm = Imm;
16108       return convertToNonDenormSingle(APFloatOfImm);
16109     }
16110     LLVM_FALLTHROUGH;
16111   case MVT::ppcf128:
16112     return Imm.isPosZero();
16113   }
16114 }
16115 
16116 // For vector shift operation op, fold
16117 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16118 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16119                                   SelectionDAG &DAG) {
16120   SDValue N0 = N->getOperand(0);
16121   SDValue N1 = N->getOperand(1);
16122   EVT VT = N0.getValueType();
16123   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16124   unsigned Opcode = N->getOpcode();
16125   unsigned TargetOpcode;
16126 
16127   switch (Opcode) {
16128   default:
16129     llvm_unreachable("Unexpected shift operation");
16130   case ISD::SHL:
16131     TargetOpcode = PPCISD::SHL;
16132     break;
16133   case ISD::SRL:
16134     TargetOpcode = PPCISD::SRL;
16135     break;
16136   case ISD::SRA:
16137     TargetOpcode = PPCISD::SRA;
16138     break;
16139   }
16140 
16141   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16142       N1->getOpcode() == ISD::AND)
16143     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16144       if (Mask->getZExtValue() == OpSizeInBits - 1)
16145         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16146 
16147   return SDValue();
16148 }
16149 
16150 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16151   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16152     return Value;
16153 
16154   SDValue N0 = N->getOperand(0);
16155   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16156   if (!Subtarget.isISA3_0() ||
16157       N0.getOpcode() != ISD::SIGN_EXTEND ||
16158       N0.getOperand(0).getValueType() != MVT::i32 ||
16159       CN1 == nullptr || N->getValueType(0) != MVT::i64)
16160     return SDValue();
16161 
16162   // We can't save an operation here if the value is already extended, and
16163   // the existing shift is easier to combine.
16164   SDValue ExtsSrc = N0.getOperand(0);
16165   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16166       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16167     return SDValue();
16168 
16169   SDLoc DL(N0);
16170   SDValue ShiftBy = SDValue(CN1, 0);
16171   // We want the shift amount to be i32 on the extswli, but the shift could
16172   // have an i64.
16173   if (ShiftBy.getValueType() == MVT::i64)
16174     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16175 
16176   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16177                          ShiftBy);
16178 }
16179 
16180 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16181   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16182     return Value;
16183 
16184   return SDValue();
16185 }
16186 
16187 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16188   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16189     return Value;
16190 
16191   return SDValue();
16192 }
16193 
16194 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16195 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16196 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16197 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16198 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16199                                  const PPCSubtarget &Subtarget) {
16200   if (!Subtarget.isPPC64())
16201     return SDValue();
16202 
16203   SDValue LHS = N->getOperand(0);
16204   SDValue RHS = N->getOperand(1);
16205 
16206   auto isZextOfCompareWithConstant = [](SDValue Op) {
16207     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16208         Op.getValueType() != MVT::i64)
16209       return false;
16210 
16211     SDValue Cmp = Op.getOperand(0);
16212     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16213         Cmp.getOperand(0).getValueType() != MVT::i64)
16214       return false;
16215 
16216     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16217       int64_t NegConstant = 0 - Constant->getSExtValue();
16218       // Due to the limitations of the addi instruction,
16219       // -C is required to be [-32768, 32767].
16220       return isInt<16>(NegConstant);
16221     }
16222 
16223     return false;
16224   };
16225 
16226   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16227   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16228 
16229   // If there is a pattern, canonicalize a zext operand to the RHS.
16230   if (LHSHasPattern && !RHSHasPattern)
16231     std::swap(LHS, RHS);
16232   else if (!LHSHasPattern && !RHSHasPattern)
16233     return SDValue();
16234 
16235   SDLoc DL(N);
16236   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16237   SDValue Cmp = RHS.getOperand(0);
16238   SDValue Z = Cmp.getOperand(0);
16239   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16240 
16241   assert(Constant && "Constant Should not be a null pointer.");
16242   int64_t NegConstant = 0 - Constant->getSExtValue();
16243 
16244   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16245   default: break;
16246   case ISD::SETNE: {
16247     //                                 when C == 0
16248     //                             --> addze X, (addic Z, -1).carry
16249     //                            /
16250     // add X, (zext(setne Z, C))--
16251     //                            \    when -32768 <= -C <= 32767 && C != 0
16252     //                             --> addze X, (addic (addi Z, -C), -1).carry
16253     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16254                               DAG.getConstant(NegConstant, DL, MVT::i64));
16255     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16256     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16257                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16258     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16259                        SDValue(Addc.getNode(), 1));
16260     }
16261   case ISD::SETEQ: {
16262     //                                 when C == 0
16263     //                             --> addze X, (subfic Z, 0).carry
16264     //                            /
16265     // add X, (zext(sete  Z, C))--
16266     //                            \    when -32768 <= -C <= 32767 && C != 0
16267     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16268     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16269                               DAG.getConstant(NegConstant, DL, MVT::i64));
16270     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16271     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16272                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16273     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16274                        SDValue(Subc.getNode(), 1));
16275     }
16276   }
16277 
16278   return SDValue();
16279 }
16280 
16281 // Transform
16282 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16283 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16284 // In this case both C1 and C2 must be known constants.
16285 // C1+C2 must fit into a 34 bit signed integer.
16286 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16287                                           const PPCSubtarget &Subtarget) {
16288   if (!Subtarget.isUsingPCRelativeCalls())
16289     return SDValue();
16290 
16291   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16292   // If we find that node try to cast the Global Address and the Constant.
16293   SDValue LHS = N->getOperand(0);
16294   SDValue RHS = N->getOperand(1);
16295 
16296   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16297     std::swap(LHS, RHS);
16298 
16299   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16300     return SDValue();
16301 
16302   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16303   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16304   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16305 
16306   // Check that both casts succeeded.
16307   if (!GSDN || !ConstNode)
16308     return SDValue();
16309 
16310   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16311   SDLoc DL(GSDN);
16312 
16313   // The signed int offset needs to fit in 34 bits.
16314   if (!isInt<34>(NewOffset))
16315     return SDValue();
16316 
16317   // The new global address is a copy of the old global address except
16318   // that it has the updated Offset.
16319   SDValue GA =
16320       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16321                                  NewOffset, GSDN->getTargetFlags());
16322   SDValue MatPCRel =
16323       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16324   return MatPCRel;
16325 }
16326 
16327 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16328   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16329     return Value;
16330 
16331   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16332     return Value;
16333 
16334   return SDValue();
16335 }
16336 
16337 // Detect TRUNCATE operations on bitcasts of float128 values.
16338 // What we are looking for here is the situtation where we extract a subset
16339 // of bits from a 128 bit float.
16340 // This can be of two forms:
16341 // 1) BITCAST of f128 feeding TRUNCATE
16342 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16343 // The reason this is required is because we do not have a legal i128 type
16344 // and so we want to prevent having to store the f128 and then reload part
16345 // of it.
16346 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16347                                            DAGCombinerInfo &DCI) const {
16348   // If we are using CRBits then try that first.
16349   if (Subtarget.useCRBits()) {
16350     // Check if CRBits did anything and return that if it did.
16351     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16352       return CRTruncValue;
16353   }
16354 
16355   SDLoc dl(N);
16356   SDValue Op0 = N->getOperand(0);
16357 
16358   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16359   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16360     EVT VT = N->getValueType(0);
16361     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16362       return SDValue();
16363     SDValue Sub = Op0.getOperand(0);
16364     if (Sub.getOpcode() == ISD::SUB) {
16365       SDValue SubOp0 = Sub.getOperand(0);
16366       SDValue SubOp1 = Sub.getOperand(1);
16367       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16368           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16369         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16370                                SubOp1.getOperand(0),
16371                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16372       }
16373     }
16374   }
16375 
16376   // Looking for a truncate of i128 to i64.
16377   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16378     return SDValue();
16379 
16380   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16381 
16382   // SRL feeding TRUNCATE.
16383   if (Op0.getOpcode() == ISD::SRL) {
16384     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16385     // The right shift has to be by 64 bits.
16386     if (!ConstNode || ConstNode->getZExtValue() != 64)
16387       return SDValue();
16388 
16389     // Switch the element number to extract.
16390     EltToExtract = EltToExtract ? 0 : 1;
16391     // Update Op0 past the SRL.
16392     Op0 = Op0.getOperand(0);
16393   }
16394 
16395   // BITCAST feeding a TRUNCATE possibly via SRL.
16396   if (Op0.getOpcode() == ISD::BITCAST &&
16397       Op0.getValueType() == MVT::i128 &&
16398       Op0.getOperand(0).getValueType() == MVT::f128) {
16399     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16400     return DCI.DAG.getNode(
16401         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16402         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16403   }
16404   return SDValue();
16405 }
16406 
16407 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16408   SelectionDAG &DAG = DCI.DAG;
16409 
16410   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16411   if (!ConstOpOrElement)
16412     return SDValue();
16413 
16414   // An imul is usually smaller than the alternative sequence for legal type.
16415   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16416       isOperationLegal(ISD::MUL, N->getValueType(0)))
16417     return SDValue();
16418 
16419   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16420     switch (this->Subtarget.getCPUDirective()) {
16421     default:
16422       // TODO: enhance the condition for subtarget before pwr8
16423       return false;
16424     case PPC::DIR_PWR8:
16425       //  type        mul     add    shl
16426       // scalar        4       1      1
16427       // vector        7       2      2
16428       return true;
16429     case PPC::DIR_PWR9:
16430     case PPC::DIR_PWR10:
16431     case PPC::DIR_PWR_FUTURE:
16432       //  type        mul     add    shl
16433       // scalar        5       2      2
16434       // vector        7       2      2
16435 
16436       // The cycle RATIO of related operations are showed as a table above.
16437       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16438       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16439       // are 4, it is always profitable; but for 3 instrs patterns
16440       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16441       // So we should only do it for vector type.
16442       return IsAddOne && IsNeg ? VT.isVector() : true;
16443     }
16444   };
16445 
16446   EVT VT = N->getValueType(0);
16447   SDLoc DL(N);
16448 
16449   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16450   bool IsNeg = MulAmt.isNegative();
16451   APInt MulAmtAbs = MulAmt.abs();
16452 
16453   if ((MulAmtAbs - 1).isPowerOf2()) {
16454     // (mul x, 2^N + 1) => (add (shl x, N), x)
16455     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16456 
16457     if (!IsProfitable(IsNeg, true, VT))
16458       return SDValue();
16459 
16460     SDValue Op0 = N->getOperand(0);
16461     SDValue Op1 =
16462         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16463                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16464     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16465 
16466     if (!IsNeg)
16467       return Res;
16468 
16469     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16470   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16471     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16472     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16473 
16474     if (!IsProfitable(IsNeg, false, VT))
16475       return SDValue();
16476 
16477     SDValue Op0 = N->getOperand(0);
16478     SDValue Op1 =
16479         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16480                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16481 
16482     if (!IsNeg)
16483       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16484     else
16485       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16486 
16487   } else {
16488     return SDValue();
16489   }
16490 }
16491 
16492 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16493 // in combiner since we need to check SD flags and other subtarget features.
16494 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16495                                           DAGCombinerInfo &DCI) const {
16496   SDValue N0 = N->getOperand(0);
16497   SDValue N1 = N->getOperand(1);
16498   SDValue N2 = N->getOperand(2);
16499   SDNodeFlags Flags = N->getFlags();
16500   EVT VT = N->getValueType(0);
16501   SelectionDAG &DAG = DCI.DAG;
16502   const TargetOptions &Options = getTargetMachine().Options;
16503   unsigned Opc = N->getOpcode();
16504   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16505   bool LegalOps = !DCI.isBeforeLegalizeOps();
16506   SDLoc Loc(N);
16507 
16508   if (!isOperationLegal(ISD::FMA, VT))
16509     return SDValue();
16510 
16511   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16512   // since (fnmsub a b c)=-0 while c-ab=+0.
16513   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16514     return SDValue();
16515 
16516   // (fma (fneg a) b c) => (fnmsub a b c)
16517   // (fnmsub (fneg a) b c) => (fma a b c)
16518   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16519     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16520 
16521   // (fma a (fneg b) c) => (fnmsub a b c)
16522   // (fnmsub a (fneg b) c) => (fma a b c)
16523   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16524     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16525 
16526   return SDValue();
16527 }
16528 
16529 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16530   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16531   if (!Subtarget.is64BitELFABI())
16532     return false;
16533 
16534   // If not a tail call then no need to proceed.
16535   if (!CI->isTailCall())
16536     return false;
16537 
16538   // If sibling calls have been disabled and tail-calls aren't guaranteed
16539   // there is no reason to duplicate.
16540   auto &TM = getTargetMachine();
16541   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16542     return false;
16543 
16544   // Can't tail call a function called indirectly, or if it has variadic args.
16545   const Function *Callee = CI->getCalledFunction();
16546   if (!Callee || Callee->isVarArg())
16547     return false;
16548 
16549   // Make sure the callee and caller calling conventions are eligible for tco.
16550   const Function *Caller = CI->getParent()->getParent();
16551   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16552                                            CI->getCallingConv()))
16553       return false;
16554 
16555   // If the function is local then we have a good chance at tail-calling it
16556   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16557 }
16558 
16559 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16560   if (!Subtarget.hasVSX())
16561     return false;
16562   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16563     return true;
16564   return VT == MVT::f32 || VT == MVT::f64 ||
16565     VT == MVT::v4f32 || VT == MVT::v2f64;
16566 }
16567 
16568 bool PPCTargetLowering::
16569 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16570   const Value *Mask = AndI.getOperand(1);
16571   // If the mask is suitable for andi. or andis. we should sink the and.
16572   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16573     // Can't handle constants wider than 64-bits.
16574     if (CI->getBitWidth() > 64)
16575       return false;
16576     int64_t ConstVal = CI->getZExtValue();
16577     return isUInt<16>(ConstVal) ||
16578       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16579   }
16580 
16581   // For non-constant masks, we can always use the record-form and.
16582   return true;
16583 }
16584 
16585 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16586 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16587 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16588 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16589 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16590 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16591   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16592   assert(Subtarget.hasP9Altivec() &&
16593          "Only combine this when P9 altivec supported!");
16594   EVT VT = N->getValueType(0);
16595   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16596     return SDValue();
16597 
16598   SelectionDAG &DAG = DCI.DAG;
16599   SDLoc dl(N);
16600   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16601     // Even for signed integers, if it's known to be positive (as signed
16602     // integer) due to zero-extended inputs.
16603     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16604     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16605     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16606          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16607         (SubOpcd1 == ISD::ZERO_EXTEND ||
16608          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16609       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16610                          N->getOperand(0)->getOperand(0),
16611                          N->getOperand(0)->getOperand(1),
16612                          DAG.getTargetConstant(0, dl, MVT::i32));
16613     }
16614 
16615     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16616     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16617         N->getOperand(0).hasOneUse()) {
16618       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16619                          N->getOperand(0)->getOperand(0),
16620                          N->getOperand(0)->getOperand(1),
16621                          DAG.getTargetConstant(1, dl, MVT::i32));
16622     }
16623   }
16624 
16625   return SDValue();
16626 }
16627 
16628 // For type v4i32/v8ii16/v16i8, transform
16629 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16630 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16631 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16632 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16633 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16634                                           DAGCombinerInfo &DCI) const {
16635   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16636   assert(Subtarget.hasP9Altivec() &&
16637          "Only combine this when P9 altivec supported!");
16638 
16639   SelectionDAG &DAG = DCI.DAG;
16640   SDLoc dl(N);
16641   SDValue Cond = N->getOperand(0);
16642   SDValue TrueOpnd = N->getOperand(1);
16643   SDValue FalseOpnd = N->getOperand(2);
16644   EVT VT = N->getOperand(1).getValueType();
16645 
16646   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16647       FalseOpnd.getOpcode() != ISD::SUB)
16648     return SDValue();
16649 
16650   // ABSD only available for type v4i32/v8i16/v16i8
16651   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16652     return SDValue();
16653 
16654   // At least to save one more dependent computation
16655   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16656     return SDValue();
16657 
16658   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16659 
16660   // Can only handle unsigned comparison here
16661   switch (CC) {
16662   default:
16663     return SDValue();
16664   case ISD::SETUGT:
16665   case ISD::SETUGE:
16666     break;
16667   case ISD::SETULT:
16668   case ISD::SETULE:
16669     std::swap(TrueOpnd, FalseOpnd);
16670     break;
16671   }
16672 
16673   SDValue CmpOpnd1 = Cond.getOperand(0);
16674   SDValue CmpOpnd2 = Cond.getOperand(1);
16675 
16676   // SETCC CmpOpnd1 CmpOpnd2 cond
16677   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16678   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16679   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16680       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16681       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16682       FalseOpnd.getOperand(1) == CmpOpnd1) {
16683     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16684                        CmpOpnd1, CmpOpnd2,
16685                        DAG.getTargetConstant(0, dl, MVT::i32));
16686   }
16687 
16688   return SDValue();
16689 }
16690